<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lamalharbi on Medium]]></title>
        <description><![CDATA[Stories by Lamalharbi on Medium]]></description>
        <link>https://medium.com/@lamalharbi?source=rss-87f03ec137ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Lamalharbi on Medium</title>
            <link>https://medium.com/@lamalharbi?source=rss-87f03ec137ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 00:16:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lamalharbi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Titanic — Machine Learning from Disaster]]></title>
            <link>https://lamalharbi.medium.com/titanic-machine-learning-from-disaster-90632b15ec49?source=rss-87f03ec137ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/90632b15ec49</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[titanic]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Lamalharbi]]></dc:creator>
            <pubDate>Fri, 02 Jul 2021 21:05:32 GMT</pubDate>
            <atom:updated>2021-07-02T21:05:32.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>Titanic — Machine Learning from Disaster</h3><p>Done by: <a href="https://medium.com/u/87f03ec137ee">Lamalharbi</a>, <a href="https://medium.com/u/cac8f1becf29">Monirah abdulaziz</a>, <a href="https://medium.com/u/20e1553c7e2c">Aisha Y Hakami</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*fmGf09MgkwHjY_j8-cHffA.jpeg" /></figure><p>In this project Notebook we will go through the whole process of cleaning the data and developing a machine learning model on the Titanic dataset which is one of the famous data sets which every Data Scientist explores at the start of their career and here we are. The dataset provides all the information on the fate of passengers on the Titanic, summarized according to sex, age, economic status (class), and survival.</p><p>In addition, we join the <a href="https://www.kaggle.com/c/titanic/overview">Titanic: Machine Learning from Disaster</a> challenge on Kaggle according to our work.</p><h3><strong>Import Libraries</strong></h3><pre>import pandas as pd<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt</pre><pre>%matplotlib inline<br>from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier<br>from sklearn.model_selection import cross_val_score, train_test_split, GridSearchCV<br>from sklearn.naive_bayes import GaussianNB<br>from sklearn.linear_model import SGDClassifier,Perceptron<br>from sklearn.metrics import classification_report, confusion_matrix<br>from sklearn.svm import SVC,LinearSVC</pre><pre># To ignore unwanted warnings<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h3>Data Wrangling</h3><p>We used the data after applying the neccessary cleaning in the Random Forest Lab by:</p><ul><li>Dealing with null values.</li><li>Gaining more information on text data.</li></ul><p>To look deeper see <a href="https://lamalharbi.medium.com/titanic-machine-learning-from-disaster-data-cleaning-ad0bb6ce1b87">Cleaning Post</a></p><pre>train = pd.read_csv(&#39;datasets/cleaned_train.csv&#39;)<br>test = pd.read_csv(&#39;datasets/cleaned_test.csv&#39;)</pre><h3>Data Dictionary</h3><p>Main features in the dataset before cleaning steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*3IzCPn9REOKdKhT7J4NEhQ.png" /></figure><h3>Exploratory Data Analysis</h3><p>The most important point in working with the data is to understand the it first, then try to find patterns in it by using the visualization because in the real-world, so it’s important to ask why this person particulary survived?, to answer we need to look deeper to the features and the relationship.</p><pre># grab the quantitative features<br>quan_train = list(train.loc[:,train.dtypes != &#39;object&#39;].columns.values)<br>quan_train.remove(&#39;Survived&#39;)</pre><pre># visualize the distribution of each numerical feature</pre><pre>temp = pd.melt(train.drop(&#39;Survived&#39;,axis=1), value_vars= quan_train)<br>grid = sns.FacetGrid(temp, col=&quot;variable&quot;,  col_wrap=5 , size=3.0, <br>                     aspect=1.0,sharex=False, sharey=False)<br>grid.map(sns.distplot, &quot;value&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKx4M7-SoiXRRt2dBNCiPQ.png" /></figure><h4>Observations</h4><ul><li>For the Age, SibSp,Parch, value, Embarked_Q, Fare, Cabin are positively skewed.</li><li>The Pclass, sex_male, and Embarked_S are negatively skewed.</li></ul><pre># selecting without ID<br>corr = train.iloc[:, 1:].corr()<br>plt.figure(figsize=(8, 8))<br>sns.heatmap(corr, vmax=1, square=True,annot=True,cmap = &#39;RdBu&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fgs3_BrOpcrIHO8W9NsYmQ.png" /></figure><pre># List the numerical features decendingly by correlation with Survived<br>cor_dict = corr[&#39;Survived&#39;].to_dict()<br>del cor_dict[&#39;Survived&#39;]<br>print(&quot;List the numerical features by their correlation with Survived:\n&quot;)<br>for ele in sorted(cor_dict.items(), key = lambda x: -abs(x[1])):<br>    print(&quot;{0}: \t{1}&quot;.format(*ele))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GQzosjhas5jnOMTea-gIg.png" /></figure><h4>Observations</h4><ul><li>The distribution of each variable with itself is shown on the diagonal</li><li>To see patterns the observable pattern is that all the variables correlate with each other. On the bottom of the diagonal : we can see the negative correlations.</li><li>On the top of the diagonal : the positive correlation is displayed.</li></ul><pre>sns.pairplot(train.drop(&quot;Name&quot;,axis = 1),hue = &quot;Survived&quot;,palette=&#39;RdBu&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*fiDgbXeoARVWjj7WnxkCug.png" /></figure><h4>Observations</h4><ul><li>The Pair plot helps us to understand the best set of features to explain a relationship between two variables</li><li>We still need to take a deeper look.</li></ul><pre># here we take only 4 features to  perform analysis.<br>sns.set_style(&quot;whitegrid&quot;);<br>sns.pairplot(train[[&quot;Survived&quot;,&quot;Pclass&quot;,&quot;Fare&quot;,&quot;Age&quot;]], hue=&quot;Survived&quot;, size=3);<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivssPLbVDX9NXD8mBfhS9g.png" /></figure><h4>Observarions</h4><ul><li>We can see that passengers who paid higher fare or travelling in upper class has a higher chances to survive.</li><li>According to the Age the young persons have a higher chance to survive than old peoples.</li><li>The picture might not very clear so lets take step towards uni-variate analysis to understand what exactly is happening</li></ul><h3>Uni-variate Analysis</h3><h4>1. Survived Feature</h4><pre># Countplot counts the each category of value and plot that.<br>sns.countplot(train[&#39;Survived&#39;],data = train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*zqi6F8ZcjsbfKhtqxfUL8Q.png" /></figure><h4>2. Pclass Feature</h4><pre>sns.countplot(train[&quot;Pclass&quot;],hue = train[&quot;Survived&quot;],data = train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*aqKH64Z77ge-ErwUumYMVw.png" /></figure><h4>Other features</h4><pre>plt.figure(1)<br>f, axarr = plt.subplots(3, 2, figsize=(10, 9))<br>Survived = train.Survived.values<br>axarr[0, 0].hist(train[&#39;Pclass&#39;].values,bins=3)<br>axarr[0, 0].set_title(&#39;Pclass&#39;)<br>axarr[0, 1].hist(train.Cabin.values,bins=2)<br>axarr[0, 1].set_title(&#39;Cabin&#39;)<br>axarr[1, 0].hist(train.Age.values, bins=5)<br>axarr[1, 0].set_title(&#39;Age&#39;)<br>axarr[1, 1].hist(train[&#39;Parch&#39;].values,bins=7)<br>axarr[1, 1].set_title(&#39;Parch&#39;)<br>axarr[2, 0].hist(train.Embarked_Q.values, bins=2)<br>axarr[2, 0].set_title(&#39;Embarked_Q&#39;)<br>axarr[2, 1].hist(train.Embarked_S.values, bins=2)<br>axarr[2, 1].set_title(&#39;Embarked_S&#39;)<br>f.text(-0.01, 0.5, &#39;Survived&#39;, va=&#39;center&#39;, rotation=&#39;vertical&#39;, fontsize = 18)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92kywz5S_zZrRv2oCfGP9g.png" /></figure><h4>Observations</h4><ul><li>The Class 3 have the highest survivors.</li><li>Passenger with age between 20–30 has high chance to survive.</li></ul><h3>Feature Engeneering</h3><p>For the Parch and SibSp we can use these columns to explore wether the passenger is traveled alone or with relatives.</p><pre># add relative<br>data = [train, test]<br>for dataset in data:<br>    dataset[&#39;relatives&#39;] = dataset[&#39;SibSp&#39;] + dataset[&#39;Parch&#39;]<br>    dataset.loc[dataset[&#39;relatives&#39;] &gt; 0, &#39;travelled_alone&#39;] = 0<br>    dataset.loc[dataset[&#39;relatives&#39;] == 0, &#39;travelled_alone&#39;] = 1</pre><p>To remove any noise might occur while training the models we decide to split the Age and Fare to quarter classes.</p><pre># add age and fare<br>train[&#39;CatAge&#39;] = pd.qcut(train.Age, q=4, labels=False )<br>train[&#39;CatFare&#39;]= pd.qcut(train.Fare, q=4, labels=False)</pre><pre>test[&#39;CatAge&#39;] = pd.qcut(test.Age, q=4, labels=False )<br>test[&#39;CatFare&#39;]= pd.qcut(test.Fare, q=4, labels=False)</pre><pre># Train: drop the features after extracting info<br>train = train.drop([&#39;SibSp&#39;,&#39;Parch&#39;], axis=1)<br>train = train.drop([&#39;Age&#39;, &#39;Fare&#39;], axis=1)</pre><pre># Test: drop the features after extracting info<br>test = test.drop([&#39;SibSp&#39;,&#39;Parch&#39;], axis=1)<br>test = test.drop([&#39;Age&#39;, &#39;Fare&#39;], axis=1)</pre><p>There’s a large variety of titles from the people on the ship.</p><p>We will make new features for Titles from Name column, with grouping the people according to Mr, Mrs .. etc.</p><pre># Extract titles from Name feature.<br>import re <br>def get_title(name):<br>    title_search = re.search(&#39; ([A-Za-z]+)\.&#39;, name)<br>    if title_search:<br>        return title_search.group(1)<br>    return &quot;&quot;</pre><pre>train[&#39;title&#39;]=train[&#39;Name&#39;].apply(get_title)<br>test[&#39;title&#39;]=test[&#39;Name&#39;].apply(get_title)</pre><pre>title_lev1=list(train[&#39;title&#39;].value_counts().reset_index()[&#39;index&#39;])<br>title_lev2=list(test[&#39;title&#39;].value_counts().reset_index()[&#39;index&#39;])</pre><pre>title_lev=list(set().union(title_lev1, title_lev2))<br># print(title_lev)</pre><pre>train[&#39;title&#39;]=pd.Categorical(train[&#39;title&#39;], categories=title_lev)<br>test[&#39;title&#39;]=pd.Categorical(test[&#39;title&#39;], categories=title_lev)</pre><pre>title_dum = pd.get_dummies(train[&#39;title&#39;],drop_first=True)<br>train = pd.concat([train, title_dum],axis=1)<br>train=train.drop([&#39;title&#39;], axis=1)</pre><pre># test <br>test_dum = pd.get_dummies(test[&#39;title&#39;],drop_first=True)<br>test = pd.concat([test, test_dum],axis=1)<br>test=test.drop([&#39;title&#39;], axis=1)</pre><pre>train=train.drop([&#39;Name&#39;], axis=1)<br>test=test.drop([&#39;Name&#39;], axis=1)</pre><h4>Correlation after feature engineering</h4><pre>corrmat = abs(train.iloc[:train.shape[0],:].corr())<br>plt.figure(figsize=(17, 8))<br>k = 15 #number of variables for heatmap<br>cols = corrmat.nlargest(k, &#39;Survived&#39;)[&#39;Survived&#39;].index<br>cm = np.corrcoef(train.iloc[:train.shape[0],:][cols].values.T)<br>sns.set(font_scale=1.50)<br>hm = sns.heatmap(cm, cbar=True, annot=True, square=True,<br>                 fmt=&#39;.2f&#39;, annot_kws={&#39;size&#39;: 10}, yticklabels=cols.values, xticklabels=cols.values,<br>                 cmap = &#39;RdBu&#39;, linecolor = &#39;white&#39;, linewidth = 1)<br>plt.title(&quot;Correlations between Survived and  features including dummy variables&quot;, fontsize =15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVNteLcIgKPF8qpJqYbbvA.png" /></figure><h3>Feature and Target</h3><pre>X_train = train[[&#39;Pclass&#39;,&#39;Cabin&#39;,&#39;sex_male&#39;,&#39;Embarked_Q&#39;,&#39;Embarked_S&#39;,&#39;relatives&#39;,&#39;travelled_alone&#39;,&#39;CatAge&#39;,&#39;CatFare&#39;, &#39;Miss&#39;, &#39;Mr&#39;,&#39;Mrs&#39;]]<br>y_train = train[&#39;Survived&#39;]<br>X_test = test[[&#39;Pclass&#39;,&#39;Cabin&#39;,&#39;sex_male&#39;,&#39;Embarked_Q&#39;,&#39;Embarked_S&#39;,&#39;relatives&#39;,&#39;travelled_alone&#39;,&#39;CatAge&#39;,&#39;CatFare&#39;, &#39;Miss&#39;, &#39;Mr&#39;,&#39;Mrs&#39;]]</pre><h3>Scaling</h3><pre>from sklearn.preprocessing import StandardScaler</pre><pre>s = StandardScaler()</pre><pre>X_s = pd.DataFrame(s.fit_transform(X_train) , columns=X_train.columns)<br>Xtest_s = pd.DataFrame(s.transform(X_test) , columns=X_test.columns)</pre><pre># plot<br>fig,ax = plt.subplots(figsize=(16,8))<br>sns.boxplot(data=X_s, orient=&#39;h&#39; , fliersize=2, linewidth=3, notch=True,saturation=0.5, ax=ax)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3RFeLl_Wm20YNLuXxQRwQ.png" /></figure><h3>Detect the Outliers</h3><pre>from scipy.stats import zscore<br>from scipy.stats import iqr<br>iqr(X_s, axis=0)<br>z = zscore(X_s)<br>outlier = X_s[(z &lt; 3).all(axis=1)]</pre><h3>Split the Data</h3><pre># split</pre><pre>from sklearn.model_selection import  train_test_split, cross_val_score</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X_s, y_train, test_size=0.3 , random_state = 101,stratify=y_train)</pre><h3>Baseline Model</h3><pre># CODE HERE PLEASE<br>basline_acc = y_train.value_counts()[0]/(y_train.value_counts()[0]+y_train.value_counts()[1])<br>print(f&quot;0: {basline_acc}&quot;)<br>basline_acc = y_train.value_counts()[1]/(y_train.value_counts()[0]+y_train.value_counts()[1])<br>print(f&quot;1: {basline_acc}&quot;)</pre><p>output:</p><pre>0: 0.6163723916532905<br>1: 0.38362760834670945</pre><h3>Models</h3><h4>Decision Tree</h4><pre>from sklearn.tree import DecisionTreeRegressor<br>regressor = DecisionTreeRegressor(splitter = &quot;random&quot;)<br>regressor.fit(X_train, y_train)<br>dtree_score=round(regressor.score(X_train,y_train)* 100, 2)<br>dtree_score</pre><p>output:</p><pre>74.35</pre><h4>KNN</h4><pre>from sklearn.neighbors import KNeighborsClassifier<br>knn = KNeighborsClassifier()<br>knn.fit(X_train,y_train)<br>knn_score=round(knn.score(X_train, y_train) * 100, 2)<br>knn_score</pre><p>output:</p><pre>87.0</pre><h4>KNN with Grid Search</h4><pre>#grid search for KNN<br>params = {<br>    &#39;n_neighbors&#39;:[1,4,6,8,10,5,20,19],<br>    &#39;algorithm&#39;:[ &#39;ball_tree&#39;, &#39;kd_tree&#39;, &#39;brute&#39;],<br>}<br>gs = GridSearchCV(knn, param_grid=params,  verbose = 1,n_jobs=-1)<br>gs.fit(X_train, y_train)<br>knn_score_gs=round(gs.best_score_ * 100, 2)<br>knn_score_gs</pre><p>output:</p><pre>83.3</pre><h4>Adabost</h4><pre>from sklearn.ensemble import RandomForestClassifier,  GradientBoostingClassifier , ExtraTreesClassifier , AdaBoostClassifier<br>gb= GradientBoostingClassifier()<br>gb.fit(X_train, y_train)<br>gb_score=round(gb.score(X_train,y_train) * 100, 2)<br>gb_score</pre><p>output:</p><pre>86.84</pre><h4>Adabost with Grid Search</h4><pre># grid search for adabost<br>param_grid = {&#39;learning_rate&#39;: [0.01],<br> &#39;max_depth&#39;: [3,5,6,7 ],<br> &#39;max_features&#39;: [&#39;auto&#39;],<br> &#39;min_samples_leaf&#39;: [15 ],<br> &#39;min_samples_split&#39;: [15],<br> &#39;n_estimators&#39;: [1500]}</pre><pre>grad = GridSearchCV(GradientBoostingClassifier(),<br>                           param_grid, cv=5, verbose= 1 , n_jobs=-1)<br>grad.fit(X_train , y_train)<br>gb_score_gs=round(grad.best_score_ * 100, 2)<br>gb_score_gs</pre><p>output:</p><pre>83.46</pre><h4>Random Forest with Grid Search</h4><pre>rf_params = {<br>   &#39;n_estimators&#39;: [3,5,4,8,9,10,11,12,13,14],<br>    &#39;max_depth&#39;: [1, 2, 3,4,6],<br>   &#39;criterion&#39;:[&#39;gini&#39;],<br>   &#39;min_samples_split&#39; : [3,5],   <br>   &#39;max_features&#39;:[4,13,2,8],<br>    &#39;bootstrap&#39;:[True,False]<br>}<br>rf_g = RandomForestClassifier(oob_score =True,random_state=1 )<br>gs = GridSearchCV(rf_g, param_grid=rf_params, cv=5, verbose = 1,n_jobs=-1)<br>gs.fit(X_train, y_train)<br>rf_score=round(gs.best_score_ * 100, 2)</pre><pre>rf_score</pre><p>output:</p><pre>85.07</pre><h4>Extra Tree with Grid Search</h4><pre>## extra tree<br>par = {&#39;bootstrap&#39;: [True],<br> &#39;max_depth&#39;: [12,10,4,6],<br> &#39;min_samples_leaf&#39;: [4,2,5,7],<br> &#39;min_samples_split&#39;: [3,3,4,5],<br> &#39;n_estimators&#39;: [8]}</pre><pre>ex = GridSearchCV(ExtraTreesClassifier(),<br>                   par , cv = 5 , verbose= 1  , n_jobs= -1)<br>ex.fit(X_train , y_train)<br>ex_score=round(ex.best_score_ * 100, 2)<br>ex_score</pre><p>output:</p><pre>82.34</pre><h4>SVM</h4><pre>from sklearn import svm<br>from sklearn.svm import SVC</pre><pre>param_grid = {&#39;C&#39;: [1000 , 10000],  <br>              &#39;gamma&#39;: [ 0.001,0.01], <br>              &#39;kernel&#39;: [  &#39;rbf&#39;],}  <br>  <br>sv = GridSearchCV(SVC(), param_grid, verbose = 3 , n_jobs=-1 , cv = 5) <br>  <br># fitting the model for grid search <br>sv.fit(X_train , y_train)<br>svm_score=round(sv.best_score_ * 100, 2)<br>svm_score</pre><p>output:</p><pre>84.59</pre><h4>Stochastic Gradient Descent</h4><pre>sgd = SGDClassifier()<br>sgd.fit(X_train, y_train)<br>Y_pred = sgd.predict(X_test)<br>sgd_score = round(sgd.score(X_train, y_train) * 100, 2)<br>sgd_score</pre><p>output:</p><pre>73.35</pre><h4>Linear svc</h4><pre>linear_svc = LinearSVC()<br>linear_svc.fit(X_train, y_train)<br>Y_pred = linear_svc.predict(X_test)<br>linear_svc_score = round(linear_svc.score(X_train, y_train) * 100, 2)<br>linear_svc_score</pre><p>output:</p><pre>82.83</pre><h4>Perceptron</h4><pre>perceptron = Perceptron()<br>perceptron.fit(X_train, y_train)<br>Y_pred = perceptron.predict(X_test)<br>perceptron_score = round(perceptron.score(X_train, y_train) * 100, 2)<br>perceptron_score</pre><h4>Scores</h4><p>list the scores and the models:</p><pre>models = pd.DataFrame({<br>    &#39;Model&#39;: [&#39;DecisionTreeRegressor&#39;, &#39;KNN&#39;,&#39;KNN with grid search&#39;, &#39;GradientBoostingClassifier&#39;, &#39;GradientBoostingClassifier with grid search&#39;<br>             , &#39;RandomForestClassifier&#39;, &#39;ExtraTreesClassifier&#39;, &#39;SVM&#39;, <br>              &#39;SGDClassifier&#39;, &#39;LinearSVC&#39;, <br>              &#39;Perceptron&#39;],<br>    &#39;Score&#39;: [dtree_score, knn_score,knn_score_gs, gb_score,gb_score_gs, <br>              rf_score, ex_score, svm_score, <br>              sgd_score, linear_svc_score, perceptron_score]})<br>models.sort_values(by=&#39;Score&#39;, ascending=False)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*OhRRXj-dCGOZoPF9e6yuXg.png" /></figure><h3>Kaggle submission scores</h3><p>Below is screenshots of the highest score we get in the Kaggle competition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWUHGE1MyJ0yvYttt22s8A.png" /></figure><h3>Conclusion</h3><p>At the end, Of course there is still more processes for improvement, like doing a more extensive feature engineering, by dive more into the features against each other by comparing and plotting to identifying and removing the outliers and noisy features. Moreover, the kaggle score could be improved by applying extensive hyperparameter tuning on the machine learning models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90632b15ec49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Recommendation System]]></title>
            <link>https://lamalharbi.medium.com/book-recommendation-system-cd978faa405b?source=rss-87f03ec137ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd978faa405b</guid>
            <category><![CDATA[recommendation-engine]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[goodreads]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[content-based]]></category>
            <dc:creator><![CDATA[Lamalharbi]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 09:11:01 GMT</pubDate>
            <atom:updated>2021-02-11T09:11:01.569Z</atom:updated>
            <content:encoded><![CDATA[<p>Done by: <a href="https://medium.com/u/cac8f1becf29">Monirah abdulaziz</a>, <a href="https://medium.com/u/20e1553c7e2c">Aisha Y Hakami</a>, <a href="https://medium.com/u/87f03ec137ee">Lamalharbi</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*gJlJ_NpZ33yLMh2fiALQUA.jpeg" /></figure><h3>Problem statement</h3><p>Usually when we plan to buy a book specially the scientific books, we normally ask about the goods ones, research the book domains, compare the books with similar or read the reviews so here the recommender system is the master of this problem.</p><h3><strong>Datasets</strong></h3><p>This project uses two datasets each one containing more that one thousand rows for books with different features. The data was obtained from Kaggle.</p><p><strong>The datasets</strong></p><ol><li><a href="https://www.kaggle.com/modhiibrahimalmannaa/1000-children-books-on-amazom">Children’s books in Amazon</a></li><li><a href="https://www.kaggle.com/muneeralhajri/goodreadscomputerbooks">Goodreads-Computer-Books</a></li></ol><h3>Amazon books</h3><p><strong>import libraries</strong></p><pre><em># Importing necessary libraries</em><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong><br><strong>from</strong> <strong>nltk.corpus</strong> <strong>import</strong> stopwords<br><strong>from</strong> <strong>sklearn.metrics.pairwise</strong> <strong>import</strong> linear_kernel<br><strong>from</strong> <strong>sklearn.feature_extraction.text</strong> <strong>import</strong> CountVectorizer<br><strong>from</strong> <strong>sklearn.feature_extraction.text</strong> <strong>import</strong> TfidfVectorizer<br><strong>from</strong> <strong>nltk.tokenize</strong> <strong>import</strong> RegexpTokenizer<br><strong>from</strong> <strong>sklearn.neighbors</strong> <strong>import</strong> NearestNeighbors<br><strong>import</strong> <strong>re</strong><br><strong>import</strong> <strong>string</strong><br><strong>import</strong> <strong>random</strong><br><strong>from</strong> <strong>PIL</strong> <strong>import</strong> Image<br><strong>import</strong> <strong>requests</strong><br><strong>from</strong> <strong>io</strong> <strong>import</strong> BytesIO<br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br>%matplotlib inline</pre><p><strong>Import and read dataset</strong></p><pre>df= pd.read_csv(&#39;amazon_books_data.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AH0w_eQtvefxYLb6D2bnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*nhfOS29qVkomzuZVhEjpPg.png" /></figure><p><strong>EDA and Cleaning</strong></p><p>regex the Description and the Product_Details features.</p><pre>df.Product_Details[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJ90NfanbCrjMCr2EW47wA.png" /><figcaption>Before regex</figcaption></figure><p>regex is refer to <em>regular expression</em> which is a special sequence of characters that helps to match or find other helpful strings or sets of strings, using a specialized syntax.</p><pre>df[&#39;Product_Details&#39;] = df.Product_Details.str.replace(r&#39;\n&#39;, &#39;&#39;, regex=True).str.strip()<br>df.Product_Details[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVg1Z2i3MkrmHm0cvbxUvg.png" /><figcaption>After regex</figcaption></figure><p>From the result we can clearly see that thePublisher, ISBN would be good features in the data, so we can extract it also using regex and save it as new features.</p><pre># Publisher feature<br>df[&#39;Publisher&#39;] = df[&#39;Product_Details&#39;].str.extract(&#39;((?&lt;=Publisher:).+?(?=;))&#39; ,expand=False) #&#39;ISBN-13:.+?(?= ;)<br>df[&#39;Publisher&#39;] = df.Publisher.str.replace(r&#39;-&#39;, &#39;&#39;, regex=True).str.strip() #Program</pre><pre># ISBN feature<br>df[&#39;ISBN&#39;] = df[&#39;Product_Details&#39;].str.extract(&#39;ISBN-13:(\d+-?\d*)&#39;, expand=False)##ISBN consists of 13 digits<br>df[&#39;ISBN&#39;] = df.ISBN.str.replace(r&#39;-&#39;, &#39;&#39;, regex=True).str.strip()</pre><p><strong>Check Nulls</strong></p><pre>hasNAN = df.isnull().sum()<br>hasNAN = hasNAN[hasNAN &gt; 0]<br>hasNAN = hasNAN.sort_values(ascending=False)<br>print(hasNAN,df.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*nOYB4w8wXxzw_hPBNgBgnw.png" /><figcaption>Null values</figcaption></figure><p><strong>Create new dataframe that consists of desired features</strong></p><pre>df1<strong>=</strong>df[[&#39;ISBN&#39;,&#39;Name&#39;,&#39;Description&#39;,&#39;Rating_out_of_5&#39;,&#39;No_of_Ratings&#39;,&#39;Publisher&#39;]]</pre><pre>df1.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIqjzQ7HflB8BaM8lhzIYA.png" /></figure><p><strong>Drop Nulls</strong></p><pre># Shape before dropping nulls<br>(1200, 6) </pre><pre>df1 = df1.dropna(how=&#39;any&#39;,axis=0)</pre><pre># Shape after dropping nulls <br>(873, 6)</pre><h3>Text Preprocessing</h3><p>Cleaning the book descriptions:</p><pre># Function for removing NonAscii characters<br>def _removeNonAscii(s):<br>    return &quot;&quot;.join(i for i in s if  ord(i)&lt;128)</pre><pre># Function for converting into lower case<br>def make_lower_case(text):<br>    return text.lower()</pre><pre># Function for removing stop words<br>def remove_stop_words(text):<br>    text = text.split()<br>    stops = set(stopwords.words(&quot;english&quot;))<br>    text = [w for w in text if not w in stops]<br>    text = &quot; &quot;.join(text)<br>    return text</pre><pre># Function for removing punctuation<br>def remove_punctuation(text):<br>    tokenizer = RegexpTokenizer(r&#39;\w+&#39;)<br>    text = tokenizer.tokenize(text)<br>    text = &quot; &quot;.join(text)<br>    return text</pre><pre># Function for removing the html tags<br>def remove_html(text):<br>    html_pattern = re.compile(&#39;&lt;.*?&gt;&#39;)<br>    return html_pattern.sub(r&#39;&#39;, text)</pre><pre># Applying all the functions in description and storing as a cleaned_desc<br>df1[&#39;cleaned_desc&#39;] = df1[&#39;Description&#39;].apply(_removeNonAscii)<br>df1[&#39;cleaned_desc&#39;] = df1.cleaned_desc.apply(func = make_lower_case)<br>df1[&#39;cleaned_desc&#39;] = df1.cleaned_desc.apply(func = remove_stop_words)<br>df1[&#39;cleaned_desc&#39;] = df1.cleaned_desc.apply(func=remove_punctuation)<br>df1[&#39;cleaned_desc&#39;] = df1.cleaned_desc.apply(func=remove_html)<br>df1.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nd3I3aI4ahCnKpuQUfI4nA.png" /></figure><h3>Recommendation engine</h3><p>Now we will build a recommendation engine using the book titles and descriptions. But first we need to convert each book title and description into vectors using TF-IDF and bigram. Our model will recommends a similar book based on title and description. Furthermore, we will define a function that takes the book title as input and returns the top five similar recommended books based on the title and description.</p><pre>tfidf <strong>=</strong> TfidfVectorizer(stop_words<strong>=</strong>&#39;english&#39;)</pre><pre>df1[&#39;cleaned_desc&#39;] <strong>=</strong> df1[&#39;cleaned_desc&#39;].fillna(&#39;&#39;)</pre><pre><em>#Construct the required TF-IDF matrix by applying the fit_transform method on the overview feature</em></pre><pre>overview_matrix <strong>=</strong> tfidf.fit_transform(df1[&#39;cleaned_desc&#39;])</pre><pre><em>#Output the shape of tfidf_matrix</em></pre><pre>overview_matrix.shape</pre><p>(873, 12175)</p><pre>similarity_matrix = linear_kernel(overview_matrix,overview_matrix)<br>similarity_matrix</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaXhkgFj9M48701AGw69RA.png" /></figure><pre>#book index mapping<br>mapping = pd.Series(df1.index,index =df1[&#39;Name&#39;])<br>mapping[:3]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*mI0zV16DWv__aLr8h4F9og.png" /></figure><pre>def recommend_books_based_on_plot(book_input):<br>    book_index = mapping[book_input]<br>    #get similarity values with other books<br>    #similarity_score is the list of index and similarity matrix<br>    similarity_score = list(enumerate(similarity_matrix[book_index]))<br>    #sort in descending order the similarity score of book inputted with all the other books<br>    similarity_score = sorted(similarity_score, key=lambda x: x[1], reverse=True)<br>    # Get the scores of the 5 most similar books. Ignore the first book.<br>    similarity_score = similarity_score[1:6]<br>    #return book names using the mapping series<br>    book_indices = [i[0] for i in similarity_score]<br>    return (df1[&#39;Name&#39;].iloc[book_indices])</pre><h3>Test the model</h3><p>Let&#39;s now try to get a recommendation for the book ‘If Animals Kissed Good Night’ from the above recommendation function and see what it outputs.</p><pre>recommend_books_based_on_plot(&#39;If Animals Kissed Good Night&#39;).to_frame()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*YIpz9GBzkM7HVG5rjGijhw.png" /></figure><p>In[31]:</p><pre>df1.Description[649]</pre><p>Out[31]:</p><pre>&quot;A must-have board book for all babies. Good night, Gorilla. Good night, Elephant.  It&#39;s bedtime at the zoo, and all the animals are going to sleep. Or are they? Who&#39;s that short, furry guy with the key in his hand and the mischievous grin? Good night, Giraffe. Good night, Hyena.  Sneak along behind the zookeeper&#39;s back, and see who gets the last laugh in this riotous good-night romp.&quot;</pre><p>In [32]:</p><pre>df1.Description[458]</pre><p>Out[32]:</p><pre>&#39;Shaped, die-cut, picture-changing pages add a subtly interactive element to this peaceful, rhyming bedtime book―say &quot;Night, night&quot; and turn the page to watch the animals transform from being awake to asleep.It’s nighttime down on the farm. The animals are in the barn and it’s time to say a soft and cozy, &quot;Night, night.&quot; Say goodnight to the horse, the dog, and all their farm friends, as you turn the shaped pages and watch as the animals go to sleep, one by one. The gentle rhymes and sleepy tone make Night Night Farm perfect for settling your little one into bed and ending with your own, quiet, &quot;Night, night.&quot; With irresistibly sweet illustrations and a magical sky of glow-in-the-dark stars, Night Night Farm is the perfect way to end the day.&#39;</pre><p>We can observe from the descriptions that we can see that the recommender books have similar points in the stories from the &#39;If Animals Kissed Good Nightbook.</p><h3>Goodreads</h3><p><strong>Import and read dataset</strong></p><pre>df= pd.read_csv(&#39;goodreads_books_data.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGhaXWnLpiyzieo8fqKReA.png" /></figure><p><strong>Check Nulls</strong></p><pre>hasNAN <strong>=</strong> df.isnull().sum()<br>hasNAN <strong>=</strong> hasNAN[hasNAN <strong>&gt;</strong> 0]hasNAN <strong>=</strong> hasNAN.sort_values(ascending<strong>=False</strong>)<br>print(hasNAN,df.shape)</pre><p>Series([], dtype: int64) (1234, 10)</p><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*_sMX6aXPez1EYkM3-s0cmg.png" /></figure><h3>EDA</h3><p>Since the Book_Id column is as in index we will drop it and generate a new ID</p><pre>df.drop([&#39;Book_Id&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><ul><li>Check duplicates and drop if exists.</li></ul><pre>df.shape</pre><p>(1234, 9)</p><pre>df[df[&#39;book_Title&#39;]<strong>==</strong>&#39;Anime and the Visual Novel: Narrative Structure Design and Play at the Crossroads of Animation and Computer Games&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vcy0yrcqk_2L99pBJ-OxA.png" /></figure><pre>df.drop_duplicates(inplace<strong>=True</strong>)</pre><pre>df.shape</pre><p>(1142, 9)</p><pre>df[df[&#39;book_Title&#39;]<strong>==</strong>&#39;Anime and the Visual Novel: Narrative Structure Design and Play at the Crossroads of Animation and Computer Games&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*homFF25tNHbk8PP9SY9ltQ.png" /></figure><pre># Generate a new id <br>df=df.assign(id=(df[&#39;book_Title&#39;]).astype(&#39;category&#39;).cat.codes)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqWhQ_cyPvGPvmWoA0xfEg.png" /></figure><h3>Visualisation</h3><h4>Most frequent authors</h4><pre>plt.subplots(figsize<strong>=</strong>(10,7))<br>df.Author_Name.value_counts()[:10].plot(kind<strong>=</strong>&quot;bar&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlT3sjg39X3sL35kZWb25A.png" /></figure><h3>Content-Based Recommender Systems</h3><pre># test poinst for ratings_count=40, Avg_Rating= 4.5, Publish_year= 2002, Pages_no= 523<br>test_point = [40, 4.5, 2002, 523]<br>X = df.iloc[:, [2, 3, 4, 6]].values</pre><pre># build a nearest neighbor object, we are searching for just 3 neighbors so n_neighbors=3<br>nn = NearestNeighbors(n_neighbors=3).fit(X)<br># kneighbors returns the neighbor for the test_point<br>print(nn.kneighbors([test_point]))</pre><p>(array([[ 3.9028323 , 7.91060048, 12.2137791 ]]), array([[626, 445, 486]]))</p><pre># This is the most similar book from all the available books<br>df.iloc[626].to_frame()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*XMrb2koC5v-A95MiOW4g-Q.png" /></figure><pre>df.iloc[445].to_frame()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*esGWdoIIreSgUisSMbyU8A.png" /></figure><p>From the results we can observe that the recommender books are near to the test points that we fed manually to the model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd978faa405b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Titanic — Machine Learning from Disaster — Data Cleaning]]></title>
            <link>https://lamalharbi.medium.com/titanic-machine-learning-from-disaster-data-cleaning-ad0bb6ce1b87?source=rss-87f03ec137ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad0bb6ce1b87</guid>
            <category><![CDATA[titanic]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Lamalharbi]]></dc:creator>
            <pubDate>Sat, 16 Jan 2021 18:40:15 GMT</pubDate>
            <atom:updated>2021-01-16T18:40:15.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>Titanic — Machine Learning from Disaster — Data Cleaning</h3><p>Done by: <a href="https://medium.com/u/87f03ec137ee">Lamalharbi</a>, <a href="https://medium.com/u/cac8f1becf29">Monirah abdulaziz</a>, <a href="https://medium.com/u/20e1553c7e2c">Aisha Y Hakami</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*nNcgXmjqRLF16e1jhiGDlg.jpeg" /><figcaption>src: <a href="https://www.forbes.com/sites/davidbressan/2019/04/14/a-geological-study-of-the-titanic-shipwreck-site/?sh=60fd0046431a">TitanicShip</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>In this article we will go through the whole process of cleaning the data and develping a machine learning model on the Titanic dataset which is one of the famous data sets which every Data Scientist explores at the start of their career and here we are. The dataset provides all the information on the fate of passengers on the Titanic, summarized according to sex, age, economic status (class), and survival.</p><p>In addition, we join the <a href="https://www.kaggle.com/c/titanic/overview">Titanic: Machine Learning from Disaster</a> challenge on Kaggle according to our work follow up to see the score.</p><h3>Data Cleaning</h3><pre># upload the data<br>train = pd.read_csv(&#39;../datasets/train.csv&#39;)<br>test = pd.read_csv(&#39;../datasets/test.csv&#39;)</pre><p>Check the null values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*cyFmG_PsZZR8JTm2LnkkaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*2Sp9zrVwVyXCt9dUzhbY1g.png" /><figcaption>Null values in train and Test</figcaption></figure><p><strong>Observation</strong>:</p><ul><li>There is a missing values in train: Age, Cabin and Embarked.</li><li>In the test: Age, Fare and Cabin.</li></ul><pre>fig, ax = plt.subplots(nrows = 1, ncols = 2, figsize = (18, 6))</pre><pre># train data <br>sns.heatmap(train.isnull(), yticklabels=False, ax = ax[0], cbar=False, cmap=&#39;viridis&#39;)<br>ax[0].set_title(&#39;Train data&#39;)</pre><pre># test data<br>sns.heatmap(test.isnull(), yticklabels=False, ax = ax[1], cbar=False, cmap=&#39;viridis&#39;)<br>ax[1].set_title(&#39;Test data&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Y2JGLJIeTcoBU3yaPuSEA.png" /><figcaption>Heatmap to visualize the null values before cleaning</figcaption></figure><ol><li>Embarked feature in Train</li></ol><p>First we need to check How many ports are in Embarked column,</p><pre>train.Embarked.value_counts()</pre><p>the result was:</p><p>S 644<br>C 168<br>Q 77</p><p>Well, now we can drop the two rows with missing Embarked values in train, however, let&#39;s fill the nulls with the port of highest embarkation.</p><pre>from collections import Counter</pre><pre>train.Embarked= train.Embarked.replace(np.nan,Counter(train.Embarked).most_common(1)[0][0])</pre><p>2. Fare feature in Test</p><p>To fill the missing values in Fare we can use the Pclass column, by computing the average of Fare of the missing Class.</p><pre>class3_mean = train[train[&#39;Pclass&#39;]==3][&#39;Fare&#39;].mean()<br>test[&#39;Fare&#39;] = test[&#39;Fare&#39;].replace({np.nan:class3_mean})</pre><p>3. Age feature in Train and Test</p><pre>#defining a function &#39;impute_age&#39;<br>def impute_age(age_pclass): # passing age_pclass as [&#39;Age&#39;, &#39;Pclass&#39;]<br>    <br>    # Passing age_pclass[0] which is &#39;Age&#39; to variable &#39;Age&#39;<br>    Age = age_pclass[0]<br>    <br>    # Passing age_pclass[2] which is &#39;Pclass&#39; to variable &#39;Pclass&#39;<br>    Pclass = age_pclass[1]<br>    <br>    #applying condition based on the Age and filling the missing data respectively <br>    if pd.isnull(Age):</pre><pre>if Pclass == 1:<br>            return 38</pre><pre>elif Pclass == 2:<br>            return 30</pre><pre>else:<br>            return 25</pre><pre>else:<br>        return Age</pre><p>By using the above function we can<strong> </strong>fill the missing data in Age feature according to the mean age with respect to each Pclass.</p><pre># (for train) grab age and apply the impute_age, our custom function<br>train[&#39;Age&#39;] = train[[&#39;Age&#39;,&#39;Pclass&#39;]].apply(impute_age,axis=1)</pre><pre># (for test) grab age and apply the impute_age, our custom function <br>test[&#39;Age&#39;] = test[[&#39;Age&#39;,&#39;Pclass&#39;]].apply(impute_age,axis=1)</pre><p>4. Cabin feature in Train and Test</p><p>Now we reach half of the way, the last step is the Cabin column we need to apply some feature engineering.</p><ul><li>If there was a value for Cabin — replace with <strong>1</strong></li><li>If the value is missing/null — replace with <strong>0</strong></li></ul><pre>#Train:<br>train.loc[train[&#39;Cabin&#39;].notnull(), &#39;Cabin&#39;] =1<br>train[&#39;Cabin&#39;] = train[&#39;Cabin&#39;].replace({np.nan:0})<br>train[&#39;Cabin&#39;] = train[&#39;Cabin&#39;].astype(int)</pre><pre>#Test:<br>test.loc[test[&#39;Cabin&#39;].notnull(), &#39;Cabin&#39;] =1<br>test[&#39;Cabin&#39;] = test[&#39;Cabin&#39;].replace({np.nan:0})<br>test[&#39;Cabin&#39;] = test[&#39;Cabin&#39;].astype(int)</pre><p>Now let’s take a look to the heatmap again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kU7uo55L5aPMsbXzikC8jA.png" /><figcaption>Heatmap to visualize the null values after cleaning</figcaption></figure><h3>Look’s Great!! No more missing values :)</h3><h3>Feature Engineering</h3><p>To include the categorical variables as predictors in statistical and machine learning models we need to Dummy the variables.</p><p>Dummy the Sex and Embarked columns</p><pre># Train<br>sex = pd.get_dummies(train[&#39;Sex&#39;],drop_first=True)<br>embark = pd.get_dummies(train[&#39;Embarked&#39;],drop_first=True)<br>train = pd.concat([train, sex,embark],axis=1)<br>train=train.drop([&#39;Sex&#39;,&#39;Embarked&#39;], axis=1)<br>train.rename(columns={&quot;male&quot;: &quot;sex_male&quot;, &quot;Q&quot;: &quot;Embarked_Q&quot;,&quot;S&quot;: &quot;Embarked_S&quot;}, inplace=True)<br># Same for the Test</pre><h3><strong>Model Preparation</strong></h3><ol><li>First we need to select our features and it will be the following:</li></ol><p>[Pclass, Age, SibSp, Parch, Fare, Cabin, Sex_male, Embarked_Q, Embarked_S]</p><p>And our target will be the feature: Survived</p><p>2. Then we need to write a list comprehension to grab the selected features.</p><p>3. Separate the selected_column in X_train and the Survived in y_train.</p><pre>features_drop = [&#39;PassengerId&#39;,&#39;Name&#39;, &#39;Ticket&#39;, &#39;Survived&#39;]<br>selected_features = [x for x in train.columns  if x not in features_drop ]<br>X_train = train[selected_features]<br>y_train = train[&#39;Survived&#39;]</pre><p><strong>Now the data is ready to train on the models.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0bb6ce1b87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Driving Licenses, Traffic Accidents and Casualties Analysis]]></title>
            <link>https://lamalharbi.medium.com/driving-licenses-traffic-accidents-and-casualties-analysis-cd33adf86f66?source=rss-87f03ec137ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd33adf86f66</guid>
            <category><![CDATA[traffic-accidents]]></category>
            <category><![CDATA[driving-license]]></category>
            <category><![CDATA[saudi-arabia]]></category>
            <category><![CDATA[accidents-analytics]]></category>
            <dc:creator><![CDATA[Lamalharbi]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 22:56:35 GMT</pubDate>
            <atom:updated>2021-02-11T10:31:57.982Z</atom:updated>
            <content:encoded><![CDATA[<p>Saudi Arabia</p><h3><strong>Problem Statment</strong></h3><p>Traffic accidents was the main reason of health hazard in Saudi Arabia [1]. Traffic authorities have been working hard on reducing the number of road accidents in Saudi Arabia by forcing new rules [2]. To investigate the problem and solutions this analytics study is conducted to compare between the regions, and to find which has the highest number and causes against the lowest to improve the society and save lives.</p><h3><strong>Executive Summary</strong></h3><p>Traffic accidents in Saudi Arabia fall 30% a year [3]. Makkah and Riyadh has the largest numbers in accidents with a dramatic different comparing with the other regions. The new punishments for traffic violations, traffic safety equipment affect in decreasing these numbers [3].</p><h3><strong>Datasets</strong></h3><ul><li><a href="https://datasource.kapsarc.org/explore/dataset/saudi-arabia-driving-licenses-issued-in-the-kingdom-2004-2008/information/?disjunctive.administritive_area&amp;sort=time_period&amp;location=5,24.37495,45.08024&amp;basemap=jawg.streets">Driving Licenses.</a> <br>This dataset contains Saudi Arabia Driving Licenses Issued By Administrative Area for 1993–2016, and 1993–2019. Data from General Authority for Statistics . Follow datasource.kapsarc.org for timely data to advance energy economics research [4].</li><li><a href="https://datasource.kapsarc.org/explore/dataset/saudi-arabia-traffic-accidents-and-casualties-injured-dead-2008/export/?disjunctive.region&amp;disjunctive.indicator&amp;sort=time_period">Traffic Accidents and Casualties</a>.<br>This dataset contains Saudi Arabia Traffic Accidents and Casualties by Region for 2016. Data from General Authority for Statistics. Follow datasource.kapsarc.org for timely data to advance energy economics research [5].</li></ul><h3>Preprocessing</h3><p>After exploring the data, we can observe missing data, and unnecessary features to my analytics. In addition, for the Traffic Accidents and Casualties dataset, the dataset needs to be transform to wide to get the most advantage to analysing the casualities. Furthermore, to enhance the merging process the features names need to match.</p><h3>Statistics and Investigating the trends</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGU4ChAIVaLW-qOG2t4JyQ.png" /><figcaption>fig.1: dataset statistics</figcaption></figure><ul><li>The highest number of issued driving licenses between 1993–2017 was in Riyadh in 2017 with 495307 licenses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*R8q9jlCmYeoJ7MBZqt_hyA.png" /><figcaption>fig.2: Highest number of issued driving licenses</figcaption></figure><ul><li>The lowest number of issued driving licenses between 1993–2017 was in Tabouk in 2015 with 915 licenses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*HVUcKB84FUwONxh_PDgbaQ.png" /><figcaption>fig.3: Lowest number of issued driving licenses</figcaption></figure><ul><li>The highest mean of traffic accidents between 2016–2017 was in Makkah in 2017 with 145541 accidents.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*BCZmv1lY5zVkHRvkNDVxag.png" /><figcaption>fig.4: Highest mean of traffic accidents</figcaption></figure><ul><li>The lowest mean of traffic accidents between 2016–2017 was in Al-Baha in 2017 with 1414 accidents.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*-8KUh6xWe5rapioUlabUvw.png" /><figcaption>fig.5: Lowest mean of traffic accidents</figcaption></figure><h3><strong>Visualization and Key Findings</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*VBSpFrjhYEMUenbc0MuQIw.png" /><figcaption>fig.6: Number of driving_licences 2016–2017</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*0gcyCLNq2z1sh2Y9jAmlMw.png" /><figcaption>fig.7: Number of indicators in 2016–2017</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*NzdSHkcFwKqXaoZW1IZjSg.png" /><figcaption>fig.8: Relation between number of driving licences and number of accidents in 2016</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*5SRHk551s_fVKsRZWydIZg.png" /><figcaption>fig.9: Relation between number of driving licences and number of accidents in 2017</figcaption></figure><p>From the above plots we can see that even with the high increasing in the issued driving licenses, there is a high decrease in the number of indicators in the year 2016–2017.</p><p>In addition, the high number of issued driving licenses in Riyadh in 2017 consider very high comparing with the other regions and the decreasing in number of accidents is obviously high.</p><p>To investigate more about this, I upload an updated dataset that include 2018, 2019.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*cHkMn2P6Eux8MieFCrpiXA.png" /><figcaption>fig.10: Number of driving licences including 2018–2019</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*NWjovVj4Gr_DRv13bKU_WA.png" /><figcaption>fig. 11: Number of traffic accidents including 2018–2019</figcaption></figure><p>The number of accidents continue to decrease with the increasing in the driving licences numbers. After allowing the woman to drive in Saudi Arabia the new rules and regulation that forced by the traffic authority help to decrease the accidents numbers.</p><p>After analysing the year relations, the next step is to find the highest and lowest regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*8CxfBkOmEU8wL2HKgDtqWQ.png" /><figcaption>fig. 12: Number of indicators in each region</figcaption></figure><p>As observed in investigating the trends section, the regions with the high number of accidents are Makkah, Riyadh, and the lowest is Al-Baha.</p><h3>Conclusions and Recommendations</h3><p>As we see there is an increasing in driving licences over the years wherever there is a decreasing in traffic accidents. The main causes for decreasing traffic accidents to fall 30% a year are tough new punishments for traffic violations, including fines and lengthy prison sentences for causing injury or death, and a crackdown on mobile phone usage. Furthermore, Saudi Arabia has also introduced traffic safety equipment including high tensile fencing, protective barriers and rotating shock absorbers to reduce injuries [3].</p><p><strong>Key takeaways</strong></p><ul><li>From the above analysis the highest number of accidents for 2016–2017 was fro regions Makkah, Riyadh.</li><li>In addition there is a dramatic difference for the issued driving licenses for Makkah, and Riyadh comparing with other regions.</li><li>Makkah has the highest number in traffic accidents with 145541 accidents where lower region is Al-Baha with 1212 accidents.</li><li>Riyadh issued driving licenses was the highest with 495307 licenses in 2017, on the other hand the lowest was in 2015 in Tabouk region.</li><li>The high population of capital Riyadh and Hajj and Umrah seasons in Makkah might consider as main reasons for high number of accidents in these regions.</li><li>The new rules forced by the traffic authority after allowing woman to drive help to decrease the accident numbers.</li></ul><p><strong>Recommendation</strong></p><ul><li>Develop driving training program methods, and manage or motivate drivers through supervisory such as, coaching and leadership. Also, the appropriate driving training space with road challenges would help to think and act before accidents happens.</li><li>Rules and punishments from the government for the negligent drivers who break any type of rules.</li><li>Spread the awareness and statistics of number of accidents using the social media to reach to all the society.</li></ul><h3>References</h3><p>[1] PhD MRCGPN.J.Shanks, Road traffic accidents in Saudi Arabia.</p><p>[2] Lovin Saudi. 2021. <em>The Main Cause Of Road Accidents In Saudi Arabia Has Been Revealed And It Is Hardly A Shocker</em>. [online] Available at: &lt;https://lovin.co/saudi/en/news/main-cause-of-road-accidents-in-saudi/&gt; [Accessed 2 January 2021].</p><p>[3] Anderson, R., 2021. <em>Saudi Road Deaths Fall 33% In A Year</em>. [online] Gulf Business. Available at: &lt;https://gulfbusiness.com/saudi-road-deaths-fall-33-year/&gt; [Accessed 2 January 2021].</p><p>[4] Datasource.kapsarc.org. 2021. <em>Driving Licenses Issued By Region</em>. [online] Available at: &lt;https://datasource.kapsarc.org/explore/dataset/saudi-arabia-driving-licenses-issued-in-the-kingdom-2004-2008/information/?disjunctive.administritive_area&amp;sort=time_period&amp;location=5,24.37495,45.08024&amp;basemap=jawg.streets&gt; [Accessed 2 January 2021].</p><p>[5] Datasource.kapsarc.org. 2021. <em>Traffic Accidents And Casualties By Region</em>. [online] Available at: &lt;https://datasource.kapsarc.org/explore/dataset/saudi-arabia-traffic-accidents-and-casualties-injured-dead-2008/export/?disjunctive.region&amp;disjunctive.indicator&amp;sort=time_period&gt; [Accessed 2 January 2021].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd33adf86f66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>