Skip to content
Portfolio Project 6 - Titanic Machine Learning from Disaster
The Challenge
The sinking of the Titanic is one of the most infamous shipwrecks in history.
On April 15, 1912, during her maiden voyage, the widely considered “unsinkable” RMS Titanic sank after colliding with an iceberg. Unfortunately, there weren’t enough lifeboats for everyone onboard, resulting in the death of 1502 out of 2224 passengers and crew.
While there was some element of luck involved in surviving, it seems some groups of people were more likely to survive than others.
In this challenge, we ask you to build a predictive model that answers the question: “what sorts of people were more likely to survive?” using passenger data (ie name, age, gender, socio-economic class, etc).
import pandas as pd
import numpy as np
# Load the data of actual data (train)
train_data = pd.read_csv("train.csv")
train_data.head()# Load the data of the test data (test)
test_data = pd.read_csv("test.csv")
test_data.head()# Check survival rate of women
women = train_data.loc[train_data.Sex == 'female']["Survived"]
rate_women = sum(women)/len(women)
print("Percentage of Women Survivors:", rate_women)
# Check survival rate of men
men = train_data.loc[train_data.Sex == 'male']["Survived"]
rate_men = sum(men)/len(men)
print("Percentage of Men Survivors:", rate_men)# Build a random forest model
from sklearn.ensemble import RandomForestClassifier
y = train_data["Survived"]
features = ["Pclass", "Sex", "SibSp", "Parch"]
X = pd.get_dummies(train_data[features])
X_test = pd.get_dummies(test_data[features])
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)
model.fit(X, y)
predictions = model.predict(X_test)
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions})
output.to_csv('submission.csv', index=False)
print("Your submission was successfully saved!")
# Predictive results are loaded into 'submission.csv'# Display the predictive results of 'test.csv' in 'submission.csv'
submission = pd.read_csv('submission.csv')
submission.head()