Module 10 · Intermediate · Decision trees

Titanic survival prediction project in Python

A Titanic survival prediction project in Python with decision trees: baselines, a pipeline, tuning, model comparison, an honest test and error analysis.

By theprogrammers team · · 16 min read

On 15 April 1912, the Titanic sank with about 2,200 people aboard, and fewer than a third survived. Survival wasn't random: "women and children first" was the rule at the lifeboats, and first-class cabins were closer to the boat deck. This Titanic survival prediction project asks how well a model can tell, from a passenger's ticket class, sex, age, fare and family aboard, whether they survived, and whether it does better than the simple rule a historian would give you.

You'll build it with a decision tree: check the data for columns that give the answer away, set baselines, build a pipeline, tune the tree, compare it with the models from earlier modules, test it once, and then find out why the test score is disappointing. That last step is the most useful part of the project.

What you need first: decision trees explained, hyperparameter tuning, scikit-learn pipelines and data leakage.

Key terms

  • Label leakage: a feature that contains the answer, or is recorded after it, so the model looks brilliant and is useless.
  • Baseline: the score of a simple method that any model must beat.
  • Repeated cross-validation: cross-validation run several times with different shuffles, to see how much scores wobble.
  • Error analysis: studying the rows a model gets wrong to learn what it's missing.

The goal, metric and baseline

  • Goal: predict whether a passenger survived from facts known when they boarded.
  • Metric: accuracy. About 38% survived, so the classes are uneven but not rare; accuracy is easy to explain, and the confusion matrix in Step 10 shows the two kinds of mistake.
  • Baselines: predicting "died" for everyone, and the rule "women survive, men don't".

Step 1: load the data and look for leaks

Download the data: titanic.csv (58 KB), or from the original source, the seaborn-data repository on GitHub. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("titanic.csv").

import numpy as np
import pandas as pd
import seaborn as sns

titanic = sns.load_dataset("titanic")
print(titanic.shape)
print(titanic.head(3).T)
(891, 15)
                       0          1            2
survived               0          1            1
pclass                 3          1            3
sex                 male     female       female
age                 22.0       38.0         26.0
sibsp                  1          1            0
parch                  0          0            0
fare                7.25    71.2833        7.925
embarked               S          C            S
class              Third      First        Third
who                  man      woman        woman
adult_male          True      False        False
deck                 NaN          C          NaN
embark_town  Southampton  Cherbourg  Southampton
alive                 no        yes          yes
alone              False      False         True

sns.load_dataset downloads the table once and keeps a copy. .T turns the table on its side, so each column becomes a row and all 15 fit on screen.

Predict first: before reading on, which columns would you refuse to give the model?

Several columns are the same information twice, and one is the answer itself:

ColumnProblemDecision
alive"yes"/"no": the label in wordsDrop: pure leakage
class, embark_townCopies of pclass and embarkedDrop
who, adult_maleBuilt from sex and age by whoever prepared the dataDrop, and let the model use sex and age
aloneBuilt from sibsp and parchDrop; Step 5 builds its own version
deckMissing for most passengersDrop for now (see Take it further)

See what alive would do:

from sklearn.tree import DecisionTreeClassifier

leaky = DecisionTreeClassifier(max_depth=1).fit(titanic[["alive"]].eq("yes"), titanic["survived"])
print("accuracy with alive as a feature:", leaky.score(titanic[["alive"]].eq("yes"), titanic["survived"]))
accuracy with alive as a feature: 1.0

.eq("yes") turns the text into True or False. One question, perfect accuracy, and nothing learnt. Always ask of each column: would I know this before the outcome?

Step 2: explore

print(titanic.isna().sum()[lambda counts: counts > 0])
print(titanic.groupby(["sex", "pclass"])["survived"].mean().unstack().round(2))
age            177
embarked         2
deck           688
embark_town      2
dtype: int64
pclass     1     2     3
sex                     
female  0.97  0.92  0.50
male    0.37  0.16  0.14

isna().sum() counts the missing values per column, and [lambda counts: counts > 0] keeps only the columns with any. groupby(...).mean() on a 0/1 column gives the survival rate of each group, and unstack() spreads the classes into columns.

Two facts dominate: women survived far more often than men, and first class more often than third. Age is missing for 177 passengers, about one in five.

import matplotlib.pyplot as plt

titanic["age_group"] = pd.cut(titanic["age"], bins=[0, 12, 18, 40, 60, 80],
                              labels=["0–12", "13–18", "19–40", "41–60", "61–80"])
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
sns.barplot(data=titanic, x="pclass", y="survived", hue="sex", hue_order=["female", "male"], errorbar=None, ax=axes[0])
axes[0].set_title("Survival rate by class and sex")
sns.barplot(data=titanic, x="age_group", y="survived", hue="sex", hue_order=["female", "male"], errorbar=None, ax=axes[1])
axes[1].set_title("Survival rate by age group and sex")
for ax in axes:
    ax.set_ylabel("Share who survived")
plt.tight_layout()
plt.show()
Two bar charts of survival rates. Left, by class: women survived at about 0.97 in first class, 0.92 in second and 0.50 in third; men at about 0.37, 0.16 and 0.14. Right, by age group: for ages 0 to 12, boys and girls both survived at about 0.6; in every older group, women survived at 0.75 to 1.0 and men at only 0.1 to 0.2.

pd.cut sorts ages into labelled bands; passengers with no age get no band and are left out of the right-hand chart. hue_order gives each sex the same colour in both charts, and errorbar=None hides seaborn's uncertainty lines to keep the bars readable.

Boys aged 12 or under survived far more often than older males: "children first" shows up in the data. These interactions, where the effect of age depends on sex, are what trees capture naturally.

Step 3: choose features and split

family_size counts the passenger plus the siblings, spouses, parents and children aboard. It's a new feature built from two columns, as in feature engineering basics.

from sklearn.model_selection import train_test_split

titanic["family_size"] = titanic["sibsp"] + titanic["parch"] + 1
features = ["pclass", "sex", "age", "sibsp", "parch", "fare", "embarked", "family_size"]
X, y = titanic[features], titanic["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape, f"survived in training: {y_train.mean():.3f}")
(712, 8) (179, 8) survived in training: 0.383

The test set of 179 passengers is locked away until Step 9.

Step 4: baselines

from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.dummy import DummyClassifier

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
dummy = cross_val_score(DummyClassifier(strategy="most_frequent"), X_train, y_train, cv=cv).mean()
rule = ((X_train["sex"] == "female").astype(int) == y_train).mean()
print(f"everyone died:          {dummy:.3f}")
print(f"women survive, men die: {rule:.3f}")
everyone died:          0.617
women survive, men die: 0.789

The rule learns nothing from the data, so its training accuracy is a fair estimate on its own. A model has to beat 0.789 to be worth anything, and that's a high bar: one line of common sense.

Step 5: a pipeline and a first tree

The pipeline fills missing ages with the median, fills the 2 missing ports with the most common one, and one-hot encodes the text columns. Because it's a pipeline, each cross-validation fold learns its median from its own training rows.

from sklearn.pipeline import make_pipeline
from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numbers = ["pclass", "age", "sibsp", "parch", "fare", "family_size"]
text = ["sex", "embarked"]

def preparation(scale=False):
    number_steps = [SimpleImputer(strategy="median")] + ([StandardScaler()] if scale else [])
    return make_column_transformer(
        (make_pipeline(*number_steps), numbers),
        (make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore")), text),
        verbose_feature_names_out=False)

for depth in [3, None]:
    tree = make_pipeline(preparation(), DecisionTreeClassifier(max_depth=depth, random_state=0))
    print(f"tree, max_depth={str(depth):4}: CV accuracy {cross_val_score(tree, X_train, y_train, cv=cv).mean():.3f}")
tree, max_depth=3   : CV accuracy 0.813
tree, max_depth=None: CV accuracy 0.775

preparation(scale=True) adds a scaler for the models that need one in Step 8; trees don't. *number_steps unpacks the list into separate arguments. verbose_feature_names_out=False keeps the column names short, such as sex_female.

A depth-3 tree beats the rule by about two points. The unlimited tree falls below it: it memorises passengers.

Step 6: tune the tree

from sklearn.model_selection import GridSearchCV

search = GridSearchCV(
    make_pipeline(preparation(), DecisionTreeClassifier(random_state=0)),
    {"decisiontreeclassifier__max_depth": [2, 3, 4, 5, 6, 8, None],
     "decisiontreeclassifier__min_samples_leaf": [1, 5, 10, 20, 40]},
    cv=cv)
search.fit(X_train, y_train)
print(search.best_params_, f"CV accuracy {search.best_score_:.3f}")
{'decisiontreeclassifier__max_depth': 5, 'decisiontreeclassifier__min_samples_leaf': 5} CV accuracy 0.824

Step 7: what did the tree learn?

best_tree = search.best_estimator_
names = best_tree[0].get_feature_names_out()
importance = pd.Series(best_tree[-1].feature_importances_, index=names)
print(importance.sort_values(ascending=False).round(3))
sex_male       0.556
pclass         0.193
age            0.093
fare           0.091
family_size    0.046
embarked_S     0.018
sibsp          0.002
sex_female     0.000
parch          0.000
embarked_C     0.000
embarked_Q     0.000
dtype: float64

best_estimator_ is the pipeline refitted on all the training data with the best settings. best_tree[0] is its first step, the column transformer, and best_tree[-1] its last, the tree.

Sex dominates, as the charts promised; sex_female and sex_male carry the same information, so the tree used one and ignored the other. Class follows, then age and fare. family_size matters more than sibsp and parch separately, so the engineered feature earned its place.

Step 8: compare with other models

The tree isn't the only option. Logistic regression, KNN and the SVM from earlier modules need scaled features. Predict first: will any of them beat the tuned tree?

A single 5-fold run can favour one model by luck, so this comparison repeats it 5 times with different shuffles and reports the spread:

from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC

repeated = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=0)
models = {
    "Tuned tree": best_tree,
    "Logistic regression": make_pipeline(preparation(scale=True), LogisticRegression(max_iter=1000)),
    "KNN (k=15)": make_pipeline(preparation(scale=True), KNeighborsClassifier(n_neighbors=15)),
    "SVM (RBF kernel)": make_pipeline(preparation(scale=True), SVC()),
}
for name, model in models.items():
    scores = cross_val_score(model, X_train, y_train, cv=repeated)
    print(f"{name:20}: {scores.mean():.3f} ± {scores.std():.3f}")
Tuned tree          : 0.821 ± 0.023
Logistic regression : 0.793 ± 0.028
KNN (k=15)          : 0.815 ± 0.030
SVM (RBF kernel)    : 0.819 ± 0.027

± shows the standard deviation across the 25 rounds. The tree, the SVM and KNN are within a point of each other, well inside the spread of 2 to 3 points, so none is really better. Logistic regression trails by almost three points: a single straight-line score struggles with interactions such as "age matters for males, class matters for females". The tree wins the tie because you can print it and explain it, which matters for a question about people. (The tree's settings were chosen with the same training data, which flatters its score slightly; Step 9's check covers that.)

Step 9: the final test, and a surprise

test_accuracy = best_tree.score(X_test, y_test)
rule_test = ((X_test["sex"] == "female").astype(int) == y_test).mean()
print(f"tuned tree on the test set: {test_accuracy:.3f}")
print(f"the women-survive rule:     {rule_test:.3f}")
tuned tree on the test set: 0.754
the women-survive rule:     0.777

The tuned tree scores below the one-line rule on the test passengers, after scoring three and a half points above it in cross-validation. Did the tuning overfit, or is this test set just unusual?

You can't tune again on the test set: that would make its score meaningless. But you can check the process. Experiment: repeat the whole thing, split, tune and test, with 10 other random splits. Predict first: on how many of them will the tree lose to the rule?

rows = []
for seed in range(10):
    Xa, Xb, ya, yb = train_test_split(X, y, test_size=0.2, stratify=y, random_state=seed)
    s = GridSearchCV(make_pipeline(preparation(), DecisionTreeClassifier(random_state=0)),
                     search.param_grid, cv=cv).fit(Xa, ya)
    rows.append({"split": seed, "tree": s.score(Xb, yb),
                 "rule": ((Xb["sex"] == "female").astype(int) == yb).mean()})
results = pd.DataFrame(rows).set_index("split")
print(results.round(3).T)
print(results.mean().round(3).to_string())
split      0      1      2      3      4      5      6      7      8      9
tree   0.810  0.838  0.827  0.844  0.849  0.821  0.799  0.793  0.860  0.849
rule   0.777  0.804  0.777  0.827  0.765  0.793  0.765  0.765  0.844  0.788
tree    0.829
rule    0.791

search.param_grid reuses the same grid of settings. Each row of results is one complete run of the project on a different split.

On every one of the other splits, the tuned tree beats the rule, by about four points on average. The split with random_state=42 happens to be a hard one for the tree. With 179 test passengers, each passenger is about half a percentage point, so the gap to the rule, 0.754 against 0.777, is 4 passengers. The honest summary: expect about 0.82 to 0.83, with single test sets landing anywhere from about 0.79 to 0.86. A single test score is one draw, and a small test set makes for a noisy draw.

Step 10: look at the mistakes

from sklearn.metrics import confusion_matrix

test_pred = best_tree.predict(X_test)
print(confusion_matrix(y_test, test_pred))
wrong = X_test.assign(survived=y_test, predicted=test_pred)[y_test != test_pred]
print(wrong.groupby(["sex", "pclass"]).size().unstack(fill_value=0))
[[94 16]
 [28 41]]
pclass   1  2   3
sex              
female   1  1  11
male    14  3  14

The rows of the confusion matrix are the real outcome (died, survived) and the columns the prediction. assign adds columns to a copy of the table, and the mask keeps the wrong rows. size() counts them by sex and class.

The mistakes cluster where the rules of the night broke down: men who survived (mostly predicted to die), and third-class women, who survived only half the time. Nothing in these features can tell which third-class women reached a lifeboat; where they were on the ship and when they heard would. That's the ceiling on any model built from these columns.

Step 11: use the model

Two new passengers, as a model would see them on the passenger list:

passengers = pd.DataFrame({
    "pclass": [3, 1], "sex": ["female", "male"], "age": [24, np.nan], "sibsp": [0, 0],
    "parch": [2, 0], "fare": [15.0, 80.0], "embarked": ["S", "C"], "family_size": [3, 1],
})
print(best_tree.predict_proba(passengers)[:, 1].round(2))
[0.41 0.31]

np.nan marks the second passenger's unknown age; the pipeline fills it with the training median, just as it did in training. [:, 1] keeps the probability of surviving, which is the share of survivors in the leaf each passenger lands in.

The young third-class mother gets 0.41. Her path through the tree is female, third class, a family of 4 or fewer, boarded at Southampton, older than 7.5: in the training data, 44 passengers took that path and 18 of them survived. The first-class man with an unknown age gets 0.31, the survival share of 55 first-class men who paid higher fares. Both predictions are "died", but neither is confident, which matches the history: these were the groups whose fate depended most on luck.

Limitations

  • 891 passengers is a small dataset: test scores move by several points between splits, as Step 9 showed.
  • Missing information. Where people were on the ship when it hit, and when they reached the deck, decided many fates, and none of it is in the data.
  • Imputed ages. One in five ages is a filled-in median, which blurs the "children first" pattern.
  • Historical data. The model describes one night in 1912. It isn't a model of who survives disasters in general.

Take it further

Try these on your own. There are no worked answers: compare your results with repeated cross-validation, as in Step 8.

  1. Use the deck. Add deck with missing values filled as "unknown", one-hot encoded. Does knowing that the deck is missing help? Hint: missing decks are mostly third class.
  2. Children. Add an is_child feature (age 12 or under) before imputing ages. Does the tree need it, or does it already split on age? Hint: compare export_text before and after.
  3. Smarter age filling. Fill missing ages with the median of each class and sex instead of one overall median. Hint: write a small transformer, or use groupby(...).transform("median") inside a function wrapped in FunctionTransformer.
  4. Pruning. Tune ccp_alpha instead of depth and leaf size. Hint: cost_complexity_pruning_path on the training data gives candidate values.
  5. Explain one passenger. For a passenger the tree gets wrong, trace their path with best_tree[-1].decision_path and the transformed row from best_tree[0].transform.

Practice

  1. Why is who a problem even though it isn't the label?
Show the answer

It was built by whoever prepared the data, from sex and age, using an age cut-off they chose. The model can learn the same thing from sex and age itself, and keeping who hides the decision about where "child" ends inside a column nobody checks. It's not leakage of the answer, but it is duplicated information made with an unknown rule.

  1. Why does the rule baseline in Step 4 not need cross-validation?
Show the answer

It learns nothing from the training data: "women survive" is fixed in advance. Its accuracy on the training passengers is already an honest estimate of its accuracy on new passengers from the same population.

  1. Using the results table from Step 9, how many of the 10 other splits did the tree win against the rule, and by how much on average?
Show the answer
print((results["tree"] > results["rule"]).sum(), "of", len(results))
print(round(results["tree"].mean() - results["rule"].mean(), 3))
10 of 10
0.039
  1. Train the tuned tree's settings with max_depth=3 instead and print the rules with export_text. Which questions does it ask?
Show the answer
from sklearn.tree import export_text

small = make_pipeline(preparation(), DecisionTreeClassifier(max_depth=3, random_state=0)).fit(X_train, y_train)
print(export_text(small[-1], feature_names=list(small[0].get_feature_names_out())))
|--- sex_male <= 0.50
|   |--- pclass <= 2.50
|   |   |--- fare <= 28.86
|   |   |   |--- class: 1
|   |   |--- fare >  28.86
|   |   |   |--- class: 1
|   |--- pclass >  2.50
|   |   |--- family_size <= 4.50
|   |   |   |--- class: 1
|   |   |--- family_size >  4.50
|   |   |   |--- class: 0
|--- sex_male >  0.50
|   |--- age <= 3.50
|   |   |--- sibsp <= 2.50
|   |   |   |--- class: 1
|   |   |--- sibsp >  2.50
|   |   |   |--- class: 0
|   |--- age >  3.50
|   |   |--- pclass <= 1.50
|   |   |   |--- class: 0
|   |   |--- pclass >  1.50
|   |   |   |--- class: 0

The root separates the sexes; the next questions are about age for males and class for females, the same story as the charts in Step 2.

  1. A friend reports "my Titanic model gets 0.95 accuracy". Name two things you'd check first.
Show the answer

Whether a leaky column such as alive, or anything recorded after the sinking, is among the features; and whether the score came from the training data or from many tries on the same test set. Honest scores on these features land around 0.80 to 0.85.

Interview questions

How do you know if a model's test score is reliable?

Consider the size of the test set: each row moves accuracy by 1 ÷ n. Compare with cross-validation on the training data, and if possible repeat the whole process over several random splits to see the spread. One small test set is a single noisy draw.

What's label leakage, with an example?

A feature that contains the target or information recorded after it. In the Titanic data, alive is the survival label in words; a model using it scores 100% and is useless. Check every feature: would it be known at prediction time?

Why choose a decision tree when an SVM scores the same?

When scores are within the noise, prefer the model that's simpler to explain, check and maintain. A small tree can be printed and audited; an RBF SVM can't be read directly.

Key takeaways

  • Check every column for leakage first: would you know it before the outcome?
  • A common-sense rule can be a strong baseline; here "women survive" scores 0.789.
  • Tune and compare with cross-validation inside a pipeline; when scores tie, prefer the explainable model.
  • A small test set is noisy: repeat the whole process over several splits before trusting or doubting one score.
  • Error analysis shows the ceiling: the features can't tell which third-class women reached a lifeboat.

Frequently asked questions

Is this the same as the Kaggle Titanic competition?

It's the same 891 passengers, loaded from seaborn instead. The competition scores predictions on another 418 passengers whose outcomes are hidden; the methods here carry straight over.

What's a good accuracy for Titanic?

With these features, about 0.80 to 0.84 on new passengers. Scores far above that usually mean leakage or a lucky test set.

Would a random forest do better?

Usually a little, because averaging many trees removes much of one tree's instability. That's the next module.

What to learn next

  1. Average hundreds of trees to fix one tree's instability in random forest explained, the next module.
  2. Revisit the tree you built by hand in decision tree from scratch in Python.
  3. Review why a single test score can mislead in cross-validation explained.