<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Machine Learning | StatCityPro</title>
    <link>/en/tag/machine-learning/</link>
      <atom:link href="/en/tag/machine-learning/index.xml" rel="self" type="application/rss+xml" />
    <description>Machine Learning</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><lastBuildDate>Sun, 16 Aug 2020 00:00:00 +0000</lastBuildDate>
    <image>
      <url>/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_512x512_fill_lanczos_center_2.png</url>
      <title>Machine Learning</title>
      <link>/en/tag/machine-learning/</link>
    </image>
    
    <item>
      <title>Immigration - Where do they live? - Part 2</title>
      <link>/en/post/migration-part2/migrationenpart2/</link>
      <pubDate>Sun, 16 Aug 2020 00:00:00 +0000</pubDate>
      <guid>/en/post/migration-part2/migrationenpart2/</guid>
      <description>


&lt;p&gt;This publication follows on from a previous &lt;a href=&#34;https://www.statcitypro.com/en/post/migration/migrationen/#what-is-the-eastern-sector&#34;&gt;post&lt;/a&gt; and looks to build a machine learning classification model to predict if an immigrant that arrived to Santiago de Chile in 2019 lived in the Eastern Sector of the city upon arrival.&lt;/p&gt;
&lt;div id=&#34;packages&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Packages&lt;/h2&gt;
&lt;p&gt;The following packages are used in this publication.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)
library(caret)
library(modelr)
library(forcats) 
library(caTools)
library(readr)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;the-eastern-sector&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;2) The Eastern Sector&lt;/h2&gt;
&lt;p&gt;As previously explained the Eastern Sector contains the comunas of Providencia, Las Condes, Vitacura, y Lo Barnechea and is located to the north east of the city. These comunas are considered the most wealthy in the city and are identified in the below map.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/MigrationENpart2/EasternSector.png&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;distribution-of-immigrants&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;3) Distribution of Immigrants&lt;/h2&gt;
&lt;p&gt;The below map shows the distribution of all immigrants who arrived to Santiago in 2019. Tt must be noted that the data used only refers to the comuna of residence when an immigrant applied for their visa. Therefore, it is possible that they have since moved to a different sector of the city.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/MigrationENpart2/LocationImmigrants.png&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;maplabels &amp;lt;- read_csv(&amp;quot;lables.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Warning: Missing column names filled in: &amp;#39;X1&amp;#39; [1]&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Parsed with column specification:
## cols(
##   X1 = col_double(),
##   nombre_comuna = col_character(),
##   labels = col_double()
## )&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;maplabels&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 32 x 3
##       X1 nombre_comuna    labels
##    &amp;lt;dbl&amp;gt; &amp;lt;chr&amp;gt;             &amp;lt;dbl&amp;gt;
##  1     1 Santiago              1
##  2     2 Cerrillos             2
##  3     3 Cerro Navia           3
##  4     4 Conchalí              4
##  5     5 El Bosque             5
##  6     6 Estación Central      6
##  7     7 Huechuraba            7
##  8     8 Independencia         8
##  9     9 La Cisterna           9
## 10    10 La Florida           10
## # … with 22 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;4) Data&lt;/h2&gt;
&lt;p&gt;The idea of this section is to create a classification model to predict in which comuna immigrants lived when they arrived to Santiago. The data used is the &lt;em&gt;visas2019STG&lt;/em&gt; data frame that was prepared in &lt;a href=&#34;https://www.statcitypro.com/en/post/migration/migrationen/#what-is-the-eastern-sector&#34;&gt;part 1&lt;/a&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG &amp;lt;- read.csv(&amp;quot;visas2019STG.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;model-preparation&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;5) Model Preparation&lt;/h2&gt;
&lt;p&gt;The following processes are conducted to prepare the data for modeling.&lt;/p&gt;
&lt;div id=&#34;selecting-variables-and-eastern-sector-variable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.1) Selecting Variables and Eastern Sector Variable&lt;/h3&gt;
&lt;p&gt;First the relevant variables are choosen.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STGfilter &amp;lt;- visas2019STG %&amp;gt;% select(SEXO, PAÍS, ACTIVIDAD, PROFESIÓN, ESTUDIOS, nombre_comuna, AÑO, MES, Age)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Second a new binomial variable is created to determine if an immigrant lived in the Eastern Sector. Within this variable 1 represents an immigrant that lived in the Eastern Sector, and 0 represents an immigrant who lived in a different sector of the city.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STGfilter$SECTOR_ORRIENTE &amp;lt;- if_else(visas2019STGfilter$nombre_comuna == &amp;#39;Providencia&amp;#39;, 1,
                                 if_else(visas2019STGfilter$nombre_comuna == &amp;#39;Las Condes&amp;#39;, 1, 
                                         if_else(visas2019STGfilter$nombre_comuna == &amp;#39;Vitacura&amp;#39;, 1,
                                                 if_else(visas2019STGfilter$nombre_comuna ==&amp;#39;Lo Barnechea&amp;#39;, 1, 0))))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;one-hot-encoding&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.2) One Hot Encoding&lt;/h3&gt;
&lt;p&gt;Thirdly One Hot Encoding is conducted. This is a process by which to convert categorical variables into a strucutre which is easier to compute. When One Hot Encoding is applied to a particular variable, new columns are created for each categorical class of the original variable. For each class column, a one is recorded for all the observations that have that class, with a zero recorded for all those that do not.&lt;/p&gt;
&lt;p&gt;One Hot Encoding is carried out for the variables of Sex, Activity and Studies.&lt;/p&gt;
&lt;div id=&#34;sex&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Sex&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model_matrix(visas2019STGfilter, SECTOR_ORRIENTE~SEXO-1)

visas2019STGfilter &amp;lt;- cbind(visas2019STGfilter, model_matrix(visas2019STGfilter, SECTOR_ORRIENTE~SEXO-1))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;activity&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Activity&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model_matrix(visas2019STGfilter, SECTOR_ORRIENTE~ACTIVIDAD-1)

visas2019STGfilter &amp;lt;- cbind(visas2019STGfilter, model_matrix(visas2019STGfilter, SECTOR_ORRIENTE~ACTIVIDAD-1))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;studies&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Studies&lt;/h4&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;model_matrix(visas2019STGfilter, SECTOR_ORRIENTE~ESTUDIOS-1)

visas2019STGfilter &amp;lt;- cbind(visas2019STGfilter, model_matrix(visas2019STGfilter, SECTOR_ORRIENTE~ESTUDIOS-1))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;countries-to-continents&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.3) Countries to Continents&lt;/h3&gt;
&lt;p&gt;In total there are 75 nationalities in the data. To make these easier to compute a new variable is created, grouping the nationalities into continents. One Hot Encoding is then carried out for this variable.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STGfilter$continente &amp;lt;- fct_collapse(visas2019STGfilter$PAÍS, Europe = c(&amp;#39;Alemania&amp;#39;, &amp;#39;Austria&amp;#39;, &amp;#39;Bélgica&amp;#39;, &amp;#39;Bulgaria&amp;#39;, &amp;#39;Croacia&amp;#39;, &amp;#39;Dinamarca&amp;#39;, &amp;#39;Eslovaquia&amp;#39;, &amp;#39;España&amp;#39;, &amp;#39;Finlandia&amp;#39;,
                                                 &amp;#39;Francia&amp;#39;, &amp;#39;Grecia&amp;#39;, &amp;#39;Holanda&amp;#39;, &amp;#39;Hungría&amp;#39;, &amp;#39;Inglaterra&amp;#39;, &amp;#39;Irlanda&amp;#39;, &amp;#39;Italia&amp;#39;, &amp;#39;Lituania&amp;#39;, &amp;#39;Noruega&amp;#39;, 
                                                 &amp;#39;Polonia&amp;#39;, &amp;#39;Portugal&amp;#39;, &amp;#39;República Checa&amp;#39;, &amp;#39;República De Bielorrusia&amp;#39;, &amp;#39;República De Serbia&amp;#39;,
                                                 &amp;#39;Rumanía&amp;#39;, &amp;#39;Rusia&amp;#39;, &amp;#39;Suecia&amp;#39;, &amp;#39;Suiza&amp;#39;, &amp;#39;Ucrania&amp;#39;), Africa = c(&amp;#39;Angola&amp;#39;, &amp;#39;Camerún&amp;#39;, &amp;#39;Egipto&amp;#39;, &amp;#39;Marruecos&amp;#39;, &amp;#39;República de Congo&amp;#39;, &amp;#39;Sudráfica&amp;#39;), 
             Asia = c(&amp;#39;Bangladesh&amp;#39;, &amp;#39;Corea del Sur&amp;#39;, &amp;#39;China&amp;#39;, &amp;#39;Filipinas&amp;#39;, &amp;#39;India&amp;#39;, &amp;#39;Indonesia&amp;#39;, &amp;#39;Irán&amp;#39;, &amp;#39;Israel&amp;#39;, &amp;#39;Japón&amp;#39;,
                      &amp;#39;Jordania&amp;#39;, &amp;#39;Líbano&amp;#39;, &amp;#39;Malasia&amp;#39;, &amp;#39;Nepal&amp;#39;, &amp;#39;Pakistán&amp;#39;, &amp;#39;Palestina&amp;#39;, &amp;#39;Siria&amp;#39;, &amp;#39;Tailandia&amp;#39;, &amp;#39;Taiwan&amp;#39;, &amp;#39;Turquía&amp;#39;),
             SouthAmerica = c(&amp;#39;Argentina&amp;#39;, &amp;#39;Bolivia&amp;#39;, &amp;#39;Brasil&amp;#39;, &amp;#39;Colombia&amp;#39;, &amp;#39;Ecuador&amp;#39;, &amp;#39;Paraguay&amp;#39;, &amp;#39;Perú&amp;#39;, &amp;#39;Uruguay&amp;#39;, &amp;#39;Venezuela&amp;#39;), 
             CentralAmerica = c(&amp;#39;Costa Rica&amp;#39;, &amp;#39;Cuba&amp;#39;, &amp;#39;El Salvador&amp;#39;, &amp;#39;Guatemala&amp;#39;, &amp;#39;Haití&amp;#39;, &amp;#39;Honduras&amp;#39;, &amp;#39;México&amp;#39;, &amp;#39;Nicaragua&amp;#39;, &amp;#39;Panamá&amp;#39;,&amp;#39;República Dominicana&amp;#39;), 
             NorthAmerica = c(&amp;#39;Canadá&amp;#39;, &amp;#39;Estados Unidos&amp;#39;), Other = c(&amp;#39;Otro país&amp;#39;), 
             Oceania = c(&amp;#39;Australia&amp;#39;, &amp;#39;Nueva Zelanda&amp;#39;))&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STGfilter &amp;lt;- cbind(visas2019STGfilter, model_matrix(visas2019STGfilter, SECTOR_ORRIENTE~continente-1))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;creating-the-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6) Creating the Model&lt;/h2&gt;
&lt;p&gt;The data is divided into two groups. One is the training group with 75% of the observations. The second is the test group with 25% of the observations.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
split &amp;lt;- sample.split(visas2019STGfilter$SECTOR_ORRIENTE, SplitRatio = 0.75)
training_set &amp;lt;- subset(visas2019STGfilter, split == TRUE)
test_set &amp;lt;- subset(visas2019STGfilter, split == FALSE)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;training_set_cut &amp;lt;- training_set[,c(-1, -2, -3, -4, -5, -6, -7, -8, -9, -34)]

test_set_cut &amp;lt;- test_set[,c(-1, -2, -3, -4, -5, -6, -7, -8, -9, -34)]&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;training-the-model&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.2) Training the Model&lt;/h3&gt;
&lt;p&gt;A General Linear Model is used and trained with the below syntax.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
classifier = glm(formula = SECTOR_ORRIENTE ~.,
                  family = binomial,
                  data = training_set_cut)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The model is used to make predictions on the test data. A prediction of 1 represents an immigrant in the Eastern Sector and a prediction of 0 represents an immigrant in another area of the city. A Confusion Matrix is used to assess the accuracy of the model.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
prob_pred &amp;lt;- predict(classifier, type = &amp;#39;response&amp;#39;, newdata = test_set_cut[,c(-1)])&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;y_pred &amp;lt;- ifelse(prob_pred &amp;gt;= 0.5, 1, 0)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cm &amp;lt;- confusionMatrix(factor(test_set_cut$SECTOR_ORRIENTE), factor(y_pred), positive = &amp;quot;1&amp;quot;)

cm&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Confusion Matrix and Statistics
## 
##           Reference
## Prediction     0     1
##          0 22616   169
##          1  1617   262
##                                           
##                Accuracy : 0.9276          
##                  95% CI : (0.9243, 0.9308)
##     No Information Rate : 0.9825          
##     P-Value [Acc &amp;gt; NIR] : 1               
##                                           
##                   Kappa : 0.2042          
##                                           
##  Mcnemar&amp;#39;s Test P-Value : &amp;lt;2e-16          
##                                           
##             Sensitivity : 0.60789         
##             Specificity : 0.93327         
##          Pos Pred Value : 0.13944         
##          Neg Pred Value : 0.99258         
##              Prevalence : 0.01747         
##          Detection Rate : 0.01062         
##    Detection Prevalence : 0.07618         
##       Balanced Accuracy : 0.77058         
##                                           
##        &amp;#39;Positive&amp;#39; Class : 1               
## &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;analysis&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;7) Analysis&lt;/h2&gt;
&lt;p&gt;The confusion matrix compares the real data with the predicted data to show how accurate the model is. The matrix provides four values:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;EasternSectorCorrect = 262
EasternSectorFalse = 1617
OtherSectorCorrect = 22616
OtherSectorIncorrect = 169

TotalObservations = EasternSectorCorrect + EasternSectorFalse + OtherSectorCorrect + OtherSectorIncorrect&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The above values can be used to calculate the following four measures of model accuracy:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Accuaracy&lt;/li&gt;
&lt;li&gt;Kappa&lt;/li&gt;
&lt;li&gt;Precision&lt;/li&gt;
&lt;li&gt;Recall&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These values are discussed below.&lt;/p&gt;
&lt;div id=&#34;accuracy&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;7.1) Accuracy&lt;/h3&gt;
&lt;p&gt;The model had an accuracy of 92.76%. This means that the model classified 92.76% of the test data correctly.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;Accuracy &amp;lt;- ((EasternSectorCorrect + OtherSectorCorrect)/TotalObservations)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;precision&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;7.2) Precision&lt;/h3&gt;
&lt;p&gt;The model has a Precision of 13.94%. This means that of all the immigrants which the model predicted as living in the Easter Sector, 13.94% actually lived there.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;Precision &amp;lt;- EasternSectorCorrect/(EasternSectorCorrect+EasternSectorFalse)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;recall&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;7.3) Recall&lt;/h3&gt;
&lt;p&gt;The Recall value of 60.79% means that out of the 431 immigrants that actually lived in the Eastern Sector, the model correctly predicted that 60.79% of them lived there.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;Recall &amp;lt;- EasternSectorCorrect / (EasternSectorCorrect + OtherSectorIncorrect)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;kappa&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;7.4) Kappa&lt;/h3&gt;
&lt;p&gt;One of the problems with the data is that it is not balanced. Only 431 immigrants from the test data live there accounting for 1.75%. Subsequently, the model can easily obtain a high accuracy as it could predict that all the observations do not live in the Eastern Sector, and it would still obtain an accuracy of 98.25%.&lt;/p&gt;
&lt;p&gt;Therefore, the Kappa value can be used to measure how well the model performed. The models performance is compared with the results for if the model had been run at random on the data. The Kappa value is between 0 and 1, with the closer to 1 meaning the model is more accurate.&lt;/p&gt;
&lt;p&gt;The model has a Kappa of 0.2042. This means that the model classifies the data with accuracy 20.42% better than that of random classification. A Kappa value of between 0.21 and 0.40 is considered reasonable.
More can be read about how to calculate the &lt;a href=&#34;https://stats.stackexchange.com/questions/82162/cohens-kappa-in-plain-english?noredirect=1&amp;amp;lq=1&#34;&gt;Kappa value&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6) Conclusion&lt;/h2&gt;
&lt;p&gt;In conclusion this publication has created a classification model to classifiy if an immigrant that arrived to Santiago in 2019 lived in the Eastern Sector. It has followed on from the &lt;a href=&#34;https://www.statcitypro.com/en/post/migration/migrationen&#34;&gt;part 1&lt;/a&gt; publication which prepared the data and looked at the distribution of some nationalities throughout the city. When the model was used on the test data an accuracy of 92.76% was obtained with a Kappa value of 0.2042, suggesting that the model had some success. However, the Precision of 13.94% and the Recall value of 60.79% suggest that the model found it difficult to correctly classify immigrants from the Eastern Setor. The model could be improved with more equally spread data and different types of classification models. These options will be explored in future publications. Many thanks for reading this publication.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Immigration - Where do they live? - Santiago</title>
      <link>/en/post/migration/migrationen/</link>
      <pubDate>Sun, 21 Jun 2020 00:00:00 +0000</pubDate>
      <guid>/en/post/migration/migrationen/</guid>
      <description>


&lt;p&gt;A few months ago an &lt;a href=&#34;https://portugalconcopiapo.wordpress.com/2020/03/28/mapping-immigration-data-in-santiago-de-chile/&#34;&gt;investigation&lt;/a&gt; was carried out by the author of StatCityPro into where immigrants live in Santiago de Chile. Various points of interest were identified regarding the number of immigrants and also where they lived upon arrival to Chile.&lt;/p&gt;
&lt;p&gt;This publication looks to build on this previous work by looking at more current data from 2019 and also by using machine learning methods of classification to build a model to predict if immigrants live in the Eastern Sector of Santiago. More information can be read about the &lt;a href=&#34;#the-eastern-sector&#34;&gt;Eastern Sector&lt;/a&gt;.&lt;/p&gt;
&lt;div id=&#34;packages&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;2) Packages&lt;/h2&gt;
&lt;p&gt;The following packages will be used in this publication.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)
library(lubridate)
library(chilemapas)
library(ggplot2)
library(sf)
library(ggspatial)
library(caret)
library(modelr)
library(forcats) 
library(caTools)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;3) Data&lt;/h2&gt;
&lt;p&gt;The data used in this publication can be downloaded from the following &lt;a href=&#34;https://www.extranjeria.gob.cl/media/2020/03/visas_otorgadas_2019.xlsx&#34;&gt;link&lt;/a&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;setwd(&amp;quot;~/Documents/Machine Learning/4. Proyectos/Migration/Data Sets&amp;quot;)

visas2019 &amp;lt;- read.csv(&amp;quot;visas_otorgadas_2019.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The below syntax can be used to reveal the data’s variables. In total there are 14 variables with 328,118 observations.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;str(visas2019)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## &amp;#39;data.frame&amp;#39;:    328115 obs. of  14 variables:
##  $ SEXO              : Factor w/ 2 levels &amp;quot;Femenino&amp;quot;,&amp;quot;Masculino&amp;quot;: 2 1 1 2 2 2 2 2 2 1 ...
##  $ PAÍS              : Factor w/ 77 levels &amp;quot;Alemania&amp;quot;,&amp;quot;Angola&amp;quot;,..: 58 65 65 18 65 31 18 14 14 14 ...
##  $ NACIMIENTO        : Factor w/ 26521 levels &amp;quot;&amp;quot;,&amp;quot;1900-01-01&amp;quot;,..: 15106 16136 16461 14048 2870 17043 21235 16788 14639 15764 ...
##  $ ACTIVIDAD         : Factor w/ 14 levels &amp;quot;Dueña De Casa&amp;quot;,..: 8 7 7 8 7 9 7 2 13 9 ...
##  $ PROFESIÓN         : Factor w/ 606 levels &amp;quot;A Bodega&amp;quot;,&amp;quot;A Planificac&amp;quot;,..: 351 426 426 432 158 423 399 245 569 84 ...
##  $ ESTUDIOS          : Factor w/ 7 levels &amp;quot;Básico&amp;quot;,&amp;quot;Medio&amp;quot;,..: 4 1 7 2 4 2 4 2 4 2 ...
##  $ COMUNA            : Factor w/ 340 levels &amp;quot;Algarrobo&amp;quot;,&amp;quot;Alhué&amp;quot;,..: 304 113 262 327 127 308 304 10 91 113 ...
##  $ PROVINCIA         : Factor w/ 56 levels &amp;quot;Antártica Chilena&amp;quot;,..: 49 49 49 56 25 51 49 2 49 49 ...
##  $ REGIÓN            : Factor w/ 16 levels &amp;quot;Antofagasta&amp;quot;,..: 13 13 13 16 6 12 13 1 13 13 ...
##  $ TIT_DEP           : Factor w/ 3 levels &amp;quot;&amp;quot;,&amp;quot;D&amp;quot;,&amp;quot;T&amp;quot;: 1 1 1 1 1 1 1 1 1 1 ...
##  $ AUTORIDAD         : Factor w/ 55 levels &amp;quot;Dem&amp;quot;,&amp;quot;Gobernación Antártica Chilena&amp;quot;,..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ BENEFICIO_AGRUPADO: Factor w/ 7 levels &amp;quot;Estudiante&amp;quot;,&amp;quot;Inversionista&amp;quot;,..: 5 5 5 5 5 5 5 5 5 5 ...
##  $ AÑO               : int  2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 ...
##  $ MES               : int  4 7 7 7 5 2 2 5 6 5 ...&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;feature-engineering&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;4) Feature Engineering&lt;/h2&gt;
&lt;p&gt;Feature Engineering will be conducted to preapre the date for further analysis.&lt;/p&gt;
&lt;div id=&#34;filter-data&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.1) Filter Data&lt;/h3&gt;
&lt;p&gt;Firstly the data is filtered to only have data for the province of Santiago. From now on this area will be referred to as Santiago. It is important to note that this area does not include the comunas of San Bernado or Puente Alto as they are part of different provinces.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG &amp;lt;- visas2019 %&amp;gt;% filter(REGIÓN == &amp;quot;Metropolitana de Santiago&amp;quot;) 

visas2019STG &amp;lt;- visas2019STG %&amp;gt;% filter(PROVINCIA == &amp;#39;Santiago&amp;#39;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;missing-values&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.2) Missing Values&lt;/h3&gt;
&lt;p&gt;Some variables have a class of ‘No Informa’. However, this is not the case for TIT-DEP which has 15,902 without a value. In accordance with the other variables, a class of ‘No Informa’ is added for these missing values. After this all of the observations that have a value of ‘No Informa’ for any of the variables are removed from the data frame as they can reduce the precision of the model.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(visas2019STG$ACTIVIDAD) 
      
table(visas2019STG$PROFESIÓN) 
            
table(visas2019STG$ESTUDIOS) 

table(visas2019STG$TIT_DEP)

levels(visas2019STG$TIT_DEP)

levels(visas2019STG$TIT_DEP)[1] &amp;lt;- &amp;quot;No Informa&amp;quot;

table(visas2019STG$TIT_DEP)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG &amp;lt;- visas2019STG %&amp;gt;% filter(!ACTIVIDAD == &amp;quot;No Informa&amp;quot; ) %&amp;gt;% filter(!PROFESIÓN == &amp;quot;No Informa&amp;quot;) %&amp;gt;% filter(!ESTUDIOS == &amp;quot;No Informa&amp;quot;) %&amp;gt;% filter(!TIT_DEP == &amp;quot;No Informa&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;immigrante-age&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.3) Immigrante Age&lt;/h3&gt;
&lt;p&gt;The date of birth is converted to age.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG$NACIMIENTO &amp;lt;- as.Date(visas2019STG$NACIMIENTO)

year &amp;lt;- 2020

Birth_year &amp;lt;- year(visas2019STG$NACIMIENTO)

visas2019STG &amp;lt;- visas2019STG %&amp;gt;% mutate(Age = year - Birth_year)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;geographic-coordinates&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.4) Geographic Coordinates&lt;/h3&gt;
&lt;p&gt;The package &lt;em&gt;chilemapas&lt;/em&gt; is used to create a base map for the Province of Santiago.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;Chile &amp;lt;- chilemapas::codigos_territoriales
STG &amp;lt;- Chile %&amp;gt;% filter(nombre_provincia == &amp;#39;Santiago&amp;#39;)
Comunas &amp;lt;- chilemapas::mapa_comunas
STGgeo &amp;lt;- left_join(STG, Comunas)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Additionally, accents are added to the names of each of the comunas, so that they can be combined with other data bases that use accents in their spelling of the comunas.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;STGgeo[4, 2] = &amp;quot;Conchalí&amp;quot;
STGgeo[6, 2] = &amp;quot;Estación Central&amp;quot;
STGgeo[19, 2] = &amp;quot;Maipú&amp;quot;
STGgeo[20, 2] = &amp;quot;Ñuñoa&amp;quot;
STGgeo[22, 2] = &amp;quot;Peñalolén&amp;quot;
STGgeo[29, 2] = &amp;quot;San Joaquín&amp;quot;
STGgeo[31, 2] = &amp;quot;San Ramón&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two data bases are combined.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG &amp;lt;- visas2019STG %&amp;gt;% rename(nombre_comuna = COMUNA)

visas2019STG$nombre_comuna &amp;lt;- as.factor(visas2019STG$nombre_comuna)

visas2019STG &amp;lt;- left_join(visas2019STG, STGgeo)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;initial-analysis&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;5) Initial Analysis&lt;/h2&gt;
&lt;p&gt;In this section the data is explored.&lt;/p&gt;
&lt;div id=&#34;nationalities&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.1) Nationalities&lt;/h3&gt;
&lt;p&gt;In 2019 156,260 inmigrantes arrived to Santiago with a total of 76 nationalities. However, after following the feature engineering steps outline in &lt;a href=&#34;feature-engineering&#34;&gt;Section 4&lt;/a&gt; this number reduces to 98,655 with 76 nationalities. Of this amount Venezuelans are the most prominent representing 58.80% with 58,009 people. An additional point of interest is that of the ten most prominent nationalities eight are from South or Central America, with China and the United States the only exceptions. It is also observed that six of these ten nationalities speak Spanish as a first language.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG %&amp;gt;% group_by(PAÍS) %&amp;gt;% count() %&amp;gt;% arrange(-n)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 75 x 2
## # Groups:   PAÍS [75]
##    PAÍS               n
##    &amp;lt;fct&amp;gt;          &amp;lt;int&amp;gt;
##  1 Venezuela      58009
##  2 Perú           11474
##  3 Colombia        8465
##  4 Haití           7135
##  5 Bolivia         2424
##  6 Ecuador         2119
##  7 Argentina       1988
##  8 Brasil          1335
##  9 China            923
## 10 Estados Unidos   564
## # … with 65 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;where-do-they-live&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.2) Where do they live?&lt;/h3&gt;
&lt;p&gt;The most popular comuna for immigrants in 2019 was Santiago Centro with 30,207 arrivals. This is not surprising as Santiago Centro is the center of the city where there is more access to services, employment opportunities and housing. However, it must be noted that the data used only refers to the comuna of residence when an immigrant applied for their visa. Therefore, it is possible that they have since moved to a different sector of the city as they have become used to the city and have developed a support network.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;comuna_count &amp;lt;- visas2019STG %&amp;gt;% group_by(nombre_comuna) %&amp;gt;% count() %&amp;gt;% arrange(-n)

comuna_count&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 32 x 2
## # Groups:   nombre_comuna [32]
##    nombre_comuna        n
##    &amp;lt;chr&amp;gt;            &amp;lt;int&amp;gt;
##  1 Santiago         30207
##  2 Estación Central  8080
##  3 Independencia     7291
##  4 Quinta Normal     4343
##  5 San Miguel        4124
##  6 Recoleta          3871
##  7 Ñuñoa             3736
##  8 Las Condes        3591
##  9 La Florida        3571
## 10 Maipú             2780
## # … with 22 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The total number of immigrants in each comuna is added to the STGgeo data frame so that it can be mapped below. Each comuna is labelled, with details of which comunas correspond to each number provided in the table below the map.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;STGgeo &amp;lt;- left_join(STGgeo, comuna_count, by = &amp;quot;nombre_comuna&amp;quot;)

STGgeo &amp;lt;- STGgeo %&amp;gt;% rename(number_inmigrantes = n)

STGgeo &amp;lt;- cbind(STGgeo, st_coordinates(st_centroid(STGgeo$geometry)))

labels &amp;lt;- seq(1,32)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot() + geom_sf(data = STGgeo$geometry, aes(fill = STGgeo$number_inmigrantes)) + 
scale_fill_viridis_c(option = &amp;quot;inferno&amp;quot;,trans = &amp;#39;sqrt&amp;#39;) +
geom_text(data = STGgeo, aes(X, Y, label = labels), size = 3, color = &amp;quot;white&amp;quot;) +
geom_text(data = STGgeo %&amp;gt;% filter(nombre_comuna == &amp;quot;Santiago&amp;quot;), aes(X, Y, label = &amp;quot;1&amp;quot;), size = 3, color = &amp;quot;black&amp;quot;) +
annotation_north_arrow(aes(which_north = &amp;quot;true&amp;quot;, location = &amp;quot;br&amp;quot;), pad_y = unit(0.8, &amp;quot;cm&amp;quot;)) +
  annotation_scale(aes(location = &amp;quot;br&amp;quot;, style = &amp;quot;bar&amp;quot;)) +
  theme(panel.grid.major = element_line(color = gray(0.5), linetype = &amp;quot;dashed&amp;quot;)) +
  theme (panel.background = element_rect(fill = &amp;quot;light grey&amp;quot;)) +
  ggtitle(&amp;quot;5.1) Location of immigrants that arrived in 2019&amp;quot;) + xlab(&amp;quot;Longitude&amp;quot;) + ylab(&amp;quot;Latitude&amp;quot;) +
  labs(fill = &amp;quot;Number of Immigrants&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Migration/MigrationEN_files/figure-html/unnamed-chunk-14-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;cbind(STGgeo, labels) %&amp;gt;% select(nombre_comuna, labels)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##          nombre_comuna labels
## 1             Santiago      1
## 2            Cerrillos      2
## 3          Cerro Navia      3
## 4             Conchalí      4
## 5            El Bosque      5
## 6     Estación Central      6
## 7           Huechuraba      7
## 8        Independencia      8
## 9          La Cisterna      9
## 10          La Florida     10
## 11           La Granja     11
## 12          La Pintana     12
## 13            La Reina     13
## 14          Las Condes     14
## 15        Lo Barnechea     15
## 16           Lo Espejo     16
## 17            Lo Prado     17
## 18               Macul     18
## 19               Maipú     19
## 20               Ñuñoa     20
## 21 Pedro Aguirre Cerda     21
## 22           Peñalolén     22
## 23         Providencia     23
## 24            Pudahuel     24
## 25           Quilicura     25
## 26       Quinta Normal     26
## 27            Recoleta     27
## 28               Renca     28
## 29         San Joaquín     29
## 30          San Miguel     30
## 31           San Ramón     31
## 32            Vitacura     32&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;the-eastern-sector&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.4) The Eastern Sector&lt;/h3&gt;
&lt;p&gt;This publication and its part two counterpart aims to build a classification model to predict if an immigrant lives in the Eastern Sector. This sector contains the comunas of Providencia, Las Condes, Vitacura, and Lo Barnechea and is located to the north east of the city. These comunas are considered the most wealthy in the city and are identified in the below map.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;SectorOriente &amp;lt;- STGgeo %&amp;gt;% filter(nombre_comuna == &amp;#39;Providencia&amp;#39; | nombre_comuna == &amp;#39;Las Condes&amp;#39; | nombre_comuna == &amp;#39;Vitacura&amp;#39; | nombre_comuna == &amp;#39;Lo Barnechea&amp;#39;)

ggplot() + geom_sf(data = STGgeo$geometry, fill = &amp;quot;white&amp;quot;) + 
  geom_sf(data = SectorOriente$geometry, fill = &amp;quot;purple&amp;quot;) +
geom_text(data = STGgeo, aes(X, Y, label = labels), size = 3, color = &amp;quot;white&amp;quot;) +
annotation_north_arrow(aes(which_north = &amp;quot;true&amp;quot;, location = &amp;quot;br&amp;quot;), pad_y = unit(0.8, &amp;quot;cm&amp;quot;)) +
  annotation_scale(aes(location = &amp;quot;br&amp;quot;, style = &amp;quot;bar&amp;quot;)) +
  theme(panel.grid.major = element_line(color = gray(0.5), linetype = &amp;quot;dashed&amp;quot;)) +
  theme (panel.background = element_rect(fill = &amp;quot;light grey&amp;quot;)) +
  ggtitle(&amp;quot;5.2 Eastern Sector of Santiago&amp;quot;) + xlab(&amp;quot;Longitude&amp;quot;) + ylab(&amp;quot;Latitude&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Migration/MigrationEN_files/figure-html/unnamed-chunk-16-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;further-mapping&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6) Further Mapping&lt;/h2&gt;
&lt;p&gt;In this section four maps are presented.&lt;/p&gt;
&lt;p&gt;Map 6.1 shows the distribution of Venezuelan immigrants.&lt;/p&gt;
&lt;p&gt;Map 6.2 shows the distribution of Haitian immigrants.&lt;/p&gt;
&lt;p&gt;Map 6.3 shows the distribution of immigrants from the USA.&lt;/p&gt;
&lt;p&gt;Map 6.4 shows the distribution of Peruvian immigrants.&lt;/p&gt;
&lt;p&gt;These four nationalities were chosen as they play an important role in the immigration trends in Santiago. There has been a big increase in the number of Venezuelans in the last few years due to the political situation in their own country. The number of Haitians has also increased dramatically since 2015 due to the lower quality of life in their own country. The GDP per capita in Haiti is $868. This value is the lowest within the ten most prominent nationalities for immigrants that arrived to Santiago in 2019. Similarly it is interesting to explore the distribution of immigrants from the United States as it is the country with the highest GDP per capita. Finally, Peruvians are the nationality which historically has been the biggest contributor of immigrants to Chile. The GDP per capita (Banco Mundial, 2018) for each of the ten main nationalities are shown in US Dollars below.&lt;/p&gt;
&lt;p&gt;USA = $62,887
Peru = $6,941
Colombia = $6,668
Haití = $868
Bolivia = $3,549
Ecuador = $6,345
Argentina = $11,684
Brasil = $9,001
China = $9,771&lt;/p&gt;
&lt;p&gt;For comparison the GDP per capita of Chile is $15,923.&lt;/p&gt;
&lt;div id=&#34;venezuelans&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.1) Venezuelans&lt;/h3&gt;
&lt;p&gt;This map shows that Venezuelans were concentrated in Santiago Centro with 21,387 people, corresponding to 36.88% of the Venezuelans that arrived in 2019. Estacion Central and Independencia were the second and third most populated comunas. In the eastern sector there were 1,998 Venezuelans.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;venezuela_count &amp;lt;- visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Venezuela&amp;#39;) %&amp;gt;% group_by(nombre_comuna) %&amp;gt;% count() %&amp;gt;% arrange(-n)

venezuela_count&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 32 x 2
## # Groups:   nombre_comuna [32]
##    nombre_comuna        n
##    &amp;lt;chr&amp;gt;            &amp;lt;int&amp;gt;
##  1 Santiago         21387
##  2 Estación Central  5628
##  3 Independencia     4710
##  4 San Miguel        3318
##  5 Quinta Normal     2805
##  6 Ñuñoa             2622
##  7 La Florida        2339
##  8 Macul             1575
##  9 Maipú             1537
## 10 La Cisterna       1237
## # … with 22 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Venezuela&amp;#39; &amp;amp; nombre_comuna %in% c(&amp;#39;Providencia&amp;#39;, &amp;quot;Las Condes&amp;quot;, &amp;#39;Vitacura&amp;#39;, &amp;#39;Lo Barnechea&amp;#39;)) %&amp;gt;% count()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      n
## 1 1998&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;STGgeo &amp;lt;- left_join(STGgeo, venezuela_count, by = &amp;quot;nombre_comuna&amp;quot;)

STGgeo &amp;lt;- STGgeo %&amp;gt;% rename(numero_venezuelanos = n)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot() + geom_sf(data = STGgeo$geometry, aes(fill = STGgeo$numero_venezuelanos)) + 
scale_fill_viridis_c(option = &amp;quot;inferno&amp;quot;,trans = &amp;#39;sqrt&amp;#39;) +
geom_text(data = STGgeo, aes(X, Y, label = labels), size = 3, color = &amp;quot;white&amp;quot;) +
annotation_north_arrow(aes(which_north = &amp;quot;true&amp;quot;, location = &amp;quot;br&amp;quot;), pad_y = unit(0.8, &amp;quot;cm&amp;quot;)) +
  annotation_scale(aes(location = &amp;quot;br&amp;quot;, style = &amp;quot;bar&amp;quot;)) +
  theme(panel.grid.major = element_line(color = gray(0.5), linetype = &amp;quot;dashed&amp;quot;)) +
  theme (panel.background = element_rect(fill = &amp;quot;light grey&amp;quot;)) +
  ggtitle(&amp;quot;6.1 Location of Venezuelans that arrived in 2019&amp;quot;) + xlab(&amp;quot;Longitude&amp;quot;) + ylab(&amp;quot;Latitude&amp;quot;) +
  labs(fill = &amp;quot;Number of immigrants&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Migration/MigrationEN_files/figure-html/unnamed-chunk-19-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;haitians&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;6.2) Haitians&lt;/h4&gt;
&lt;p&gt;The below map highlights that the most popular comuna for Haitians was Quilicura to the north of Santiago with 984 arrivals, accounting for 13.79% of the 7,135 Haitians that arrived in 2019. Estacion Central also had a high amount of Haitians with 758 arriving (10.62%). Likewise Santiago Centro had 523 (7.33%) arrivals. It is also interesting to note the lack of Haitians in the Eastern Sector of the city with only 25 Haitians arriving there in 2019.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;haitiano_count &amp;lt;- visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Haití&amp;#39;) %&amp;gt;% group_by(nombre_comuna) %&amp;gt;% count() %&amp;gt;% arrange(-n)

visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Haití&amp;#39;) %&amp;gt;% count()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      n
## 1 7135&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;haitiano_count&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 32 x 2
## # Groups:   nombre_comuna [32]
##    nombre_comuna           n
##    &amp;lt;chr&amp;gt;               &amp;lt;int&amp;gt;
##  1 Quilicura             984
##  2 Estación Central      758
##  3 Santiago              523
##  4 Lo Espejo             426
##  5 Recoleta              375
##  6 Pedro Aguirre Cerda   367
##  7 Cerro Navia           363
##  8 Conchalí              280
##  9 Quinta Normal         252
## 10 El Bosque             248
## # … with 22 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Haití&amp;#39; &amp;amp; nombre_comuna %in% c(&amp;#39;Providencia&amp;#39;, &amp;quot;Las Condes&amp;quot;, &amp;#39;Vitacura&amp;#39;, &amp;#39;Lo Barnechea&amp;#39;)) %&amp;gt;% count()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##    n
## 1 25&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;STGgeo &amp;lt;- left_join(STGgeo, haitiano_count, by = &amp;quot;nombre_comuna&amp;quot;)

STGgeo &amp;lt;- STGgeo %&amp;gt;% rename(numero_haitianos = n)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot() + geom_sf(data = STGgeo$geometry, aes(fill = STGgeo$numero_haitianos)) + 
scale_fill_viridis_c(option = &amp;quot;inferno&amp;quot;,trans = &amp;#39;sqrt&amp;#39;) +
geom_text(data = STGgeo, aes(X, Y, label = labels), size = 3, color = &amp;quot;white&amp;quot;) +
annotation_north_arrow(aes(which_north = &amp;quot;true&amp;quot;, location = &amp;quot;br&amp;quot;), pad_y = unit(0.8, &amp;quot;cm&amp;quot;)) +
  annotation_scale(aes(location = &amp;quot;br&amp;quot;, style = &amp;quot;bar&amp;quot;)) +
  theme(panel.grid.major = element_line(color = gray(0.5), linetype = &amp;quot;dashed&amp;quot;)) +
  theme (panel.background = element_rect(fill = &amp;quot;light grey&amp;quot;)) +
  ggtitle(&amp;quot;6.2 Location of Haitians that arrived in 2019&amp;quot;) + xlab(&amp;quot;Longitude&amp;quot;) + ylab(&amp;quot;Latitude&amp;quot;) +
  labs(fill = &amp;quot;Number of immigrants&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Migration/MigrationEN_files/figure-html/unnamed-chunk-22-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;united-states-of-america&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.3) United States of America&lt;/h3&gt;
&lt;p&gt;Of the 564 US-Americans that arrived in 2019, 252 (62.41%) lived in the Eastern Sector. As was the case for Venezuelans and Haitians, Santiago Centro again received a high percentage of the arrivals with 80 people (14.18%). It is also interesting that there were various comunas without US-American arrivals in 2019, this was not the case for the other two nationalities analysed so far with Venezuelans and Haitians present in each of Santiago’s comunas.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;eeuu_count &amp;lt;- visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Estados Unidos&amp;#39;) %&amp;gt;% group_by(nombre_comuna) %&amp;gt;% count() %&amp;gt;% arrange(-n)

eeuu_count&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 23 x 2
## # Groups:   nombre_comuna [23]
##    nombre_comuna        n
##    &amp;lt;chr&amp;gt;            &amp;lt;int&amp;gt;
##  1 Providencia        208
##  2 Las Condes         110
##  3 Santiago            80
##  4 Maipú               57
##  5 Ñuñoa               30
##  6 Vitacura            21
##  7 Lo Barnechea        13
##  8 Estación Central    11
##  9 Macul                5
## 10 Independencia        4
## # … with 13 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Estados Unidos&amp;#39;) %&amp;gt;% count() &lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     n
## 1 564&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Estados Unidos&amp;#39; &amp;amp; nombre_comuna %in% c(&amp;#39;Providencia&amp;#39;, &amp;quot;Las Condes&amp;quot;, &amp;#39;Vitacura&amp;#39;, &amp;#39;Lo Barnechea&amp;#39;)) %&amp;gt;% count()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     n
## 1 352&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;STGgeo &amp;lt;- left_join(STGgeo, eeuu_count, by = &amp;quot;nombre_comuna&amp;quot;)

STGgeo &amp;lt;- STGgeo %&amp;gt;% rename(numero_eeuu = n)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot() + geom_sf(data = STGgeo$geometry, aes(fill = STGgeo$numero_eeuu)) + 
scale_fill_viridis_c(option = &amp;quot;inferno&amp;quot;,trans = &amp;#39;sqrt&amp;#39;) +
geom_text(data = STGgeo, aes(X, Y, label = labels), size = 3, color = &amp;quot;white&amp;quot;) +
annotation_north_arrow(aes(which_north = &amp;quot;true&amp;quot;, location = &amp;quot;br&amp;quot;), pad_y = unit(0.8, &amp;quot;cm&amp;quot;)) +
  annotation_scale(aes(location = &amp;quot;br&amp;quot;, style = &amp;quot;bar&amp;quot;)) +
  theme(panel.grid.major = element_line(color = gray(0.5), linetype = &amp;quot;dashed&amp;quot;)) +
  theme (panel.background = element_rect(fill = &amp;quot;light grey&amp;quot;)) +
  ggtitle(&amp;quot;6.3 Location of US-Americans that arrived in 2019&amp;quot;) + xlab(&amp;quot;Longitude&amp;quot;) + ylab(&amp;quot;Latitude&amp;quot;) +
  labs(fill = &amp;quot;Number of Immigrants&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Migration/MigrationEN_files/figure-html/unnamed-chunk-25-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;peruvians&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.4) Peruvians&lt;/h3&gt;
&lt;p&gt;Santiago Centro, Recoleta, and Independencia were the three comunas with the most Peruvian arrivals in 2019 with 2,785 (24.27%), 1,272 (11.09%), and 1,092 (9.51%) respectively. In the Eastern Sector there were 855 (7.45%) Peruvians.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;peruano_count &amp;lt;- visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Perú&amp;#39;) %&amp;gt;% group_by(nombre_comuna) %&amp;gt;% count() %&amp;gt;% arrange(-n)

visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Perú&amp;#39;) %&amp;gt;% count()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       n
## 1 11474&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;visas2019STG %&amp;gt;% filter(PAÍS == &amp;#39;Perú&amp;#39; &amp;amp; nombre_comuna %in% c(&amp;#39;Providencia&amp;#39;, &amp;quot;Las Condes&amp;quot;, &amp;#39;Vitacura&amp;#39;, &amp;#39;Lo Barnechea&amp;#39;)) %&amp;gt;% count()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##     n
## 1 855&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;peruano_count&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 32 x 2
## # Groups:   nombre_comuna [32]
##    nombre_comuna        n
##    &amp;lt;chr&amp;gt;            &amp;lt;int&amp;gt;
##  1 Santiago          2785
##  2 Recoleta          1272
##  3 Independencia     1092
##  4 Estación Central   634
##  5 Quinta Normal      585
##  6 Conchalí           475
##  7 Peñalolén          415
##  8 Las Condes         373
##  9 La Florida         335
## 10 Lo Prado           320
## # … with 22 more rows&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;STGgeo &amp;lt;- left_join(STGgeo, peruano_count, by = &amp;quot;nombre_comuna&amp;quot;)

STGgeo &amp;lt;- STGgeo %&amp;gt;% rename(numero_peruanos = n)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot() + geom_sf(data = STGgeo$geometry, aes(fill = STGgeo$numero_peruanos)) + 
scale_fill_viridis_c(option = &amp;quot;inferno&amp;quot;,trans = &amp;#39;sqrt&amp;#39;) +
geom_text(data = STGgeo, aes(X, Y, label = labels), size = 3, color = &amp;quot;white&amp;quot;) +
annotation_north_arrow(aes(which_north = &amp;quot;true&amp;quot;, location = &amp;quot;br&amp;quot;), pad_y = unit(0.8, &amp;quot;cm&amp;quot;)) +
  annotation_scale(aes(location = &amp;quot;br&amp;quot;, style = &amp;quot;bar&amp;quot;)) +
  theme(panel.grid.major = element_line(color = gray(0.5), linetype = &amp;quot;dashed&amp;quot;)) +
  theme (panel.background = element_rect(fill = &amp;quot;light grey&amp;quot;)) +
  ggtitle(&amp;quot;6.4 Location of Peruvians tha arrived in 2019&amp;quot;) + xlab(&amp;quot;Longitude&amp;quot;) + ylab(&amp;quot;Latitude&amp;quot;) +
  labs(fill = &amp;quot;Number of immigrants&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Migration/MigrationEN_files/figure-html/unnamed-chunk-28-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;analysis-summary&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.5) Analysis Summary&lt;/h3&gt;
&lt;p&gt;The following conclusions can be taken from the above analysis:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;There were more immigrants from Central America and South America.&lt;/li&gt;
&lt;li&gt;Speaking Spanish is an important factor for determining if there are many immigrants from a certain nationality.&lt;/li&gt;
&lt;li&gt;US-Americans have the highest GDP per capita and were the only analysed nationality with the majority of their population living in the Eastern Sector.&lt;/li&gt;
&lt;li&gt;Haitians have the lowest GDP per capita and also had the lowest percentage of people living in the Eastern Sector.&lt;/li&gt;
&lt;li&gt;Haitians were more widely dispersed with Quilicura, to the north of Santiago having the most Haitians. In comparison Venezuelans, US-Americans, and Peruvians were more concentrated around the center of the city.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;7) Conclusion&lt;/h2&gt;
&lt;p&gt;In this part 1 publication immigration data from 2019 for Santiago has been explored with maps created for the distribution of Venezuelan, Haitian, US-American, and Peruvian immigrants, with some conclusions drawn. A part 2 publication will follow where a classification model will be created to try and classify if an immigrant lives in the Eastern Sector of the city. Thank you for reading this publication.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Titanic - Random Forest</title>
      <link>/en/post/titanic-rf/titanicrf-en/</link>
      <pubDate>Tue, 02 Jun 2020 00:00:00 +0000</pubDate>
      <guid>/en/post/titanic-rf/titanicrf-en/</guid>
      <description>


&lt;p&gt;In the last &lt;a href=&#34;https://www.statcitypro.com/en/post/titanc-part2/titanic-part2/&#34;&gt;publication&lt;/a&gt; from StatCityPro a decision tree classification model was created with the aim of predicting if a passenger on the Titanic survived or died. Cross validation was used with an accuracy of 80.79% achieved.&lt;/p&gt;
&lt;p&gt;In this new publication a Random Forest model is used to try and improve the accuracy. The data used is the same as the data which was being used at the end of the previous publication. (&lt;em&gt;total&lt;/em&gt;, &lt;em&gt;train_val&lt;/em&gt;, &lt;em&gt;train_test_val&lt;/em&gt;). Therefore, feature engineering has already been carried out with the data ready for model creation.&lt;/p&gt;
&lt;div id=&#34;packages&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;2) Packages&lt;/h2&gt;
&lt;p&gt;The following packages are used in this publication.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)
library(tidyr)
library(ggplot2)
library(knitr)
library(DT)
library(purrr)
library(corrplot)
library(randomForest)
library(caret)
library(rpart)
library(rpart.plot)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;loading-the-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;3) Loading the Data&lt;/h2&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;setwd(&amp;quot;~/Documents/Machine Learning/15. Hugo/academic-kickstart-master/content/en/post/Titanic-RF&amp;quot;)

total &amp;lt;- read.csv(&amp;quot;total2.csv&amp;quot;)

total &amp;lt;- total[,-1]

train_val &amp;lt;- read.csv(&amp;quot;train_val.csv&amp;quot;)

train_test_val &amp;lt;- read.csv(&amp;quot;train_test_val.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The variables of Title and Age Group are changed to factors.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;train_val$Title &amp;lt;- as.factor(train_val$Title)
train_val$Age.Group &amp;lt;- as.factor(train_val$Age.Group)
train_val$Survived &amp;lt;- as.factor(train_val$Survived)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;variables-and-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;4) Variables and Data&lt;/h2&gt;
&lt;p&gt;The data base &lt;em&gt;total&lt;/em&gt; has 1,309 observations and 16 variables. Of these 1,309 observations, 891 are training data and 418 are testing data.&lt;/p&gt;
&lt;p&gt;To train the model the 891 training observations are used, and are divided into two groups. The first group is &lt;em&gt;train_val&lt;/em&gt; which has 714 observations. This group is used to train the model. Then the model is tested using the second group &lt;em&gt;train_test_val&lt;/em&gt; which acts as a preliminary testing group. After the feature engineering that took place in the &lt;a href=&#34;https://www.statcitypro.com/en/post/titanic/titanic-en&#34;&gt;part 1&lt;/a&gt; publication these data bases only have seven variables.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;Variable&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Survived&lt;/td&gt;
&lt;td&gt;Survived (1) or Died (0)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Pclass&lt;/td&gt;
&lt;td&gt;Social class of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Title&lt;/td&gt;
&lt;td&gt;Title of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Sexo&lt;/td&gt;
&lt;td&gt;Sex of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Age Group&lt;/td&gt;
&lt;td&gt;Age group of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Family_size&lt;/td&gt;
&lt;td&gt;Number of family members on Titanic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Embarked&lt;/td&gt;
&lt;td&gt;Port of embarkation&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;div id=&#34;what-is-a-random-forest-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;5) What is a Random Forest Model?&lt;/h2&gt;
&lt;p&gt;A Random Forest is a collection of decision trees that are joined together in a forest. This collection of trees is what makes a Random Forest Model more reliable than a Decision Tree Model. Each tree gives a classification of survived or deceased for each observation. For each observation the final result is the most frequent classification. For example in a model with 500 trees, if 300 predict that an observation survived and 200 predict that they died, the observation is classified as survived.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;creating-the-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6) Creating the Model&lt;/h2&gt;
&lt;p&gt;The model is created using survived as the dependent variable and the other six variables as independent variables. The model is ran against the &lt;em&gt;train_val&lt;/em&gt; data and obtains an accuracy of 83.47% (100 - 16.53 (error rate)). The model uses 500 trees with two variables tested at each node. Further on these settings are verified to check the model can not be improved with different settings.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
rf_model &amp;lt;- randomForest(Survived ~ Pclass + Title + Sex + Embarked + Family_size + Age.Group, data = train_val, ntree = 500)


rf_model&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
##  randomForest(formula = Survived ~ Pclass + Title + Sex + Embarked +      Family_size + Age.Group, data = train_val, ntree = 500) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 16.53%
## Confusion matrix:
##     0   1 class.error
## 0 409  31  0.07045455
## 1  87 187  0.31751825&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;number-of-trees&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6.1) Number of Trees&lt;/h2&gt;
&lt;p&gt;In this section the number of trees in the model is reviewed to see if it needs to be increased. A table is created to show the error rate for each of the 500 trees. For each tree there are tree error rates:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;for values of 0 (somebody who died)&lt;/li&gt;
&lt;li&gt;for values of 1 (somebody who survived)&lt;/li&gt;
&lt;li&gt;for all values (people who died and survived)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These error rates are graphed. It is hoped that before the 500th tree the error rate will have stabilised with a flat line present on the graph.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;oob.error.data &amp;lt;- data.frame(
  Trees=rep(1:nrow(rf_model$err.rate), times=3),
  Type=rep(c(&amp;quot;OOB&amp;quot;, &amp;quot;0&amp;quot;, &amp;quot;1&amp;quot;), each=nrow(rf_model$err.rate)),
  Error=c(rf_model$err.rate[,&amp;quot;OOB&amp;quot;],
          rf_model$err.rate[,&amp;quot;0&amp;quot;],
          rf_model$err.rate[,&amp;quot;1&amp;quot;]))&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(data=oob.error.data, aes(x=Trees, y=Error)) + 
  geom_line(aes(color=Type))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanic-RF/TitanicRF-EN_files/figure-html/unnamed-chunk-6-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;p&gt;In the above graph it is clear that the error rate stabilises before the 500th tree. This means that it is not necessary to add more trees to the model, as they would not reduce the error rate any more.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;number-of-variables&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6.2) Number of Variables&lt;/h2&gt;
&lt;p&gt;In this section a test is run to see how many variables should be tested at each node in the model. Currently, two variables are tested.&lt;/p&gt;
&lt;p&gt;In &lt;em&gt;oob.values&lt;/em&gt; it is shown that mtry=2, with two tested variables, gives the lowest error value (0.1666667) and therefore is the value that is used in the model.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;oob.values &amp;lt;- vector(length = 10)
for(i in 1:10) {
  temp.model &amp;lt;- randomForest(Survived ~ Pclass + Title + Sex + Embarked + Family_size + Age.Group, data = train_val, mtry=i, ntree=500)
  oob.values[i] &amp;lt;- temp.model$err.rate[nrow(temp.model$err.rate),1]
  }

oob.values&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] 0.1918768 0.1666667 0.1778711 0.1806723 0.1764706 0.1778711 0.1806723
##  [8] 0.1806723 0.1792717 0.1736695&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;variable-importance&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6.3) Variable Importance&lt;/h2&gt;
&lt;p&gt;The Gini value can be used to determine which variable are the most and least important in the model. The below table and graph show that the variables Age_Group and Embarked have a low importance in the model. Therefore a new model is tried without these two variables.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;importance(rf_model)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##             MeanDecreaseGini
## Pclass              33.40132
## Title               62.14757
## Sex                 42.51139
## Embarked            11.08408
## Family_size         22.26955
## Age.Group           11.74166&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;varImpPlot(rf_model)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanic-RF/TitanicRF-EN_files/figure-html/unnamed-chunk-9-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;new-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;7) New Model&lt;/h2&gt;
&lt;p&gt;A new model is created without the variables for Age.Group and Embarked. The settings of 500 trees and two variables at each node are used.&lt;/p&gt;
&lt;p&gt;However, when the model is run using the &lt;em&gt;train_val&lt;/em&gt; data it seems that the two removed variables are in fact needed in the model as without them the accuracy is reduced to 82.63% (100 - 17.37% (error rate)). Therefore, the first model with all of the independent variables is used as the final model.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;train_val1=train_val[,c(-4,-6)]

train_test_val1=train_test_val[,c(-4,-6)]&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
rf_model2 &amp;lt;- randomForest(Survived ~ Pclass + Title + Sex + Family_size, data = train_val1, ntree=500)

rf_model2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
## Call:
##  randomForest(formula = Survived ~ Pclass + Title + Sex + Family_size,      data = train_val1, ntree = 500) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 17.37%
## Confusion matrix:
##     0   1 class.error
## 0 387  53   0.1204545
## 1  71 203   0.2591241&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;varImpPlot(rf_model2)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanic-RF/TitanicRF-EN_files/figure-html/unnamed-chunk-12-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;testing-the-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;8) Testing the Model&lt;/h2&gt;
&lt;p&gt;In this section the model is tested using the &lt;em&gt;train_test_val&lt;/em&gt; data. In order to prepare this data some variables are converted to factors. The model is then run with the dependent variable hidden to predict which people survived or died. The predictions are then compared to the real data in a confusion matrix with the model achieving an accuracy of 83.05% and a kappa value of 0.6316.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;train_test_val$Title &amp;lt;- as.factor(train_test_val$Title)
train_test_val$Age.Group &amp;lt;- as.factor(train_test_val$Age.Group)
train_test_val$Survived &amp;lt;- as.factor(train_test_val$Survived)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
rf_predictions &amp;lt;- predict(rf_model, train_test_val)
confusionMatrix(train_test_val$Survived, rf_predictions)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 99 10
##          1 20 48
##                                          
##                Accuracy : 0.8305         
##                  95% CI : (0.767, 0.8826)
##     No Information Rate : 0.6723         
##     P-Value [Acc &amp;gt; NIR] : 1.683e-06      
##                                          
##                   Kappa : 0.6316         
##                                          
##  Mcnemar&amp;#39;s Test P-Value : 0.1003         
##                                          
##             Sensitivity : 0.8319         
##             Specificity : 0.8276         
##          Pos Pred Value : 0.9083         
##          Neg Pred Value : 0.7059         
##              Prevalence : 0.6723         
##          Detection Rate : 0.5593         
##    Detection Prevalence : 0.6158         
##       Balanced Accuracy : 0.8298         
##                                          
##        &amp;#39;Positive&amp;#39; Class : 0              
## &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;9) Conclusion&lt;/h2&gt;
&lt;p&gt;In this publication a Random Forest Model has been created to predict if somebody survived or died on board the titanic. It was hopped that the model would improve on the accuracy achieved using a decision tree model in a previous publication. The accuracy was improved with the Random Forest Model achieving an accuracy of 83.05% in comparison to the 80.79% of the Decision Tree Model. 500 trees were used with two variables tested at each node. Thank you for taking the time to read this publication and hopefully it has been of use.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Titanic - Who Survived? - Part 2</title>
      <link>/en/post/titanc-part2/titanic-part2/</link>
      <pubDate>Tue, 26 May 2020 00:00:00 +0000</pubDate>
      <guid>/en/post/titanc-part2/titanic-part2/</guid>
      <description>


&lt;p&gt;This publication will follow on from &lt;a href=&#34;link&#34;&gt;Part one&lt;/a&gt; on the Titanic to conduct data analysis for the passengers onboard and to create a classification decision tree model to predict if a passenger survived or died. Part one covered the data preparation process.&lt;/p&gt;
&lt;div id=&#34;packages&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;2) Packages&lt;/h2&gt;
&lt;p&gt;The following packages are used in this publication.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)
library(readr)
library(tidyr)
library(ggplot2)
library(knitr)
library(DT)
library(purrr)
library(corrplot)
library(randomForest)
library(caret)
library(rpart)
library(rpart.plot)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;data-exploration&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;3) Data Exploration&lt;/h2&gt;
&lt;p&gt;With the data already prepared in part 1 the next step is to carry out some data exploration to better understand the data’s characteristics. Only the train data is be used in this data exploration section.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;setwd(&amp;quot;~/Documents/Machine Learning/15. Hugo/academic-kickstart-master/content/en/post/Titanc-part2&amp;quot;)


total &amp;lt;- read_csv(&amp;quot;total2.csv&amp;quot;)

total &amp;lt;- total[,-1]

test &amp;lt;- read.csv(&amp;quot;test.csv&amp;quot;)

train &amp;lt;- read.csv(&amp;quot;train.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;pclass&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;3.1) Pclass&lt;/h3&gt;
&lt;p&gt;The below graph shows the survival of passengers in each of the three classes. Red represents passengers that died, and blue passengers that survived. The white line is the average survival rate for passengers in the training data (38.38%).&lt;/p&gt;
&lt;p&gt;First class passengers had a survival rate higher than the average. Second class passengers followed this trend, all be it to a lesser degree with a survival rate of close to 50%. In comparison third class passengers had a lower survival rate of 25%.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot() + 
  
  geom_bar(data = total %&amp;gt;% filter(group == &amp;#39;train&amp;#39;), aes(Pclass, fill = as.factor(Survived)), position = &amp;#39;fill&amp;#39;) + 
  
  geom_hline(yintercept = 0.3838, col = &amp;quot;white&amp;quot;, lty=2, size=2) +
  
    scale_fill_brewer(palette=&amp;quot;Set1&amp;quot;) +

  ylab(&amp;quot;Survival Rate&amp;quot;) +
  
  xlab(&amp;quot;Class&amp;quot;) + 

  ggtitle(&amp;quot;Survival Rate by Class&amp;quot;) + 
  
  labs(fill = &amp;quot;Survived&amp;quot;) +
  
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;title&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.2) Title&lt;/h3&gt;
&lt;p&gt;The following graph highlights how passengers with the tile ‘Mr’ had a very low survival rate. In comparision a child with the title ‘Master’ or an adult woman with the title “Miss” had a greater
chance of survival with survival rates of close to 70%.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot() + 
  
  geom_bar(data = total %&amp;gt;% filter(group == &amp;#39;train&amp;#39;), aes(Title, fill = as.factor(Survived)), position = &amp;#39;fill&amp;#39;) + 
  
  geom_hline(yintercept = 0.3838, col = &amp;quot;white&amp;quot;, lty=2, size=2) +
  
    scale_fill_brewer(palette=&amp;quot;Set1&amp;quot;) +

  ylab(&amp;quot;Survival Rate&amp;quot;) +

  ggtitle(&amp;quot;Survival Rate by Title&amp;quot;) + 
  
  labs(fill = &amp;quot;Survived&amp;quot;) +
  
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;port&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.3) Port&lt;/h3&gt;
&lt;p&gt;There were three ports of embarkation: Southampton, Great Britain; Cherborg, France; and Queenstown, Ireland. There is not that much variation in the survival rates of passengers from different ports, however, passengers from Cherborg had the highest survival rate.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(total %&amp;gt;% filter(group==&amp;quot;train&amp;quot;), aes(Embarked, fill=as.factor(Survived))) +

  geom_bar(position = &amp;quot;fill&amp;quot;) +

  scale_fill_brewer(palette=&amp;quot;Set1&amp;quot;) +

  ylab(&amp;quot;Survival Rate&amp;quot;) +

  geom_hline(yintercept=0.38, col=&amp;quot;white&amp;quot;, lty=2, size=2) +

  ggtitle(&amp;quot;Survival Rate by Emarking Point&amp;quot;) + 
  
  labs(fill = &amp;quot;Survived&amp;quot;) +

  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;fare-and-class&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.4) Fare and Class&lt;/h3&gt;
&lt;p&gt;The below graph show the relationship between survival and fare. The graph suggests that passengers with a more expensive ticket were more likely to survive. For example, there is a higher concentration of tickets with a cost of more than £50, found in those passengers who survived.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(total %&amp;gt;% filter(group==&amp;quot;train&amp;quot;), aes(Fare, Survived)) +
  
  geom_point() +

  ylab(&amp;quot;Survival Rate&amp;quot;) +

  ggtitle(&amp;quot;Survival vs. Fare&amp;quot;) + 
  
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-6-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Class can also be plotted by fare with this graph suggesting that there is potentially a strong correlation between class and fare.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(total %&amp;gt;% filter(group==&amp;quot;train&amp;quot;), aes(Pclass, Fare)) +
  
  geom_point() +

  ylab(&amp;quot;Fare (£)&amp;quot;) +
  
  xlab(&amp;quot;Class&amp;quot;) +

  ggtitle(&amp;quot;Class vs. Fare&amp;quot;) + 
  
  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-7-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;over-correlation&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;5.4.1) Over Correlation&lt;/h4&gt;
&lt;p&gt;Following on from the above suggestion of a correlation between class and fare the correlation for these two variables is calculated. The below graphic shows there is a negative correlation of 0.55 between these two variables. This correlation could be detrimental to the model with class and fare both having the same impact on the dependent variable and multicollinearity occurring. Therefore fare will not be included in the model.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;tbl_corr &amp;lt;- total %&amp;gt;%

  filter(group==&amp;quot;train&amp;quot;) %&amp;gt;%

  select(-PassengerId, -SibSp, -Parch) %&amp;gt;%

  select_if(is.numeric) %&amp;gt;%

  cor(use=&amp;quot;complete.obs&amp;quot;) %&amp;gt;%

  corrplot.mixed(tl.cex=0.85)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-8-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;sex&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.5) Sex&lt;/h3&gt;
&lt;p&gt;This graph shows that females had a higher rate of survival that males. Almost 75% of the females survived in comparison with close to 23% of the males.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(total %&amp;gt;% filter(group==&amp;quot;train&amp;quot;), aes(Sex, fill=as.factor(Survived))) +

  geom_bar(position = &amp;quot;fill&amp;quot;) +

  scale_fill_brewer(palette=&amp;quot;Set1&amp;quot;) +

  ylab(&amp;quot;Survival Rate&amp;quot;) +

  geom_hline(yintercept=0.38, col=&amp;quot;white&amp;quot;, lty=2, size=2) +

  ggtitle(&amp;quot;Survival Rate by Sex&amp;quot;) + 
  
  labs(fill = &amp;quot;Survived&amp;quot;) +

  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-9-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;sex-y-class&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;5.5.1) Sex y Class&lt;/h4&gt;
&lt;p&gt;The following graph shows how sex had a very strong impact on the chances of survival. To be a female from first or second class almost was a characteristic of survival, and almost 50% of the females in third class survived. In comparison to these figures the survival rate for males, without taking into account their class, was never higher than the average survival rate for all passengers.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(total %&amp;gt;% filter(group==&amp;quot;train&amp;quot;), aes(Pclass, fill=as.factor(Survived))) +
  
  facet_wrap(~Sex, scale = &amp;quot;free&amp;quot;) +

  geom_bar(position = &amp;quot;fill&amp;quot;) +

  scale_fill_brewer(palette=&amp;quot;Set1&amp;quot;) +

  ylab(&amp;quot;Survival Rate&amp;quot;) +

  geom_hline(yintercept=0.38, col=&amp;quot;white&amp;quot;, lty=2, size=2) +

  ggtitle(&amp;quot;Survival Rate by Sex and Class&amp;quot;) + 
  
  labs(fill = &amp;quot;Survived&amp;quot;) +

  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-10-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;cherborg-sex-and-class&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;5.5.2) Cherborg, Sex and Class&lt;/h4&gt;
&lt;p&gt;The below graph splits the variables of port, sex and class to see how these variables impacted survival. Some interesting trends are identified.&lt;/p&gt;
&lt;p&gt;Firstly, almost all the females from first and second class survived, regardless of the port where they started their journey. Females from third class did not have such luck with lower survival rates depending on which port they boarded the ship. Females from Southampton had a survival rate particularmente lower than the other females.&lt;/p&gt;
&lt;p&gt;In relation to the male passengers there were higher survival rates for those who had boarded the boat in Southampton and Cherborg. Additionally, Cherborg had the highest male survival rate for each of the three classes. Finally, almost all of the males from Queenstown died, with third class males from this port having the highest survival rate from male Queenstown passengers.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(total %&amp;gt;% filter(group==&amp;quot;train&amp;quot;), aes(Embarked, fill = as.factor(Survived))) + 
  
  facet_wrap(~Sex~Pclass, scale = &amp;quot;free&amp;quot;) +

  geom_bar(position = &amp;quot;fill&amp;quot;) + 
  
  scale_fill_brewer(palette=&amp;quot;Set1&amp;quot;) +

  ylab(&amp;quot;Survival Rate&amp;quot;) +

  ggtitle(&amp;quot;Survival Rate by Emarking Point&amp;quot;) + 
  
  labs(fill = &amp;quot;Survived&amp;quot;) +
  
    geom_hline(yintercept=0.38, col=&amp;quot;white&amp;quot;, lty=2, size=2) +

  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;family-size&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;5.6) Family Size&lt;/h3&gt;
&lt;p&gt;In the below graph it is noted that families of two, three, or four people on the Titanic had a higher rate of survival.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;ggplot(total %&amp;gt;% filter(group==&amp;quot;train&amp;quot;), aes(Family_size, fill=as.factor(Survived))) +

  geom_bar(position = &amp;quot;fill&amp;quot;) +
  
  scale_fill_brewer(palette=&amp;quot;Set1&amp;quot;) +

  ylab(&amp;quot;Survival Rate&amp;quot;) +

  geom_hline(yintercept=0.38, col=&amp;quot;white&amp;quot;, lty=2, size=2) +

  ggtitle(&amp;quot;Survival Rate by Family Size and Class&amp;quot;) + 
  
  labs(fill = &amp;quot;Survived&amp;quot;) +

  theme_minimal()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-12-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;creating-the-model&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;6) Creating the Model&lt;/h2&gt;
&lt;div id=&#34;preparing-the-data&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.1) Preparing the Data&lt;/h3&gt;
&lt;p&gt;Firstly, the variables used in the model need to be chosen. As previously explained, Fare and Cabin are not used. The train observations are put in a separate group and then divided into two separate groups:&lt;/p&gt;
&lt;p&gt;train_val = 80% of the training observations&lt;/p&gt;
&lt;p&gt;train_test_val = 20% of the training observations&lt;/p&gt;
&lt;p&gt;The train_val is used to train the model. Then the model is tested firstly using the train_test_val. The results of this testing are used to adjust the model so that the best settings can be used when testing the model with the real test data.&lt;/p&gt;
&lt;p&gt;Finally with the model adjusted the model is tested using the real test data with the dependent variable hidden.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;feauter1 &amp;lt;-total[1:891, c(&amp;quot;Pclass&amp;quot;, &amp;quot;Title&amp;quot;,&amp;quot;Sex&amp;quot;,&amp;quot;Embarked&amp;quot;,&amp;quot;Family_size&amp;quot;,&amp;quot;Age Group&amp;quot;, &amp;quot;Survived&amp;quot;)]

feauter1$Survived &amp;lt;- as.factor(feauter1$Survived)

set.seed(500)

ind &amp;lt;- createDataPartition(feauter1$Survived,times=1,p=0.8,list=FALSE)

train_val &amp;lt;- feauter1[as.vector(ind),]

train_test_val &amp;lt;- feauter1[-ind,]&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;the-distribution-of-the-dependent-variable&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.2) The Distribution of the Dependent Variable&lt;/h3&gt;
&lt;p&gt;The distribution of passengers that survived and died in the train_val and train_test_val groups will be analysed below to ensure that there is an equal distribution between the two groups. The distribution of survivors and fatalities across the groups is equal with a ratio of 6 deaths to 4 survivors.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(prop.table(table(train$Survived)*100),digits = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   0   1 
## 0.6 0.4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(prop.table(table(train_val$Survived)*100),digits = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   0   1 
## 0.6 0.4&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;round(prop.table(table(train_test_val$Survived)*100),digits = 1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##   0   1 
## 0.6 0.4&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;decision-tree-model&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.3) Decision Tree Model&lt;/h3&gt;
&lt;p&gt;In this section a decision tree model is created using the train_val group which represents 54% of the total data. Then the train_test_val group is used to test and make adjustments to the model.&lt;/p&gt;
&lt;p&gt;Having created the model the Confusion Matrix can be used to see its accuracy. The model has an accuracy of 0.8389 with a kappa of 0.642. Cross Validation is used to verify the model and to check that over fitting has not occurred.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)

Model_DT &amp;lt;- rpart(Survived~.,data=train_val,method=&amp;quot;class&amp;quot;)

rpart.plot(Model_DT,extra =  3,fallen.leaves = T)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-17-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;PRE_TDT=predict(Model_DT,data=train_val,type=&amp;quot;class&amp;quot;)

confusionMatrix(PRE_TDT,train_val$Survived)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1
##          0 418  93
##          1  22 181
##                                           
##                Accuracy : 0.8389          
##                  95% CI : (0.8099, 0.8652)
##     No Information Rate : 0.6162          
##     P-Value [Acc &amp;gt; NIR] : &amp;lt; 2.2e-16       
##                                           
##                   Kappa : 0.642           
##                                           
##  Mcnemar&amp;#39;s Test P-Value : 6.686e-11       
##                                           
##             Sensitivity : 0.9500          
##             Specificity : 0.6606          
##          Pos Pred Value : 0.8180          
##          Neg Pred Value : 0.8916          
##              Prevalence : 0.6162          
##          Detection Rate : 0.5854          
##    Detection Prevalence : 0.7157          
##       Balanced Accuracy : 0.8053          
##                                           
##        &amp;#39;Positive&amp;#39; Class : 0               
## &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;cross-validation&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.4) Cross Validation&lt;/h3&gt;
&lt;p&gt;Cross validation is used ten times to ensure that there is sufficient data being used to create the model and that it represents the full range of the complete data. With this method the train_val group is divided into ten parts. Each part is used as the test group once with the other nine parts being used as the training data. In this way it is less probable that over fitting occurs.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)

cv.10 &amp;lt;- createMultiFolds(train_val$Survived, k = 10, times = 10)

# Control

ctrl &amp;lt;- trainControl(method = &amp;quot;repeatedcv&amp;quot;, number = 10, repeats = 10,

                       index = cv.10)

                     
train_val &amp;lt;- as.data.frame(train_val)

##Train the data

Model_CDT &amp;lt;- train(x = train_val[,-7], y = train_val[,7], method = &amp;quot;rpart&amp;quot;, tuneLength = 30,

                   trControl = ctrl)



rpart.plot(Model_CDT$finalModel, type=4, clip.right.labs=FALSE, branch=.7)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;/en/post/Titanc-part2/Titanic-Part2_files/figure-html/unnamed-chunk-19-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;div id=&#34;cross-validation-predictions&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;6.4.1) Cross Validation Predictions&lt;/h4&gt;
&lt;p&gt;The below confusion matrix shows how the cross validation model has a precision of 0.8079. This is less that the accuracy of the first model created which did not use cross validation (accuracy of 0.8389). This suggests that over fitting did occur in the first model.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
PRE_VDTS=predict(Model_CDT$finalModel,newdata=train_test_val,type=&amp;quot;class&amp;quot;)

confusionMatrix(PRE_VDTS,train_test_val$Survived)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 94 19
##          1 15 49
##                                           
##                Accuracy : 0.8079          
##                  95% CI : (0.7421, 0.8632)
##     No Information Rate : 0.6158          
##     P-Value [Acc &amp;gt; NIR] : 2.854e-08       
##                                           
##                   Kappa : 0.5895          
##                                           
##  Mcnemar&amp;#39;s Test P-Value : 0.6069          
##                                           
##             Sensitivity : 0.8624          
##             Specificity : 0.7206          
##          Pos Pred Value : 0.8319          
##          Neg Pred Value : 0.7656          
##              Prevalence : 0.6158          
##          Detection Rate : 0.5311          
##    Detection Prevalence : 0.6384          
##       Balanced Accuracy : 0.7915          
##                                           
##        &amp;#39;Positive&amp;#39; Class : 0               
## &lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rpart.rules(Model_CDT$finalModel)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  .outcome                                                                                                                                          
##      0.08 when Title is Master or Miss or Mrs &amp;amp; Pclass &amp;gt;= 3 &amp;amp; Family_size &amp;gt;= 5                                                                     
##      0.10 when Title is                    Mr &amp;amp; Pclass &amp;lt;  2                    &amp;amp; Age Group is                         Age.60Ov                     
##      0.11 when Title is      Mr or Rare Title &amp;amp; Pclass &amp;gt;= 2                                                                                        
##      0.29 when Title is                    Mr &amp;amp; Pclass &amp;lt;  2 &amp;amp; Family_size &amp;gt;= 2 &amp;amp; Age Group is Age.1317 or Age.1839 or Age.4059 &amp;amp; Embarked is      S
##      0.32 when Title is                    Mr &amp;amp; Pclass &amp;lt;  2 &amp;amp; Family_size &amp;lt;  2 &amp;amp; Age Group is Age.1317 or Age.1839 or Age.4059                     
##      0.33 when Title is                  Miss &amp;amp; Pclass &amp;gt;= 3 &amp;amp; Family_size &amp;lt;  5 &amp;amp; Age Group is Age.1317 or Age.1839 or Age.4059 &amp;amp; Embarked is      S
##      0.53 when Title is                   Mrs &amp;amp; Pclass &amp;gt;= 3 &amp;amp; Family_size &amp;lt;  5 &amp;amp; Age Group is Age.1317 or Age.1839 or Age.4059 &amp;amp; Embarked is      S
##      0.58 when Title is                    Mr &amp;amp; Pclass &amp;lt;  2 &amp;amp; Family_size &amp;gt;= 2 &amp;amp; Age Group is Age.1317 or Age.1839 or Age.4059 &amp;amp; Embarked is      C
##      0.67 when Title is            Rare Title &amp;amp; Pclass &amp;lt;  2                                                                                        
##      0.77 when Title is Master or Miss or Mrs &amp;amp; Pclass &amp;gt;= 3 &amp;amp; Family_size &amp;lt;  5                                                 &amp;amp; Embarked is C or Q
##      0.78 when Title is Master or Miss or Mrs &amp;amp; Pclass &amp;gt;= 3 &amp;amp; Family_size &amp;lt;  5 &amp;amp; Age Group is             Age.0012 or Age.60Ov &amp;amp; Embarked is      S
##      0.94 when Title is Master or Miss or Mrs &amp;amp; Pclass &amp;lt;  3&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;important-variables&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.5) Important Variables&lt;/h3&gt;
&lt;p&gt;The importance of the variables in both models is shown below. In both models, title and gender are the most important variables in determining whether someone survived or not.&lt;/p&gt;
&lt;p&gt;This trend is reflected in the analysis carried out in Section 5 of this publication with males and passengers with the title of ‘Mr’ having a very low rate of survival.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Get importance
Model_DT$variable.importance&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       Title         Sex Family_size      Pclass   Age Group    Embarked 
##   111.41503    96.41472    54.63255    31.71858    28.20113    11.29332&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;Model_CDT$finalModel$variable.importance&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##       Title         Sex Family_size      Pclass   Age Group    Embarked 
##   114.23647    97.02466    55.44293    40.43166    29.94150    12.49217&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;final-testing&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;6.6) Final Testing&lt;/h3&gt;
&lt;p&gt;In this section the model is tested using the original testing data with its hidden results for the dependent variable. The model with cross validation is used.&lt;/p&gt;
&lt;p&gt;Running this model against the test data it is predicted that out of 418 passengers, 258 died, and 160 survived giving a survival rate of 38.28 percent, which is very close to the survival rate of 38.38% for the training data.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(1234)
PRE_TEST=predict(Model_CDT$finalModel,newdata=total[892:1309,],type=&amp;quot;class&amp;quot;)

PRE_TEST&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
##   0   1   0   0   1   0   1   0   1   0   0   0   1   0   1   1   0   0   0   1 
##  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40 
##   1   1   1   1   1   0   1   0   0   0   0   0   1   1   1   0   0   0   0   0 
##  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60 
##   0   0   0   1   1   0   0   0   1   1   0   0   1   1   0   0   0   0   0   1 
##  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80 
##   0   0   0   1   1   1   1   0   0   1   1   0   0   0   1   0   0   1   0   1 
##  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 
##   1   0   0   0   0   0   1   0   1   1   1   0   1   0   0   0   1   0   0   0 
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 
##   1   0   0   0   1   0   0   0   0   0   0   1   1   1   1   0   0   1   0   1 
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 
##   1   0   1   0   0   0   0   1   0   0   0   1   0   0   0   0   0   0   0   0 
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 
##   0   1   0   0   0   0   0   0   0   0   1   0   0   1   0   0   1   0   0   1 
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   1   1   0   0   1   0   0   1   0   0   0   0   0   0   1   1   1   1   1 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 
##   0   1   1   0   1   0   1   0   0   0   0   0   1   0   1   0   1   0   0   1 
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 
##   1   1   1   1   0   0   1   0   1   0   0   0   0   1   0   0   1   0   1   0 
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 
##   1   0   1   0   1   1   0   1   0   0   0   1   0   0   1   0   0   0   1   1 
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 
##   1   1   1   0   1   0   1   0   1   1   1   0   1   0   0   0   0   0   1   0 
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 
##   0   0   1   1   0   0   0   0   0   0   0   0   1   1   0   1   0   0   0   0 
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 
##   0   1   1   1   1   0   0   0   0   0   0   1   0   1   0   0   1   0   0   0 
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 
##   0   0   0   0   1   1   0   1   0   1   0   0   0   1   1   1   1   0   0   0 
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 
##   0   0   0   0   1   0   1   0   0   0   1   0   0   1   0   0   0   0   0   1 
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   0   0   0   1   1   0   0   1   0   1   1   0   0   0   1   0   1   0   0   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 
##   0   1   1   0   1   0   0   0   1   0   0   1   0   0   1   1   0   0   0   0 
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 
##   0   0   1   1   0   1   0   0   0   0   0   1   1   0   0   1   0   1   0   0 
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 
##   1   0   1   0   1   0   0   1   1   1   1   1   0   0   1   0   0   1 
## Levels: 0 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;TEST_Results &amp;lt;- cbind(test, PRE_TEST)

summary(PRE_TEST)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##   0   1 
## 258 160&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;7) Conclusion&lt;/h2&gt;
&lt;p&gt;In conclusion in this publication a decision tree model has been created to classify if passengers survived or died on the Titanic. The final model used cross validation in order to avoid over fitting.&lt;/p&gt;
&lt;p&gt;When the model was tested against the train_test_val an accuracy of 80.79% was achieved.&lt;/p&gt;
&lt;p&gt;Finally, when the model was tested using the test data it was predicted that out of the 418 test group passengers 258 died and 160 survived with a survival rate of 38.28%.&lt;/p&gt;
&lt;p&gt;It would be interesting to extend this analysis in the future using a random forest model to see if the model accuracy could be improved.&lt;/p&gt;
&lt;p&gt;Thanks you for reading this two part publication. Hopefully it has been informative.&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Titanic - Who Survived? - Part 1</title>
      <link>/en/post/titanic/titanic-en/</link>
      <pubDate>Wed, 20 May 2020 00:00:00 +0000</pubDate>
      <guid>/en/post/titanic/titanic-en/</guid>
      <description>


&lt;p&gt;The Titanic sank on the 15th of April 1912 after hitting an iceberg during its first voyage. Unfortunately there were not sufficient lifeboats on board resulting in the death of 1502 of the 2224 passengers and crew. When the Titanic started its journey it was considered the best boat in the World and unsinkable.&lt;/p&gt;
&lt;p&gt;As time has passed and analysis has been carried out of the passengers who died and survived it has been discovered that people with certain characteristics had a higher chance of survival. This publication responds to these findings with the intention of creating a decision tree classification model to predict if someone onboard survived or died. Therefore survival is the dependent variable. Independent variables including title, age, sex, social class, and port of embarkation are used. The publication is split into two parts. Part one focuses on the data preparation, with part two focusing on data analysis and model creation.&lt;/p&gt;
&lt;div id=&#34;packages&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;2) Packages&lt;/h2&gt;
&lt;p&gt;The following packages are used in this publication.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(dplyr)
library(tidyr)
library(ggplot2)
library(knitr)
library(DT)
library(purrr)
library(corrplot)
library(randomForest)
library(caret)
library(rpart)
library(rpart.plot)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;loading-the-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;3) Loading the Data&lt;/h2&gt;
&lt;p&gt;Two data bases are used - the first to train the model, and the second to test the model.&lt;/p&gt;
&lt;p&gt;The general idea of machine learning classification is to use the training data to look for relationships between the independent variables and the dependent variable, with a model being created.&lt;/p&gt;
&lt;p&gt;The model is then tested against the second data set which contains unseen data. This is to say that it contains all of the independent variables but with the dependent variable hidden. The model looks for similar patterns between the independent variables that existed in the training data and uses them to predict the dependent variable.&lt;/p&gt;
&lt;p&gt;Both data bases can be downloaded from &lt;a href=&#34;https://www.kaggle.com/c/titanic/data&#34;&gt;the following link.&lt;/a&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;setwd(&amp;quot;~/Documents/Machine Learning/15. Hugo/academic-kickstart-master/content/en/post/Titanic&amp;quot;)

test &amp;lt;- read.csv(&amp;quot;test.csv&amp;quot;)

train &amp;lt;- read.csv(&amp;quot;train.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;combining-test-and-train&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;3.1) Combining Test and Train&lt;/h2&gt;
&lt;p&gt;In order to conduct preliminary analysis of all of the passengers both the data sets are combined. In order for this to be possible firstly a survival variable is added to the test data set ensuring that both data sets have 12 variables and can be combined. In total with both data sets there are 1309 observations with 12 variables. The variables are:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr class=&#34;header&#34;&gt;
&lt;th&gt;Variable&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;PassengerId&lt;/td&gt;
&lt;td&gt;Id number&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Survived&lt;/td&gt;
&lt;td&gt;Survived (1) or died (0)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Pclass&lt;/td&gt;
&lt;td&gt;Social class of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Name&lt;/td&gt;
&lt;td&gt;Name of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Sex&lt;/td&gt;
&lt;td&gt;Sex of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Age&lt;/td&gt;
&lt;td&gt;Age of passenger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;SibSp&lt;/td&gt;
&lt;td&gt;Number of siblings or partners on the Titanic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Parch&lt;/td&gt;
&lt;td&gt;Number of parents or children on the Titanic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Ticket&lt;/td&gt;
&lt;td&gt;Ticket number&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Fare&lt;/td&gt;
&lt;td&gt;Cost of ticket&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;odd&#34;&gt;
&lt;td&gt;Cabin&lt;/td&gt;
&lt;td&gt;Cabin number&lt;/td&gt;
&lt;/tr&gt;
&lt;tr class=&#34;even&#34;&gt;
&lt;td&gt;Embarked&lt;/td&gt;
&lt;td&gt;Port of embarkation&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test$Survived &amp;lt;- NA

test &amp;lt;- test[,c(1,12,2,3,4,5,6,7,8,9,10,11)]

total &amp;lt;- rbind(train, test)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;str(total)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## &amp;#39;data.frame&amp;#39;:    1309 obs. of  12 variables:
##  $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
##  $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
##  $ Name       : Factor w/ 1307 levels &amp;quot;Abbing, Mr. Anthony&amp;quot;,..: 109 191 358 277 16 559 520 629 417 581 ...
##  $ Sex        : Factor w/ 2 levels &amp;quot;female&amp;quot;,&amp;quot;male&amp;quot;: 2 1 1 1 2 2 2 2 1 1 ...
##  $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
##  $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
##  $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
##  $ Ticket     : Factor w/ 929 levels &amp;quot;110152&amp;quot;,&amp;quot;110413&amp;quot;,..: 524 597 670 50 473 276 86 396 345 133 ...
##  $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...
##  $ Cabin      : Factor w/ 187 levels &amp;quot;&amp;quot;,&amp;quot;A10&amp;quot;,&amp;quot;A14&amp;quot;,..: 1 83 1 57 1 1 131 1 1 1 ...
##  $ Embarked   : Factor w/ 4 levels &amp;quot;&amp;quot;,&amp;quot;C&amp;quot;,&amp;quot;Q&amp;quot;,&amp;quot;S&amp;quot;: 4 2 4 4 4 3 4 4 4 2 ...&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;characteristics-engineering&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;4) Characteristics Engineering&lt;/h2&gt;
&lt;p&gt;In the following section the data is cleaned so that it can be analysed further on.&lt;/p&gt;
&lt;div id=&#34;missing-values&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.1) Missing Values&lt;/h3&gt;
&lt;p&gt;There are five variables with missing values: Cabin, Survived, Age, Embarked, Fare. It is necessary to treat these missing values as they can impact the effectiveness of a classification model. The only variable that is not treated for missing values is Survived as this is the dependent variable and the missing values correspond to the hidden test data.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;checkAllCols(total)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##            col   class  num numMissing numInfinite      avgVal minVal maxVal
## 1  PassengerId integer 1309          0           0 655.0000000      1   1309
## 2     Survived integer  891        418           0   0.3838384      0      1
## 3       Pclass integer 1309          0           0   2.2948816      1      3
## 4         Name  factor 1309          0          NA          NA     NA     NA
## 5          Sex  factor 1309          0          NA          NA     NA     NA
## 6          Age numeric 1046        263           0  29.8811377      0     80
## 7        SibSp integer 1309          0           0   0.4988541      0      8
## 8        Parch integer 1309          0           0   0.3850267      0      9
## 9       Ticket  factor 1309          0          NA          NA     NA     NA
## 10        Fare numeric 1308          1           0  33.2954793      0    512
## 11       Cabin  factor  295       1014          NA          NA     NA     NA
## 12    Embarked  factor 1307          2          NA          NA     NA     NA&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;age&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.2) Age&lt;/h3&gt;
&lt;p&gt;There are 263 missing values for the age variable. The average age of passengers is inserted for these missing values.&lt;/p&gt;
&lt;div id=&#34;avergae-age&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;4.2.1) Avergae Age&lt;/h4&gt;
&lt;p&gt;The below syntax is used to calculate the average age of passengers and with this value then added to the data. Additionally, a new variable is created, which groups the passengers by age into the following classes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Age &amp;lt; 13&lt;/li&gt;
&lt;li&gt;Age &amp;gt;= 13 &amp;amp; Age &amp;lt; 18&lt;/li&gt;
&lt;li&gt;Age &amp;gt;= 18 &amp;amp; Age &amp;lt; 40&lt;/li&gt;
&lt;li&gt;Age &amp;gt;= 40 &amp;amp; Age &amp;lt; 60&lt;/li&gt;
&lt;li&gt;Age &amp;gt;= 60&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;total &amp;lt;- total %&amp;gt;% mutate(Age = ifelse(is.na(Age), mean(total$Age, na.rm = T), Age), 
                          `Age Group` = case_when(Age &amp;lt; 13 ~ &amp;quot;Age.0012&amp;quot;, 

                                 Age &amp;gt;= 13 &amp;amp; Age &amp;lt; 18 ~ &amp;quot;Age.1317&amp;quot;,
                                 
                                 Age &amp;gt;= 18 &amp;amp; Age &amp;lt;40 ~ &amp;quot;Age.1839&amp;quot;,

                                 Age &amp;gt;= 40 &amp;amp; Age &amp;lt; 60 ~ &amp;quot;Age.4059&amp;quot;,

                                 Age &amp;gt;= 60 ~ &amp;quot;Age.60Ov&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;port&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.3) Port&lt;/h3&gt;
&lt;p&gt;As there are only two observations with missing values for Port, Southampton is inserted for both these observations as it is the most frequent port in the data.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;levels(total$Embarked)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;&amp;quot;  &amp;quot;C&amp;quot; &amp;quot;Q&amp;quot; &amp;quot;S&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;table(total$Embarked)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## 
##       C   Q   S 
##   2 270 123 914&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;levels(total$Embarked)[1] &amp;lt;- c(&amp;quot;S&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;fare&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.4) Fare&lt;/h3&gt;
&lt;p&gt;There is one missing value for this variable which is located in row 1044. It is likely that the variables of Class and Port impacted the cost of the Fare. Passenger 1044 ‘Mr Thomas Storey’ was a class 3 passenger and boarded the ship in Southampton. Therefore, to replace this missing value the average fare for third class passengers who boarded in Southampton is used. The result is a value of £14.44.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean_fare_calculation &amp;lt;- total %&amp;gt;% filter(Pclass == &amp;#39;3&amp;#39; &amp;amp; Embarked == &amp;#39;S&amp;#39;) %&amp;gt;% filter(!PassengerId == 1044)

mean(mean_fare_calculation$Fare)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 14.43542&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;total[1044, 10] &amp;lt;- 14.43542&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;name&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.5) Name&lt;/h3&gt;
&lt;p&gt;The title of each passenger is separated in a new variable for Title. The following table shows that the most common titles for passengers were Master, Miss, Mr, y Mrs with a representation of 97.40% of the passengers.&lt;/p&gt;
&lt;p&gt;Some of the less common titles are grouped together in a new class called rare_title. Additionally, the titles for Mlle and Ms are added to the class of Miss. The title of Mme is added to the class of Mrs.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;total$Title &amp;lt;- gsub(&amp;#39;(.*, )|(\\..*)&amp;#39;, &amp;#39;&amp;#39;, total$Name)

table_titles_total &amp;lt;- table(total$Sex, total$Title)

table_titles_total&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##         
##          Capt Col Don Dona  Dr Jonkheer Lady Major Master Miss Mlle Mme  Mr Mrs
##   female    0   0   0    1   1        0    1     0      0  260    2   1   0 197
##   male      1   4   1    0   7        1    0     2     61    0    0   0 757   0
##         
##           Ms Rev Sir the Countess
##   female   2   0   0            1
##   male     0   8   1            0&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rare_title &amp;lt;- c(&amp;#39;Dona&amp;#39;, &amp;#39;Lady&amp;#39;, &amp;#39;the Countess&amp;#39;,&amp;#39;Capt&amp;#39;, &amp;#39;Col&amp;#39;, &amp;#39;Don&amp;#39;, 
                &amp;#39;Dr&amp;#39;, &amp;#39;Major&amp;#39;, &amp;#39;Rev&amp;#39;, &amp;#39;Sir&amp;#39;, &amp;#39;Jonkheer&amp;#39;)

total$Title[total$Title %in% rare_title] &amp;lt;- &amp;#39;Rare Title&amp;#39;
total$Title[total$Title == &amp;#39;Mlle&amp;#39;] &amp;lt;- &amp;#39;Miss&amp;#39;
total$Title[total$Title == &amp;#39;Ms&amp;#39;] &amp;lt;- &amp;#39;Miss&amp;#39;
total$Title[total$Title == &amp;#39;Mme&amp;#39;] &amp;lt;- &amp;#39;Mrs&amp;#39;

table(total$Sex, total$Title)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##         
##          Master Miss  Mr Mrs Rare Title
##   female      0  264   0 198          4
##   male       61    0 757   0         25&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;family&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.6) Family&lt;/h3&gt;
&lt;p&gt;With the variables SibSp and Parch it is possible to know if a passenger had family on the Titanic. SibSp counts siblings and partners, with Parch counting parents and children. A new variable is created to count family sizes.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;total$Family_size &amp;lt;- total$SibSp + total$Parch + 1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;survival&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.7) Survival&lt;/h3&gt;
&lt;p&gt;As already explained the survived variable has missing values as it is the dependent variable, with the missing values the observations from the test data. It is therefore not necessary to treat these missing values, however, the survival rate for the available data is analysed.&lt;/p&gt;
&lt;p&gt;In the below table it can be seen that in the train data 61.62% of the passengers died and 38.38% survived.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;total$group &amp;lt;- ifelse(total$PassengerId &amp;lt;= 891, &amp;quot;train&amp;quot;, &amp;quot;test&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;total %&amp;gt;% filter(group == &amp;quot;entrenar&amp;quot;) %&amp;gt;% group_by(Survived) %&amp;gt;% count() %&amp;gt;% mutate(percentage_all = (n/1309) * 100) %&amp;gt;% mutate(percentage_entrenar = (n/891) * 100)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## # A tibble: 0 x 4
## # Groups:   Survived [0]
## # … with 4 variables: Survived &amp;lt;int&amp;gt;, n &amp;lt;int&amp;gt;, percentage_all &amp;lt;dbl&amp;gt;,
## #   percentage_entrenar &amp;lt;dbl&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;cabin&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;4.8) Cabin&lt;/h3&gt;
&lt;p&gt;Cabin is the variable with the most missing values with 1014 missing in total. Therefore, this variable is not included in the model.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion&#34; class=&#34;section level1&#34;&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;This publication has introduced this data analysis project which aims to create a decision tree classification model to predict if someone onboard the Titanic survived or died. Part one has focused on the data preparation, with the data being prepared for subsequent analysis and model creation. The data set is saved for use in further publications.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;write.csv(total, file = &amp;quot;total2.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
</description>
    </item>
    
  </channel>
</rss>
