Module 11 · Logistic regression · Lesson 47 of 66
Who survived the Titanic?
Clean real data, turn text into numbers, and train a classifier that predicts survival.
In this lesson · about 30 minutes
- Find and fill missing data
- Turn category columns into numbers with get_dummies
- Train a LogisticRegression model and read its classification report and confusion matrix
Logistic regression is a classification method: it predicts which of two groups something belongs to, such as spam or not spam, survived or not. Despite its name, it doesn't predict a number. It squeezes a weighted sum of the features through the sigmoid function, an S-shaped curve that turns any number into a probability between 0 and 1. Above 0.5 we predict class 1, otherwise class 0.
The sigmoid curve
The data
We'll predict whether a Titanic passenger survived, using the famous training file from the Kaggle competition. Columns include Pclass (ticket class), Sex, Age, SibSp (siblings or spouses aboard), Parch (parents or children aboard), Fare and Embarked (port).
Where is data missing?
Who survived?
Filling in missing ages
We could drop every passenger without an age, but we'd lose a fifth of the data. Instead, we impute: fill each gap with a sensible guess. First-class passengers tend to be older, so the average age per class is a better guess than one average for everyone.
Exercise
Impute the ages
The function impute_age below is ready. It takes a row of two values, age and class, and returns 37, 29 or 24 for a missing age in class 1, 2 or 3. Apply it to the ['Age', 'Pclass'] columns row by row (axis=1) and store the result in train['Age']. End with the number of missing ages left.
def impute_age(cols):
age, pclass = cols.iloc[0], cols.iloc[1]
if pd.isnull(age):
if pclass == 1:
return 37
elif pclass == 2:
return 29
else:
return 24
return ageCode that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
train = pd.read_csv('titanic_train.csv')
def impute_age(cols):
age, pclass = cols.iloc[0], cols.iloc[1]
if pd.isnull(age):
if pclass == 1:
return 37
elif pclass == 2:
return 29
else:
return 24
return ageCabin is too empty to fix, so we drop that column, then drop the two rows still missing Embarked.
Text to numbers
Models need numbers. pd.get_dummies turns a category column into one 0/1 column per category. With drop_first=True it drops one of them, because it's implied by the others: if male is 0, the passenger is female. Keeping both would give the model two columns that always say the same thing.
Exercise
Make the data numeric
Create sex and embark with pd.get_dummies(..., drop_first=True, dtype=int) for the Sex and Embarked columns. Drop Sex, Embarked, Name and Ticket from train, then join the new columns on with pd.concat(..., axis=1). End with train.head().
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
train = pd.read_csv('titanic_train.csv')
def impute_age(cols):
age, pclass = cols.iloc[0], cols.iloc[1]
if pd.isnull(age):
if pclass == 1:
return 37
elif pclass == 2:
return 29
else:
return 24
return age
train['Age'] = train[['Age', 'Pclass']].apply(impute_age, axis=1)
train.drop('Cabin', axis=1, inplace=True)
train.dropna(inplace=True)Exercise
Train the model
The data is split for you (test_size=0.30, random_state=101). Create a LogisticRegression(max_iter=1000) called logmodel, fit it, and save its predictions for X_test as predictions.
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
train = pd.read_csv('titanic_train.csv')
def impute_age(cols):
age, pclass = cols.iloc[0], cols.iloc[1]
if pd.isnull(age):
if pclass == 1:
return 37
elif pclass == 2:
return 29
else:
return 24
return age
train['Age'] = train[['Age', 'Pclass']].apply(impute_age, axis=1)
train.drop('Cabin', axis=1, inplace=True)
train.dropna(inplace=True)
sex = pd.get_dummies(train['Sex'], drop_first=True, dtype=int)
embark = pd.get_dummies(train['Embarked'], drop_first=True, dtype=int)
train.drop(['Sex', 'Embarked', 'Name', 'Ticket'], axis=1, inplace=True)
train = pd.concat([train, sex, embark], axis=1)
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
X_train, X_test, y_train, y_test = train_test_split(train.drop('Survived', axis=1), train['Survived'],
test_size=0.30, random_state=101)Judging a classifier
Accuracy, the share of right answers, can mislead when one class is rare. A confusion matrix shows the four kinds of result: true negatives and false positives in the top row, false negatives and true positives in the bottom row.
- Precision: of the passengers we said survived, how many did?
- Recall: of those who survived, how many did we find?
- F1-score: one number that balances the two.
Exercises solved: 0 of 3
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.