This notebook is a variation of Pradeep Tripathi's Titanic Kaggle solution in R. Instead of writing it in R as the original, we write it in Clojure, and call R from Clojure.
The goal is to study the Clojure-R interop, and expecially experiment with various ways to define Clojure functions corresponding to R functions.
In this first, naive version, the corresponding Clojure functions are rather simple. They expect a varying number of arguments, and pass those arguments to R function calls by a rather generic way (as defined by Clojuresss)
We do not try to replace the rather imperative style of the original tutorial. Rather, we try to write something that is as close as possible to the original.
We have leanred a lot from this use case. It did expose lots of issues and open questions about the Clojuress API and implementation. Note, however, that the piece of R code that we are mimicing here is not so typical to the current tidyverse trends – there is no heavy use of dplyr, tidy evaluation, etc. It may be a good idea to study other examples that have more of those.
This notebook has been written in notespace – an experimental Clojure library that allows one to use regular Clojure namespaces as notebooks, thus enabling interactive literate programming from ones' favourite Clojure editor and REPL.
daslu, Jan. 2020
Here are most of the functions that we need, brought by the standard require-r mechanism, inspired by libpython-clj's require-python (though not as sophisticated at the moment). In function names, dots are changed to hyphens.
(require '[clojuress.v1.r :as r :refer [r r->clj na empty-symbol r== r!= r< r> r<= r>= r& r&& r| r|| str-md r+ bra bra<- brabra brabra<- colon]] '[clojuress.v1.applications.plotting :refer [plotting-function->svg ggplot->svg]] '[clojuress.v1.require :refer [require-r]] '[clojure.java.shell :refer [sh]] '[clojure.string :as string])(r/discard-all-sessions)(require-r '[base :refer [round names ! set.seed sum which rnorm lapply sapply %in% table list.files c paste colnames row.names cbind gsub <- $ $<- as.data.frame data.frame nlevels factor expression is.na strsplit as.character summary table]] '[stats :refer [median predict]] '[ggplot2 :refer [ggsave qplot ggplot aes facet_grid geom_density geom_text geom_histogram geom_bar scale_x_continuous scale_y_continuous labs coord_flip geom_vline geom_hline geom_boxplot]] '[ggthemes :refer [theme_few]] '[scales :refer [dollar_format]] '[graphics :refer [par plot hist dev.off legend]] '[dplyr :refer [mutate bind_rows summarise group_by]] '[utils :refer [read.csv write.csv head]] '[mice :refer [mice complete]] '[randomForest :refer [randomForest importance]])Pradeep Tripathi's solution will use randomForest to create a model predicting survival on the Titanic.
This step assumes that the Titanic data lies under the resources/data/ path under your Clojure project.
(def data-path (-> "pwd" sh :out string/trim (str "/resources/data/titanic/")))# Original code:
list.files('../input')
(list-files data-path)[1] "test.csv.gz" "train.csv.gz"# Original code:
train <-read.csv('../input/train.csv', stringsAsFactors = F)
test <-read.csv('../input/test.csv', stringsAsFactors = F)
(def train (read-csv (str data-path "train.csv.gz") :stringsAsFactors false))(def test (read-csv (str data-path "test.csv.gz") :stringsAsFactors false))As explained by Thripathi, the Random Forest algorithm will use the Bagging method to create multiple random samples with replacement from the dataset, that will be treated as training data, while the out of bag samples will be treated as test data.
# Original code:
titanic<-bind_rows(train,test)
(def titanic (bind_rows train test))# Original code:
str(titanic)
summary(titanic)
head(titanic)
(str-md titanic)'data.frame': 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 : chr "Braund, Mr. Owen Harris" "Cumings, Mrs. John Bradley (Florence Briggs Thayer)" "Heikkinen, Miss. Laina" "Futrelle, Mrs. Jacques Heath (Lily May Peel)" ...
$ Sex : chr "male" "female" "female" "female" ...
$ 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 : chr "A/5 21171" "PC 17599" "STON/O2. 3101282" "113803" ...
$ Fare : num 7.25 71.28 7.92 53.1 8.05 ...
$ Cabin : chr "" "C85" "" "C123" ...
$ Embarked : chr "S" "C" "S" "S" ...
(summary titanic) PassengerId Survived Pclass Name Min. : 1 Min. :0.0000 Min. :1.000 Length:1309 1st Qu.: 328 1st Qu.:0.0000 1st Qu.:2.000 Class :character Median : 655 Median :0.0000 Median :3.000 Mode :character Mean : 655 Mean :0.3838 Mean :2.295 3rd Qu.: 982 3rd Qu.:1.0000 3rd Qu.:3.000 Max. :1309 Max. :1.0000 Max. :3.000 NA's :418 Sex Age SibSp Parch Length:1309 Min. : 0.17 Min. :0.0000 Min. :0.000 Class :character 1st Qu.:21.00 1st Qu.:0.0000 1st Qu.:0.000 Mode :character Median :28.00 Median :0.0000 Median :0.000 Mean :29.88 Mean :0.4989 Mean :0.385 3rd Qu.:39.00 3rd Qu.:1.0000 3rd Qu.:0.000 Max. :80.00 Max. :8.0000 Max. :9.000 NA's :263 Ticket Fare Cabin Embarked Length:1309 Min. : 0.000 Length:1309 Length:1309 Class :character 1st Qu.: 7.896 Class :character Class :character Mode :character Median : 14.454 Mode :character Mode :character Mean : 33.295 3rd Qu.: 31.275 Max. :512.329 NA's :1 (head titanic) PassengerId Survived Pclass1 1 0 32 2 1 13 3 1 34 4 1 15 5 0 36 6 0 3 Name Sex Age SibSp Parch1 Braund, Mr. Owen Harris male 22 1 02 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38 1 03 Heikkinen, Miss. Laina female 26 0 04 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 05 Allen, Mr. William Henry male 35 0 06 Moran, Mr. James male NA 0 0 Ticket Fare Cabin Embarked1 A/5 21171 7.2500 S2 PC 17599 71.2833 C85 C3 STON/O2. 3101282 7.9250 S4 113803 53.1000 C123 S5 373450 8.0500 S6 330877 8.4583 QTripathi: We've got a sense of our variables, their class type, 3 and the first few observations of each. We know we're working with 1309 observations of 12 variables.
Thripathi's explanation: We can break down Passenger name into additional meaningful variables which can feed predictions or be used in the creation of additional new variables. For instance, passenger title is contained within the passenger name variable and we can use surname to represent families.
# Original code:
colnames(titanic)
(colnames titanic) [1] "PassengerId" "Survived" "Pclass" "Name" "Sex" [6] "Age" "SibSp" "Parch" "Ticket" "Fare" [11] "Cabin" "Embarked" Retrieve title from passenger names
# Original code:
titanic$title<-gsub('(.*, )|(\..*)', '', titanic$Name)
(def titanic ($<- titanic 'title (gsub "(.*, )|(\\..*)" "" ($ titanic 'Name))))Show title counts by sex
# Original code:
table(titanic$Sex, titanic$title)
Clojuress can covert an R frequency table to a Clojure data structure:
(-> (table ($ titanic 'Sex) ($ titanic 'title)) r->clj){["Capt" "female"] 0, ["Capt" "male"] 1, ["Col" "female"] 0, ["Col" "male"] 4, ["Don" "female"] 0, ["Don" "male"] 1, ["Dona" "female"] 1, ["Dona" "male"] 0, ["Dr" "female"] 1, ["Dr" "male"] 7, ["Jonkheer" "female"] 0, ["Jonkheer" "male"] 1, ["Lady" "female"] 1, ["Lady" "male"] 0, ["Major" "female"] 0, ["Major" "male"] 2, ["Master" "female"] 0, ["Master" "male"] 61, ["Miss" "female"] 260, ["Miss" "male"] 0, ["Mlle" "female"] 2, ["Mlle" "male"] 0, ["Mme" "female"] 1, ["Mme" "male"] 0, ["Mr" "female"] 0, ["Mr" "male"] 757, ["Mrs" "female"] 197, ["Mrs" "male"] 0, ["Ms" "female"] 2, ["Ms" "male"] 0, ["Rev" "female"] 0, ["Rev" "male"] 8, ["Sir" "female"] 0, ["Sir" "male"] 1, ["the Countess" "female"] 1, ["the Countess" "male"] 0}Sometimes, it is convenient to first convert it to an R data frame:
(as-data-frame (table ($ titanic 'Sex) ($ titanic 'title))) Var1 Var2 Freq1 female Capt 02 male Capt 13 female Col 04 male Col 45 female Don 06 male Don 17 female Dona 18 male Dona 09 female Dr 110 male Dr 711 female Jonkheer 012 male Jonkheer 113 female Lady 114 male Lady 015 female Major 016 male Major 217 female Master 018 male Master 6119 female Miss 26020 male Miss 021 female Mlle 222 male Mlle 023 female Mme 124 male Mme 025 female Mr 026 male Mr 75727 female Mrs 19728 male Mrs 029 female Ms 230 male Ms 031 female Rev 032 male Rev 833 female Sir 034 male Sir 135 female the Countess 136 male the Countess 0Sometimes, it is convenient to use the way R prints a frequency table.
(table ($ titanic 'Sex) ($ titanic 'title)) 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 0Convert titles with low count into a new title, and rename/reassign Mlle, Ms and Mme.
# Original code:
unusual_title<-c('Dona', 'Lady', 'the Countess','Capt', 'Col', 'Don',
'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer')
(def unusual-title ["Dona" "Lady" "the Countess" "Capt" "Col" "Don" "Dr" "Major" "Rev" "Sir" "Jonkheer"])# Original code:
titanic$title[titanic$title=='Mlle']<-'Miss'
titanic$title[titanic$title=='Ms']<-'Miss'
titanic$title[titanic$title=='Mme']<-'Mrs'
titanic$title[titanic$title %in% unusual_title]<-'Unusual Title'
(def titanic (-> titanic (bra<- (r== ($ titanic 'title) "Mlle") "title" "Miss") (bra<- (r== ($ titanic 'title) "Ms") "title" "Miss") (bra<- (r== ($ titanic 'title) "Mme") "title" "Mrs") (bra<- (%in% ($ titanic 'title) unusual-title) "title" "Mrs")))Check the title count again:
# Original code:
table(titanic$Sex, titanic$title)
"trying again:"(table ($ titanic 'Sex) ($ titanic 'title)) Master Miss Mr Mrs female 0 264 0 202 male 61 0 757 25Create a variable which contain the surnames of passengers.
# Original code:
titanic$surname<-sapply(titanic$Name, function(x) strsplit(x,split='[,.]')[[1]][1])
nlevels(factor(titanic$surname)) ## 875 unique surnames
(def titanic ($<- titanic 'surname (sapply ($ titanic 'Name) (r "function(x) strsplit(x,split='[,.]')[[1]][1]"))))(-> titanic ($ 'surname) factor nlevels)[1] 875Tripathi: Family size variable: We are going to create a variable "famsize" to know the number of family members. It includes number of sibling/number of parents and children+ passenger themselves
# Original code:
titanic$famsize <- titanic$SibSp + titanic$Parch + 1
(def titanic ($<- titanic 'famsize (r+ ($ titanic 'SibSp) ($ titanic 'Parch) 1)))Create a family variable:
# Original code:
titanic$family <- paste(titanic$surname, titanic$famsize, sep='_')
(def titanic ($<- titanic 'family (paste ($ titanic 'surname) ($ titanic 'famsize) :sep "_")))Visualize the relationship between family size & survival:
ggplot(titanic[1:891,], aes(x = famsize, fill = factor(Survived))) +
geom_bar(stat='count', position='dodge') +
scale_x_continuous(breaks=c(1:11)) +
labs(x = 'Family Size') +
theme_few()
(-> titanic (bra (colon 1 891) (empty-symbol)) (ggplot (aes :x 'famsize :fill '(factor Survived))) (r+ (geom_bar :stat "count" :position "dodge") (scale_x_continuous :breaks (colon 1 11)) (labs :x "Family Size") (theme_few)) ggplot->svg)Tripathi: Explanation: We can see that there's a survival penalty to single/alone, and those with family sizes above 4. We can collapse this variable into three levels which will be helpful since there are comparatively fewer large families.
Discretize family size:
# Original code:
titanic$fsizeD[titanic$famsize == 1] <- 'single'
titanic$fsizeD[titanic$famsize < 5 & titanic$famsize> 1] <- 'small'
titanic$fsizeD[titanic$famsize> 4] <- 'large'
(def titanic (-> titanic (bra<- (r== ($ titanic 'famsize) 1) "fsizeD" "single") (bra<- (r& (r< ($ titanic 'famsize) 5) (r> ($ titanic 'famsize) 1)) "fsizeD" "small") (bra<- (r> ($ titanic 'famsize) 4) "fsizeD" "large")))Let us check if it makes sense:
(-> titanic ($ 'fsizeD) table) large single small 82 790 437 And let us make sure there are no missing values:
(-> titanic ($ 'fsizeD) is-na table)FALSE 1309 Tripathi: There's could be some useful information in the passenger cabin variable including about their deck, so Retrieve deck from Cabin variable.
# Original code:
titanic$Cabin[1:28]
(-> titanic (bra (colon 1 28) "Cabin")) [1] "" "C85" "" "C123" "" [6] "" "E46" "" "" "" [11] "G6" "C103" "" "" "" [16] "" "" "" "" "" [21] "" "D56" "" "A6" "" [26] "" "" "C23 C25 C27"The first character is the deck:
# Original code:
strsplit(titanic$Cabin[2], NULL) [[1]]
(-> titanic ($ 'Cabin) (bra 2) (strsplit nil) (brabra 1))[1] "C" "8" "5"Deck variable:
# Original R code:
titanic$deck<-factor(sapply(titanic$Cabin, function(x) strsplit(x, NULL)[[1]][1]))
(def titanic ($<- titanic 'deck (factor (sapply ($ titanic 'Cabin) (r "function(x) strsplit(x, NULL)[[1]][1]")))))Let us check:
(-> titanic ($ 'deck) table) A B C D E F G T 22 65 94 46 41 21 5 1 "updated summary"(summary titanic) PassengerId Survived Pclass Name Min. : 1 Min. :0.0000 Min. :1.000 Length:1309 1st Qu.: 328 1st Qu.:0.0000 1st Qu.:2.000 Class :character Median : 655 Median :0.0000 Median :3.000 Mode :character Mean : 655 Mean :0.3838 Mean :2.295 3rd Qu.: 982 3rd Qu.:1.0000 3rd Qu.:3.000 Max. :1309 Max. :1.0000 Max. :3.000 NA's :418 Sex Age SibSp Parch Length:1309 Min. : 0.17 Min. :0.0000 Min. :0.000 Class :character 1st Qu.:21.00 1st Qu.:0.0000 1st Qu.:0.000 Mode :character Median :28.00 Median :0.0000 Median :0.000 Mean :29.88 Mean :0.4989 Mean :0.385 3rd Qu.:39.00 3rd Qu.:1.0000 3rd Qu.:0.000 Max. :80.00 Max. :8.0000 Max. :9.000 NA's :263 Ticket Fare Cabin Embarked Length:1309 Min. : 0.000 Length:1309 Length:1309 Class :character 1st Qu.: 7.896 Class :character Class :character Mode :character Median : 14.454 Mode :character Mode :character Mean : 33.295 3rd Qu.: 31.275 Max. :512.329 NA's :1 title surname famsize family Length:1309 Length:1309 Min. : 1.000 Length:1309 Class :character Class :character 1st Qu.: 1.000 Class :character Mode :character Mode :character Median : 1.000 Mode :character Mean : 1.884 3rd Qu.: 2.000 Max. :11.000 fsizeD deck Length:1309 C : 94 Class :character B : 65 Mode :character D : 46 E : 41 A : 22 (Other): 27 NA's :1014 Thripathi's explanation, following the summary:
Missing value in Embarkment – Tripathi: Now we will explore missing values and rectify it through imputation. There are a number of different ways we could go about doing this. Given the small size of the dataset, we probably should not opt for deleting either entire observations (rows) or variables (columns) containing missing values. We're left with the option of replacing missing values with sensible values given the distribution of the data, e.g., the mean, median or mode.
To know which passengers have no listed embarkment port:
# Original code:
titanic$Embarked[titanic$Embarked == ""] <- NA
titanic[(which(is.na(titanic$Embarked))), 1]
Marking as missing:
(def titanic (bra<- titanic (r== ($ titanic 'Embarked) "") "Embarked" (r/na)))Checking which has missing port:
(-> titanic (bra (-> titanic ($ 'Embarked) is-na which) 1))[1] 62 830Tripathi: Passengers 62 and 830 are missing Embarkment.
# Original code:
titanic[c(62, 830), 'Embarked']
(-> titanic (bra [62 830] "Embarked"))[1] NA NATripathi: So Passenger numbers 62 and 830 are each missing their embarkment ports. Let's look at their class of ticket and their fare.
# Original code:
titanic[c(62, 830), c(1,3,10)]
(-> titanic (bra [62 830] [1 3 10])) PassengerId Pclass Fare62 62 1 80830 830 1 80Alternatively:
(-> titanic (bra [62 830] ["PassengerId" "Pclass" "Fare"])) PassengerId Pclass Fare62 62 1 80830 830 1 80Thripathi's explanation: Both passengers had first class tickets that they spent 80 (pounds?) on. Let's see the embarkment ports of others who bought similar kinds of tickets.
First way of handling missing value in Embarked:
# Original code:
titanic%>%
group_by(Embarked, Pclass) %>%
filter(Pclass == "1") %>%
filter(Pclass == "1") %>%
filter(Pclass == "1") %>%
summarise(mfare = median(Fare),n = n())
(-> titanic (group_by 'Embarked 'Pclass) (r.dplyr/filter '(== Pclass "1")) (summarise :mfare '(median Fare) :n '(n)))# A tibble: 4 x 4# Groups: Embarked [4] Embarked Pclass mfare n 1 C 1 76.7 1412 Q 1 90 33 S 1 52 1774 1 80 2 Tripathi: Looks like the median price for a first class ticket departing from 'C' (Charbourg) was 77 (in comparison to our 80). While first class tickets departing from 'Q' were only slightly more expensiive (median price 90), only 3 first class passengers departed from that port. It seems far more likely that passengers 62 and 830 departed with the other 141 first-class passengers from Charbourg.
Second Way of handling missing value in Embarked:
# Original code:
embark_fare <- titanic %>%
filter(PassengerId != 62 & PassengerId != 830)
embark_fare
(def embark_fare (-> titanic (r.dplyr/filter '(& (!= PassengerId 62) (!= PassengerId 830))) r->clj))_unnamed [1307 18]:| :PassengerId | :Survived | :Pclass | :Name | :Sex | :Age | :SibSp | :Parch | :Ticket | :Fare | :Cabin | :Embarked | :title | :surname | :famsize | :family | :fsizeD | :deck ||--------------+-----------+---------+---------------------------------------------------------+--------+--------+--------+--------+------------------+--------+--------+-----------+--------+---------------+----------+-----------------+---------+-------|| 1.000 | 0.000 | 3.000 | Braund, Mr. Owen Harris | male | 22.000 | 1.000 | 0.000 | A/5 21171 | 7.250 | | S | Mr | Braund | 2.000 | Braund_2 | small | || 2.000 | 1.000 | 1.000 | Cumings, Mrs. John Bradley (Florence Briggs Thayer) | female | 38.000 | 1.000 | 0.000 | PC 17599 | 71.283 | C85 | C | Mrs | Cumings | 2.000 | Cumings_2 | small | C || 3.000 | 1.000 | 3.000 | Heikkinen, Miss. Laina | female | 26.000 | 0.000 | 0.000 | STON/O2. 3101282 | 7.925 | | S | Miss | Heikkinen | 1.000 | Heikkinen_1 | single | || 4.000 | 1.000 | 1.000 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.000 | 1.000 | 0.000 | 113803 | 53.100 | C123 | S | Mrs | Futrelle | 2.000 | Futrelle_2 | small | C || 5.000 | 0.000 | 3.000 | Allen, Mr. William Henry | male | 35.000 | 0.000 | 0.000 | 373450 | 8.050 | | S | Mr | Allen | 1.000 | Allen_1 | single | || 6.000 | 0.000 | 3.000 | Moran, Mr. James | male | NaN | 0.000 | 0.000 | 330877 | 8.458 | | Q | Mr | Moran | 1.000 | Moran_1 | single | || 7.000 | 0.000 | 1.000 | McCarthy, Mr. Timothy J | male | 54.000 | 0.000 | 0.000 | 17463 | 51.863 | E46 | S | Mr | McCarthy | 1.000 | McCarthy_1 | single | E || 8.000 | 0.000 | 3.000 | Palsson, Master. Gosta Leonard | male | 2.000 | 3.000 | 1.000 | 349909 | 21.075 | | S | Master | Palsson | 5.000 | Palsson_5 | large | || 9.000 | 1.000 | 3.000 | Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) | female | 27.000 | 0.000 | 2.000 | 347742 | 11.133 | | S | Mrs | Johnson | 3.000 | Johnson_3 | small | || 10.000 | 1.000 | 2.000 | Nasser, Mrs. Nicholas (Adele Achem) | female | 14.000 | 1.000 | 0.000 | 237736 | 30.071 | | C | Mrs | Nasser | 2.000 | Nasser_2 | small | || 11.000 | 1.000 | 3.000 | Sandstrom, Miss. Marguerite Rut | female | 4.000 | 1.000 | 1.000 | PP 9549 | 16.700 | G6 | S | Miss | Sandstrom | 3.000 | Sandstrom_3 | small | G || 12.000 | 1.000 | 1.000 | Bonnell, Miss. Elizabeth | female | 58.000 | 0.000 | 0.000 | 113783 | 26.550 | C103 | S | Miss | Bonnell | 1.000 | Bonnell_1 | single | C || 13.000 | 0.000 | 3.000 | Saundercock, Mr. William Henry | male | 20.000 | 0.000 | 0.000 | A/5. 2151 | 8.050 | | S | Mr | Saundercock | 1.000 | Saundercock_1 | single | || 14.000 | 0.000 | 3.000 | Andersson, Mr. Anders Johan | male | 39.000 | 1.000 | 5.000 | 347082 | 31.275 | | S | Mr | Andersson | 7.000 | Andersson_7 | large | || 15.000 | 0.000 | 3.000 | Vestrom, Miss. Hulda Amanda Adolfina | female | 14.000 | 0.000 | 0.000 | 350406 | 7.854 | | S | Miss | Vestrom | 1.000 | Vestrom_1 | single | || 16.000 | 1.000 | 2.000 | Hewlett, Mrs. (Mary D Kingcome) | female | 55.000 | 0.000 | 0.000 | 248706 | 16.000 | | S | Mrs | Hewlett | 1.000 | Hewlett_1 | single | || 17.000 | 0.000 | 3.000 | Rice, Master. Eugene | male | 2.000 | 4.000 | 1.000 | 382652 | 29.125 | | Q | Master | Rice | 6.000 | Rice_6 | large | || 18.000 | 1.000 | 2.000 | Williams, Mr. Charles Eugene | male | NaN | 0.000 | 0.000 | 244373 | 13.000 | | S | Mr | Williams | 1.000 | Williams_1 | single | || 19.000 | 0.000 | 3.000 | Vander Planke, Mrs. Julius (Emelia Maria Vandemoortele) | female | 31.000 | 1.000 | 0.000 | 345763 | 18.000 | | S | Mrs | Vander Planke | 2.000 | Vander Planke_2 | small | || 20.000 | 1.000 | 3.000 | Masselmani, Mrs. Fatima | female | NaN | 0.000 | 0.000 | 2649 | 7.225 | | C | Mrs | Masselmani | 1.000 | Masselmani_1 | single | || 21.000 | 0.000 | 2.000 | Fynney, Mr. Joseph J | male | 35.000 | 0.000 | 0.000 | 239865 | 26.000 | | S | Mr | Fynney | 1.000 | Fynney_1 | single | || 22.000 | 1.000 | 2.000 | Beesley, Mr. Lawrence | male | 34.000 | 0.000 | 0.000 | 248698 | 13.000 | D56 | S | Mr | Beesley | 1.000 | Beesley_1 | single | D || 23.000 | 1.000 | 3.000 | McGowan, Miss. Anna "Annie" | female | 15.000 | 0.000 | 0.000 | 330923 | 8.029 | | Q | Miss | McGowan | 1.000 | McGowan_1 | single | || 24.000 | 1.000 | 1.000 | Sloper, Mr. William Thompson | male | 28.000 | 0.000 | 0.000 | 113788 | 35.500 | A6 | S | Mr | Sloper | 1.000 | Sloper_1 | single | A || 25.000 | 0.000 | 3.000 | Palsson, Miss. Torborg Danira | female | 8.000 | 3.000 | 1.000 | 349909 | 21.075 | | S | Miss | Palsson | 5.000 | Palsson_5 | large | |Use ggplot2 to visualize embarkment, passenger class, & median fare:
# Original code:
ggplot(embark_fare, aes(x = Embarked, y = Fare, fill = factor(Pclass))) +
geom_boxplot() +
geom_hline(aes(yintercept=80),
colour='red', linetype='dashed', lwd=2) +
scale_y_continuous(labels=dollar_format()) +
theme_few()
(-> embark_fare (ggplot (aes :x 'Embarked :y 'Fare :fill '(factor Pclass))) (r+ (geom_boxplot) (geom_hline (aes :yintercept 80) :colour "red" :linetype "dashed" :lwd 2) (scale_y_continuous :labels (dollar_format))) ggplot->svg)Tripathi: From plot we can see that The median fare for a first class passenger departing from Charbourg ('C') coincides nicely with the $80 paid by our embarkment-deficient passengers. I think we can safely replace the NA values with 'C'. Since their fare was $80 for 1st class, they most likely embarked from 'C'.
# Original code:
titanic$Embarked[c(62, 830)] <- 'C'
(def titanic (bra<- titanic [62 830] "Embarked" "C"))A missing value in fare. Thripathi's explanation: To know Which passenger has no fare information:
# Original code:
titanic[(which(is.na(titanic$Fare))) , 1]
(-> titanic (bra (-> titanic ($ 'Fare) is-na which) 1))[1] 1044Tripathi: Looks like Passenger number 1044 has no listed Fare
Where did this passenger leave from? What was their class?
# Original code:
titanic[1044, c(3, 12)]
(-> titanic (bra 1044 [3 12])) Pclass Embarked1044 3 STripathi: Another way to know about passenger id 1044 :Show row 1044
# Original code:
titanic[1044, ]
(-> titanic (bra 1044 (empty-symbol))) PassengerId Survived Pclass Name Sex Age SibSp Parch1044 1044 NA 3 Storey, Mr. Thomas male 60.5 0 0 Ticket Fare Cabin Embarked title surname famsize family fsizeD deck1044 3701 NA S Mr Storey 1 Storey_1 single Thripathi's explanation: Looks like he left from 'S' (Southampton) as a 3rd class passenger. Let's see what other people of the same class and embarkment port paid for their tickets.
titanic%>% filter(Pclass == '3' & Embarked == 'S') %>% summarise(missing_fare = median(Fare, na.rm = TRUE))
(-> titanic (r.dplyr/filter '(& (== Pclass "3") (== Embarked "S"))) (summarise :missing_fare '(median Fare :na.rm true))) missing_fare1 8.05Tripathi: Looks like the median cost for a 3rd class passenger leaving out of Southampton was 8.05. That seems like a logical value for this passenger to have paid.
Second way:
# Original code:
ggplot(titanic[titanic$Pclass == '3' & titanic$Embarked == 'S', ],
aes(x = Fare)) +
geom_density(fill = '#99d6ff', alpha=0.4) +
geom_vline(aes(xintercept=median(Fare, na.rm=T)),
colour='red', linetype='dashed', lwd=1) +
scale_x_continuous(labels=dollar_format()) +
theme_few()
(-> titanic (bra (r& (r== ($ titanic 'Pclass) 3) (r== ($ titanic 'Embarked) "S")) (empty-symbol)) (ggplot (aes :x 'Fare)) (r+ (geom_density :fill "#99d6ff" :alpha 0.4) (geom_vline (aes :xintercept '(median Fare :na.rm true)) :colour "red" :linetype "dashed" :lwd 1) (scale_x_continuous :labels (dollar_format))) ggplot->svg)Tripathi: From this visualization, it seems quite reasonable to replace the NA Fare value with median for their class and embarkment which is $8.05.
Replace that NA with 8.05
# Original code:
titanic$Fare[1044] <- 8.05
summary(titanic$Fare)
(def titanic (bra<- titanic 1044 "Fare" 8.05))(-> titanic ($ 'Fare) summary) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.000 7.896 14.454 33.276 31.275 512.329 Tripathi: Another way of Replace missing fare value with median fare for class/embarkment:
# Original code:
titanic$Fare[1044] <- median(titanic[titanic$Pclass == '3' & titanic$Embarked == 'S', ]$Fare, na.rm = TRUE)
(def titanic (bra<- titanic 1044 "Fare" (-> titanic (bra (r& (r== ($ titanic 'Pclass) 3) (r== ($ titanic 'Embarked) "S")) "Fare") (median :na.rm true))))Missing Value in Age.
Tripathi: Show number of missing Age values.
# Original code:
sum(is.na(titanic$Age)) "before"(-> titanic ($ 'Age) is-na sum)[1] 263Tripathi: 263 passengers have no age listed. Taking a median age of all passengers doesn't seem like the best way to solve this problem, so it may be easiest to try to predict the passengers' age based on other known information.
To predict missing ages, I'm going to use the mice package. To start with I will factorize the factor variables and then perform mice(multiple imputation using chained equations).
Set a random seed:
# Original code:
set.seed(129)
(set-seed 129)Tripathi: Perform mice imputation, excluding certain less-than-useful variables:
# Original code:
mice_mod <- mice(titanic[, !names(titanic) %in% c('PassengerId','Name','Ticket','Cabin','Family','Surname','Survived')], method='rf')
(def mice-mod (-> titanic (bra (empty-symbol) (-> titanic names (%in% ["PassengerId" "Name" "Ticket" "Cabin" "Family" "Surname" "Survived"]) !)) (mice :method "rf")))Save the complete output.
# Original code:
mice_output <- complete(mice_mod)
(def mice-output (complete mice-mod))Tripathi: Let's compare the results we get with the original distribution of passenger ages to ensure that nothing has gone completely awry.
Plot age distributions:
# Original code:
par(mfrow=c(1,2))
hist(titanic$Age, freq=F, main='Age: Original Data',
col='darkred', ylim=c(0,0.04))
hist(mice_output$Age, freq=F, main='Age: MICE Output',
col='lightgreen', ylim=c(0,0.04))
(plotting-function->svg (fn [] (par :mfrow [1 2]) (-> titanic ($ 'Age) (hist :freq 'F :main "Age: Original Data" :col "darkred" :lim [0 0.04] :xlab "Age")) (-> mice-output ($ 'Age) (hist :freq 'F :main "Age: MICE Output" :col "lightgreen" :lim [0 0.04] :xlab "Age"))))Tripathi: Things look good, so let's replace our age vector in the original data with the output from the mice model.
Replace Age variable from the mice model:
# Original code:
titanic$Age <- mice_output$Age
(def titanic ($<- titanic 'Age ($ mice-output 'Age)))Show new number of missing Age values
# Original code:
sum(is.na(titanic$Age))
"after"(-> titanic ($ 'Age) is-na sum)[1] 0Tripathi: I will create a couple of new age-dependent variables: Child and Mother. A child will simply be someone under 18 years of age and a mother is a passenger who is 1) female, 2) is over 18, 3) has more than 0 children and 4) does not have the title 'Miss'.
Relationship between age & survival: I include Sex since we know it's a significant predictor.
# Original code:
ggplot(titanic[1:891,], aes(Age, fill = factor(Survived))) +
geom_histogram() + facet_grid(.~Sex) + theme_few()
(-> titanic (bra (colon 1 891) (empty-symbol)) (ggplot (aes 'Age :fill '(factor Survived))) (r+ (geom_histogram) (facet_grid '(tilde . Sex)) (theme_few)) ggplot->svg)Tripathi: Create the column Child, and indicate whether child or adult:
# Original code:
titanic$Child[titanic$Age < 18] <- 'Child'
titanic$Child[titanic$Age >= 18] <- 'Adult'
(def titanic (-> titanic (bra<- (r< ($ titanic 'Age) 18) "Child" "Child") (bra<- (r>= ($ titanic 'Age) 18) "Child" "Adult")))Show counts:
# Original code:
table(titanic$Child, titanic$Survived)
(table ($ titanic 'Child) ($ titanic 'Survived)) 0 1 Adult 483 273 Child 66 69Adding Mother variable:
# Original code:
titanic$Mother <- 'Not Mother'
titanic$Mother[titanic$Sex == 'female' & titanic$Parch >0 & titanic$Age > 18 & titanic$title != 'Miss'] <- 'Mother'
(def titanic (-> titanic ($<- 'Mother "Not Mother") (bra<- (reduce r& [(r== ($ titanic 'Sex) "female") (r> ($ titanic 'Parch) 0) (r> ($ titanic 'Age) 18) (r!= ($ titanic 'title) "Miss")]) "Mother" "Mother")))Show counts:
# Original code:
table(titanic$Mother, titanic$Survived)
(table ($ titanic 'Mother) ($ titanic 'Survived)) 0 1 Mother 16 39 Not Mother 533 303Factorizing variables:
# Original code:
titanic$Child <- factor(titanic$Child)
titanic$Mother <- factor(titanic$Mother)
titanic$Pclass <- factor(titanic$Pclass)
titanic$Sex <- factor(titanic$Sex)
titanic$Embarked <- factor(titanic$Embarked)
titanic$Survived <- factor(titanic$Survived)
titanic$title <- factor(titanic$title)
titanic$fsizeD <- factor(titanic$fsizeD)
(def titanic (reduce (fn [data symbol] ($<- data symbol (factor ($ data symbol)))) titanic ['Child 'Mother 'Pclass 'Sex 'Embarked 'Survived 'title 'fsizeD]))Check classes of all columns:
(lapply titanic (r "class"))$PassengerId[1] "integer"$Survived[1] "factor"$Pclass[1] "factor"$Name[1] "character"$Sex[1] "factor"$Age[1] "numeric"$SibSp[1] "integer"$Parch[1] "integer"$Ticket[1] "character"$Fare[1] "numeric"$Cabin[1] "character"$Embarked[1] "factor"$title[1] "factor"$surname[1] "character"$famsize[1] "integer"$family[1] "character"$fsizeD[1] "factor"$deck[1] "factor"$Child[1] "factor"$Mother[1] "factor"Split into training & test sets:
# Original code:
train <- titanic[1:891,]
test <- titanic[892:1309,]
(def train (bra titanic (colon 1 891) (empty-symbol)))(def test (bra titanic (colon 892 1309) (empty-symbol)))Building the model:
Tripathi: We then build our model using randomForest on the training set.
Set a random seed:
# Original code:
set.seed(754)
(set-seed 754)Tripathi: Build the model (note: not all possible variables are used):
# Original code:
titanic_model <- randomForest(Survived ~ Pclass + Sex + Age + SibSp + Parch +
Fare + Embarked + title +
fsizeD + Child + Mother,
data = train)
(def titanic-model (randomForest '(tilde Survived (+ Pclass Sex Age SibSp Parch Fare Embarked title fsizeD Child Mother)) :data train))Show model error:
# Original code:
plot(titanic_model, ylim=c(0,0.36))
legend('topright', colnames(titanic_model$err.rate), col=1:3, fill=1:3)
(plotting-function->svg (fn [] (plot titanic-model :ylim [0 0.36] :main "Model Error") (legend "topright" (colnames ($ titanic-model 'err.rate)) :col (colon 1 3) :fill (colon 1 3))))Tripathi: The black line shows the overall error rate which falls below 20%. The red and green lines show the error rate for 'died' and 'survived', respectively. We can see that right now we're much more successful predicting death than we are survival.
Get importance:
# Original code:
importance <- importance(titanic_model)
varImportance <- data.frame(Variables = row.names(importance),
Importance = round(importance[ ,'MeanDecreaseGini'],2))
(importance titanic-model) MeanDecreaseGiniPclass 28.342693Sex 57.953089Age 45.949147SibSp 11.725061Parch 8.485071Fare 58.456066Embarked 10.073493title 68.299646fsizeD 18.323786Child 4.299471Mother 2.442574(def importance-info (importance titanic-model))(def var-importance (data-frame :Variables (row-names importance-info) :Importance (-> importance-info (bra (empty-symbol) "MeanDecreaseGini") round)))importance-info MeanDecreaseGiniPclass 28.342693Sex 57.953089Age 45.949147SibSp 11.725061Parch 8.485071Fare 58.456066Embarked 10.073493title 68.299646fsizeD 18.323786Child 4.299471Mother 2.442574var-importance Variables ImportancePclass Pclass 28Sex Sex 58Age Age 46SibSp SibSp 12Parch Parch 8Fare Fare 58Embarked Embarked 10title title 68fsizeD fsizeD 18Child Child 4Mother Mother 2Create a rank variable based on importance:
# Original code:
rankImportance <- varImportance %>%
mutate(Rank = paste0('#',dense_rank(desc(Importance))))
(def rank-importance (-> var-importance (mutate :Rank '(paste0 "#" (dense_rank (desc Importance))))))rank-importance Variables Importance Rank1 Pclass 28 #42 Sex 58 #23 Age 46 #34 SibSp 12 #65 Parch 8 #86 Fare 58 #27 Embarked 10 #78 title 68 #19 fsizeD 18 #510 Child 4 #911 Mother 2 #10Tripathi: Use ggplot2 to visualize the relative importance of variables
# Original code:
ggplot(rankImportance, aes(x = reorder(Variables, Importance),
y = Importance, fill = Importance)) +
geom_bar(stat='identity') +
geom_text(aes(x = Variables, y = 0.5, label = Rank),
hjust=0, vjust=0.55, size = 4, colour = 'red') +
labs(x = 'Variables') +
coord_flip() +
theme_few()
(-> rank-importance (ggplot (aes :x '(reorder Variables Importance) :y 'Importance :fill 'Importance)) (r+ (geom_bar :stat "Identity") (geom_text (aes :x 'Variables :y 0.5 :label 'Rank) :hjust 0 :vjust 0.55 :size 4 :colour "red") (labs :x "Variables") (coord_flip) (theme_few)) ggplot->svg)Tripathi: From the plot we can see that the 'title' variable has the highest relative importance out of all of our predictor variables.
Predict using the test set:
# Original code:
prediction <- predict(titanic_model, test)
prediction
(def prediction (predict titanic-model test)) 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 0 0 0 0 1 0 1 0 1 0 0 0 1 0 1 1 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 0 0 0 1 0 1 1 0 1 0 1 0 0 0 0 0 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 1 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 1 1 0 0 1 1 0 0 0 0 0 1 0 0 0 1 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 1 1 1 0 0 1 1 0 0 0 1 0 0 1 0 1 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 1 0 0 0 0 0 1 0 1 1 0 0 1 0 0 0 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1 0 0 0 1 0 1 0 0 1 0 0 1 1 1 1 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1 1 1 0 0 1 0 0 1 0 0 0 0 0 0 1 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1 0 1 1 0 0 1 0 1 0 1 0 0 0 0 0 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1 0 1 0 1 1 0 1 1 1 1 1 0 0 1 0 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1 0 0 0 0 1 0 0 1 0 1 0 1 0 1 0 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1 1 0 1 0 0 0 1 0 0 1 0 0 0 1 1 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1 1 0 0 0 0 1 0 1 0 1 0 0 0 0 0 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 0 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1 1 0 1 0 0 0 0 0 1 1 1 0 0 0 0 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 0 0 0 1 1 0 1 0 0 0 1 0 0 1 0 0 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 0 0 0 1 0 0 0 1 1 1 0 1 0 1 1 0 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 0 0 1 0 1 0 0 1 0 1 1 0 1 0 0 0 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1 0 0 1 0 0 1 1 0 0 0 0 0 0 1 1 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1 0 1 0 0 0 0 0 1 1 1 1 0 0 1 0 1308 1309 0 1 Levels: 0 1Tripathi: Save the solution to a dataframe with two columns: PassengerId and Survived (prediction).
# Original code:
Output<- data.frame(PassengerID = test$PassengerId, Survived = prediction)
Output
(def output (data-frame :PassengerId ($ test 'PassengerId) :Survived prediction))(r->clj output)_unnamed [418 2]:| :PassengerId | :Survived ||--------------+-----------|| 892.000 | 0 || 893.000 | 0 || 894.000 | 0 || 895.000 | 0 || 896.000 | 1 || 897.000 | 0 || 898.000 | 1 || 899.000 | 0 || 900.000 | 1 || 901.000 | 0 || 902.000 | 0 || 903.000 | 0 || 904.000 | 1 || 905.000 | 0 || 906.000 | 1 || 907.000 | 1 || 908.000 | 0 || 909.000 | 0 || 910.000 | 0 || 911.000 | 1 || 912.000 | 0 || 913.000 | 1 || 914.000 | 1 || 915.000 | 0 || 916.000 | 1 |Write the Output to file:
# Original code:
write.csv(Output, file = 'pradeep_titanic_output.csv', row.names = F)
(write-csv output :file "/tmp/pradeep_titanic_output.csv" :row.names 'F)Tripathi: Thank you for taking the time to read through my first exploration of a Titanic Kaggle dataset. Again, this newbie welcomes comments and suggestions!