Exercise 05

Logistic regression exercise with Titanic data

We'll be working with a dataset from Kaggle's Titanic competition: data, data dictionary

Goal: Predict survival based on passenger characteristics

The sinking of the RMS Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships.

One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.

In this challenge, we ask you to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the tragedy.

Read the data into Pandas


In [51]:
import pandas as pd
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/titanic.csv'
titanic = pd.read_csv(url, index_col='PassengerId')
titanic.head()


Out[51]:
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
PassengerId
1 0 3 Braund, Mr. Owen Harris male 22 1 0 A/5 21171 7.2500 NaN S
2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38 1 0 PC 17599 71.2833 C85 C
3 1 3 Heikkinen, Miss. Laina female 26 0 0 STON/O2. 3101282 7.9250 NaN S
4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 0 113803 53.1000 C123 S
5 0 3 Allen, Mr. William Henry male 35 0 0 373450 8.0500 NaN S

Create X and y

Define Pclass and Parch as the features, and Survived as the response.


In [41]:
feature_cols = ['Pclass', 'Parch']
X = titanic[feature_cols]
Y = titanic.Survived

Exercise 5.1

Split the data into training and testing sets


In [42]:
import numpy as np
# Insert code here
random_sample = np.random.rand(y.shape[0])
X_train, X_test = X[random_sample<0.7], X[random_sample>=0.7]
Y_train, Y_test = Y[random_sample<0.7], Y[random_sample>=0.7]

print(Y_train.shape, Y_test.shape)


(631,) (260,)

In [43]:
import numpy as np
from sklearn.cross_validation import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=42)
print(Y_train.shape, Y_test.shape)


(596,) (295,)

Exercise 5.2

Fit a logistic regression model and examine the coefficients

Confirm that the coefficients make intuitive sense.


In [44]:
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression(C=1e9)
mod1=logreg.fit(X_train, Y_train)

In [45]:
mod1.coef_


Out[45]:
array([[-0.80366466,  0.22085358]])

Exercise 5.3

Make predictions on the testing set and calculate the accuracy


In [47]:
titanic['survive_pred'] = logreg.predict(X)
titanic.head()


Out[47]:
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked survive_pred
PassengerId
1 0 3 Braund, Mr. Owen Harris male 22 1 0 A/5 21171 7.2500 NaN S 0
2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38 1 0 PC 17599 71.2833 C85 C 1
3 1 3 Heikkinen, Miss. Laina female 26 0 0 STON/O2. 3101282 7.9250 NaN S 0
4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 0 113803 53.1000 C123 S 1
5 0 3 Allen, Mr. William Henry male 35 0 0 373450 8.0500 NaN S 0

In [52]:
survive_pred = logreg.predict(X_test)

In [53]:
(Y_test == survive_pred).mean()


Out[53]:
0.70508474576271185

Exercise 5.4

Confusion matrix of Titanic predictions


In [54]:
from sklearn.metrics import confusion_matrix
confusion_matrix(Y_test, survive_pred)


Out[54]:
array([[148,  27],
       [ 60,  60]])

Exercise 5.5

Increase sensitivity by lowering the threshold for predicting survival

Create a new classifier by changing the probability threshold to 0.3

What is the new confusion matrix?


In [63]:
survive_pred_prob=logreg.predict_proba(X_test)[:,1]
predict2=np.where(survive_pred_prob >= 0.7, 1, 0)
confusion_matrix(Y_test, predict2)


Out[63]:
array([[173,   2],
       [111,   9]])

In [64]:
(Y_test == predict2).mean()


Out[64]:
0.61694915254237293

In [65]:
survive_pred_prob=logreg.predict_proba(X_test)[:,1]
predict2=np.where(survive_pred_prob >= 0.3, 1, 0)
confusion_matrix(Y_test, predict2)


Out[65]:
array([[105,  70],
       [ 34,  86]])

In [66]:
(Y_test == predict2).mean()


Out[66]:
0.64745762711864407