Python ML Capstone B: Survive the Titanic
This capstone predicts who survived the Titanic. It runs the full loop: fill the gaps, encode the text, train three models, and compare.
Fill the gaps first
Age is missing for 177 passengers. Filling with the median leaves zero gaps.
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset("titanic")
print("Missing age before:", int(titanic["age"].isna().sum()))
df = titanic[["pclass", "sex", "age", "sibsp", "parch", "fare", "embarked", "survived"]].copy()
df["age"] = df["age"].fillna(df["age"].median())
df["embarked"] = df["embarked"].fillna("S")
print("Missing age after:", int(df["age"].isna().sum()))Text becomes columns
get_dummies turns sex and embarked into zero-or-one columns. The table grows to 9 columns.
coded = pd.get_dummies(df, columns=["sex", "embarked"], drop_first=True)
print("Columns:", list(coded.columns))
print("Shape:", coded.shape)One model, two scores
Logistic Regression sorts 81 out of 100 test passengers right. Its F1 is 0.76.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X = coded.drop(columns=["survived"])
y = coded["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = Pipeline([("scale", StandardScaler()), ("model", LogisticRegression(max_iter=1000, random_state=42))])
model.fit(X_train, y_train)
pred = model.predict(X_test)
print("Accuracy:", round(accuracy_score(y_test, pred), 4))
print("F1:", round(f1_score(y_test, pred), 4))Example
import pandas as pd
import seaborn as sns
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
titanic = sns.load_dataset("titanic")
cols = ["pclass", "sex", "age", "sibsp", "parch", "fare", "embarked", "survived"]
df = titanic[cols].copy()
df["age"] = df["age"].fillna(df["age"].median())
df["embarked"] = df["embarked"].fillna("S")
df = pd.get_dummies(df, columns=["sex", "embarked"], drop_first=True)
X = df.drop(columns=["survived"])
y = df["survived"]
print("Rows:", len(df), "Features:", X.shape[1])
print("Survived share:", round(float(y.mean()), 4))
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
models = {
"Logistic Regression": Pipeline([
("scale", StandardScaler()),
("model", LogisticRegression(max_iter=1000, random_state=42)),
]),
"Random Forest": RandomForestClassifier(n_estimators=100, random_state=42),
"Gradient Boosting": GradientBoostingClassifier(random_state=42),
}
for name, model in models.items():
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(name, "accuracy:", round(accuracy_score(y_test, pred), 4),
"F1:", round(f1_score(y_test, pred), 4))Key points
- Use seaborn load_dataset to load the 891-row Titanic table
- Use fillna to fill the missing ages with the median age
- Use get_dummies to turn text columns into zero-or-one columns
- Accuracy: the share of passengers the model sorts right
- F1: a single number that blends precision with recall
- Use three models so the winner earns the title
In this example, the Titanic table is trimmed to seven features and the target. The 177 blank ages are filled with the median age, and the blank embarked values take S. get_dummies turns sex and embarked into zero-or-one columns, which leaves 8 features. A fifth of the passengers is kept back for testing. The models dict holds three models, and the loop fits each one and prints accuracy and F1. Random Forest wins on both scores, with 0.8212 accuracy and 0.7778 F1. What you would try next: tune the forest, add the cabin and ticket columns, and test a gradient boosting model with early stopping. In short, a survival model is a classifier that turns a passenger's ticket and age into a yes-or-no guess, and accuracy plus F1 say how good the guess is.
Note
The next step after this lesson is tuning, then trying the cabin and ticket columns.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which model wins the Titanic capstone?