First Kaggle tutorial I followed

I was studying quantitative finance at the university of Kiel in Germany, and for my master thesis, I needed to write a small program that can predict the volatility of returns on investments in crypto currencies using GARCH and GAS models. Back then I was writing simple code using Scilab to solve some statistical questions for home works in mathematical/ computational finance and risk management.

For my master thesis problem, I needed a more complex program, so I chose the statistical software R. When I began learning how to code in R, I was trying out different simple things, like creating a variable, a vector etc. then started developing the statistical concept I need for my thesis. Step by step I managed to write something fairly good for a beginner :D.

After my thesis I thought it would be a good idea to start working on my data science skills using R. So, I took part in a workshop in data science by Opencampus in Kiel and managed to do some tasks using newly learned packages like ggplot2 and dplyr among others.

To accelerate my learning speed, I got on Kaggle and looked for a small project where different techniques are used so I could mimic the code and learn by doing. It was very difficult to understand everything, specially when it came to feature engineering. The tutorial I followed used the famous Titanic survival data set. The code for it is available on Github and it is originally written by Megan L. Risdal.

Keep on coding!

The code:

# load packages
library(ggplot2) # visualization
library(ggthemes)# visualization
library(scales) # visualization
library(dplyr) # data manipulation
library(mice) # imputation
library(randomForest) # classification algorithm

# first, set the working directory, either by browsing to it or by using the function setwd()

#load raw data
train <- read.csv("train.csv", header = TRUE, stringsAsFactors = F)
test <- read.csv("test.csv", header = TRUE, stringsAsFactors = F)

#add a "survived variable to the test set to allow for combining data sets
test.survived <- data.frame(Survived = rep("None", nrow(test)), test[,])

# combine data sets (including survived)
data.combined <- rbind(train, test.survived)

# combine data sets
full <- bind_rows(train, test)

# check data
str(full)

# feature engineering
# grap title from passanger names

# show title counts by sex
table(full$Sex, full$title)
full$title <- gsub('(.*, )|(\\..*)', "", full$Name)

# titles with very low counts to be combined to "rare" level
rare_title <- c('Dona', 'Lady', 'the Countess','Capt', 'Col', 'Don', 
                'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer')

# also reassign mlle, ms, and mme accordingly
full$title[full$title == 'Mlle'] <- 'Miss'
full$title[full$title == 'Ms'] <- 'Miss'
full$title[full$title == 'Mme'] <- 'Miss'
full$title[full$title %in% rare_title] <- 'Rare Title'

# show title counts by sex again
table(full$Sex, full$title)

# finally, grab surname from passenger name
full$Surname <- sapply(full$Name, 
                       function(x) strsplit(x, split = '[,.]')[[1]][1])

cat(paste('We have <b>', nlevels(factor(full$Surname)), 
          '</b> unique surname. I wuld be interested to infer ethnicity based on surname --- another time.'))

# Do families sink or swim together?
# create a family zise variable including the passanger themselves
full$Fsize <- full$SibSp + full$Parch + 1

# create a familt variable
full$Family <- paste(full$Surname, full$Fsize, sep = '_')

# to help understand how the family size variable relate to survival, we need to plot it among the training data
# use ggplot2 to visualize the relationship between family size & survival
ggplot(full[1:891,], aes(x = Fsize, fill = factor(Survived))) +
  geom_bar(stat = 'count', position = 'dodge') +
  scale_x_continuous(breaks = c(1:11)) +
  labs(x = 'Family Size') +
  theme_few()

# according to the graph, there are not so many large families. so we can divide family size into three levels 
# descretize family size

full$FsizeD[full$Fsize == 1] <- 'singleton'
full$FsizeD[full$Fsize < 5 & full$Fsize > 1] <- 'small'
full$FsizeD[full$Fsize > 4] <- 'large'

# show family size by survival using a mosaic plot
mosaicplot(table(full$FsizeD, full$Survived), main = 'Family size by survival', shade=TRUE)

# the cabins variable might be of interest but looking at it, it has a lot of missing values
full$Cabin

# the first character is the deck. for example:
strsplit(full$Cabin[2], NULL)[[1]]

# create a deck variable. get passenger deck A - F
full$Deck <- factor(sapply(full$Cabin, function(x) strsplit(x, NULL)[[1]][1]))

# Missingness
# sensible value imputation
# passengers 62 and 830 are missing Embarkment
full$Embarked[c(62,830)]
#or
full[c(62, 830), 'Embarked']

cat(paste('We will infer their values for **embarkment** based on present data that we can imagine 
          may be relevant: **passenger class** and **fare**. We see that they paid<b> $',
          full[c(62, 830), 'Fare'][1], '</b>and<b> $', full[c(62, 830), 'Fare'][2],
          '</b>respectively and their classes are<b>', full[c(62, 830), 'Pclass'][[1]][1], '</b>and<b>',
          full[c(62, 830), 'Pclass'][[1]][2], '</b>. So from where did they embark?'))

# get rid of our missing passenger IDs
embark_fare <- full %>%
  filter(PassengerId != 62 & PassengerId != 830)

# use ggplot2 to visualize embarkment, passenger class, & median fare
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()

# since their fare was $80 for 1st class, they most likely embarked from 'C'
full$Embarked[c(62, 830)] <- 'C'

# passenger on row 1044 has an NA Fare value
full$Fare[1044]

# This is a third class passenger who departed from Southampton ('S'). 
#Let's visualize Fares among all others sharing their class and embarkment (n = 494).
ggplot(full[full$Pclass == '3' & full$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()

# it seems reasonable to replace the NA fare value with median for their class and embarkment which is $8.05.
full$Fare[1044] <- median(full[full$Pclass == 3 & full$Embarked == 'S', ]$Fare, na.rm = TRUE)

# predictive imputation
# there are some missing age values in our data. for this we can create a model predicting ages based on other variables
# lets see the number of missing age values
sum(is.na(full$Age))

# we are going to use the "mice" package for that purpose
# firstly, we need to make variables into factors
factor_vars <- c('PassengerId','Pclass','Sex','Embarked',
                 'title','Surname','Family','FsizeD')

full[factor_vars] <- lapply(full[factor_vars], function(x) as.factor(x))

# set a random seed
set.seed(129)

#perform mice imputation, excluding certain less-than-useful variables
mice_mod <- mice(full[, !names(full) %in% c('PassengerId','Name','Ticket','Cabin','Family','Surname','Survived')], method='rf') 

# save the complete output
mice_output <- complete(mice_mod)

# let us compare the results with the original distribution passenger ages to ensure that nothing has gone an unexpected way
# to do that we will plot age distributions for both
par(mfrow=c(1,2))
hist(full$Age, freq = F, main = 'Age: Original Data',
     col = 'darkgreen', ylab = c(0, 0.04))
hist(mice_output$Age, freq = F, main = 'Age: MICE Output',
     col = 'lightgreen', ylab = c(0, 0.04))

# everything looks fine, so we can replace the age values in the original dataset with the ones generated by mice
full$Age <- mice_output$Age

# show new number of missing age values
sum(is.na(full$Age))

# Feature engineering: Round 2
# we can create a couple of new age-dependent variables: Child and Mother. 
# child would be somone under 18 and a mother is a passenger who is 1)female, 2)is over 18, 3)has more than 0 kids 🙂 and 4)does not have the title 'Miss'
# First we will look at the relationship between age & survival
ggplot(full[1:891,], aes(Age, fill = factor(Survived))) +
  geom_histogram() +
  # We can include Sex since we know (a priori) it's a significant predictor
  
facet_grid(.~Sex) +
  theme_few()

# create the column child, and indicate whether child or adult
full$Child[full$Age < 18] <- 'Child'
full$Child[full$Age >= 18] <- 'Adult'

# show counts
table(full$Child, full$Survived)

# being a child doesn't seem to make a difference whether a passenger would survive or not.
# adding a mother variable
full$Mother <- 'Not Mother'
full$Mother[full$Sex == 'female' & full$Parch > 0 & full$Age > 18 & full$title != 'Miss'] <- 'Mother'

# show counts
table(full$Mother, full$Survived)

# finish by factorizing our two new factor variables
full$Child <- factor(full$Child)
full$Mother <- factor(full$Mother)

# double checking if all variables we need are taken care of and that there are no missing data
md.pattern(full)
# looks like we have everything we need to start our prediction

# prediction
# for this, we will rely on the randomForest classification algorithm
# first, we need to split the data back into the original trainig and testing sets
train <- full[1:891, ]
test <- full[892:1309, ]

# building the model
# set a random seed
set.seed(754)

# build the model (note: not all possible variables are used)
rf_model <- randomForest(factor(Survived) ~ Pclass + Sex
                         + Age + SibSp + Parch + Fare + Embarked
                         + title + FsizeD + Child + Mother, data = train)

# show model error
plot(rf_model, ylim = c(min(rf_model[["err.rate"]]), max(rf_model[["err.rate"]])))
legend('topright', colnames(rf_model$err.rate), col = 1:3, fill = 1:3, 
       pt.cex = 1, cex = 0.75)

# seems like the model is much more successful predicting death than survival

# let us take a look at relative variable importance by plotting the mean decerease in Gini calculated across all trees
# Get importance
importance <- importance(rf_model)
varImportance <- data.frame(Variables = row.names(importance),
                            Importance = round(importance[ , 'MeanDecreaseGini'],2))

# create a rank variable based on importance
rankImportance <- varImportance %>%
  mutate(Rank = paste0('#', dense_rank(desc(Importance))))

# use ggplot2 to visualize the relative importance of variables
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()
  
# as we can see, the title variable has the highest relative importance for our prediction of survival

# Final step, prediction!
# predict using the test set
prediction <- predict(rf_model, test)

# save the solution to a dataframe with two column: PassengerId and Survived (prediction)
solution <- data.frame(PassengerID = test$PassengerId, Survived = prediction)

# write solution to file
write.csv(solution, file = 'rf_mod_Solution.csv', row.names = F)

Leave a Reply