Who Was Aboard the Titanic? Clustering Passengers (and Testing Whether It Helps Prediction)

Table of Contents

Everyone who has ever touched a Kaggle dataset has tried to predict who survived the Titanic. It’s the “Hello World” of machine learning: load the data, tune a model, submit a CSV, feel clever. I wanted to ask a different question.

Not “who survived?” but Seinfeld’s age-old question of “who are these people?”

Prediction treats the passengers as rows in a matrix. Clustering treats them as human beings who fall into natural groups: the wealthy elite, young workers, immigrant families, people traveling alone. Those groups fall out of the data on their own, without anyone labeling them. Then you overlay survival on top and the story gets a lot more human than any accuracy score.

The approach

K-means is unsupervised. You hand it the data and a number of groups (k), and it carves the passengers into k clusters where everyone in a cluster looks more like each other than like anyone outside it.

The important part: I never tell it about survival. It groups people purely on who they were, demographically. Only after the grouping is finished do I go back and check how each group fared.

Seven features, all numeric, all scaled:

features = ['IsFemale', 'Pclass', 'TitleCode', 'Age', 'Fare', 'FamilySize', 'IsAlone']

Everything gets StandardScaler-normalized first, otherwise fare (which runs from 0 to 512) would stomp all over the binary features.

How many groups?

The first real question in any clustering job: how many groups? Too few and you mash distinct populations together. Too many and you shred coherent groups into confetti.

I used silhouette scores (a measure of how cleanly separated the clusters are) for k from 2 to 10:

KSilhouette Score
20.3428
30.3615
40.3445
50.3640
60.3637
70.3977
80.4129
90.4271
100.4449

Silhouette scores and elbow method for K selection

The score keeps climbing, with k=10 giving the cleanest separation (0.4449). That makes sense. A ship carrying 891 people from different countries, classes, and family situations contains way more than three or four “types” of person. So I went with k=10, which also happens to give the richest story. For you k-means nerds, this is an importnat learning: The best model when clustering isn’t always the one that is at the elbow of the silloute scores, it is the one that is most useful. We’ll see how this is useful here and you’ll also find it useful in business use cases.

The passenger archetypes

Here’s what the algorithm found. Again: it was never told who survived. It grouped people by who they were, and the survival column is just painted on afterward.

ClusterArchetypeSizeSurvivalFemale%ClassAgeFare
0Solo Upper-Class Men88 (9.9%)27.3%1.1%1.343.5£29
1Third-Class Solo Men308 (34.6%)12.0%0.0%2.828.6£10
2Third-Class Women100 (11.2%)70.0%100%2.623.4£21
3Upper-Class Men23 (2.6%)34.8%13.0%1.345.7£37
4Large Families (3rd Class)34 (3.8%)11.8%76.5%3.020.3£39
5Young Boys39 (4.4%)59.0%0.0%2.64.5£34
6Wealthy Mixed-Gender Group20 (2.2%)70.0%60.0%1.031.1£279
7Middle-Class Men107 (12.0%)17.8%0.0%2.132.1£39
8Solo Third-Class Women93 (10.4%)72.0%100%2.626.5£10
9Upper-Class Women79 (8.9%)96.2%100%1.035.2£85

Cluster profiles comparison

Let me put some faces on these.

Cluster 9: the protected elite (96.2% survival)

First-class women, average age 35, paying £85 a ticket. Almost all of them lived. Wives and daughters of industrialists and diplomats and old money. When the lifeboats went, they went first, and the numbers say so flatly. This is “women and children first” working exactly as designed, for the people who happened to be standing closest to the boats.

Cluster 8: independent working women (72.0% survival)

Solo women in second and third class, around 26, paying £10. Traveling alone: servants, governesses, young women crossing the ocean for work. Lower class, but their gender still bought them a spot in a lifeboat, just at a lower rate than the wealthy women above them.

Cluster 2: third-class women with families (70.0% survival)

Women from the lower decks, younger (around 23), traveling with family. Their survival rate sits right next to the solo women, which says being female mattered more than whether you had kids with you. The 30% who didn’t make it were probably trapped below decks or lost in the chaos of the last hour.

Cluster 5: the children (59.0% survival)

Young boys, average age four and a half, traveling with big families. The “children” half of “women and children first” shows up here, but only at 59%. Plenty of kids in large third-class families were lost because the whole family stayed together and couldn’t reach the boat deck in time.

Cluster 4: large immigrant families (11.8% survival)

Big families (average size over seven) in third class, mostly female (76.5%), very young. Despite being mostly women and children, they died at a lower rate than solo first-class men. A huge family, berths deep in steerage, far from the boats, probably not many native English speakers. They wouldn’t split up, so they died together.

Cluster 1: the young male workers (12.0% survival)

The biggest group on the ship: 308 people, more than a third of everyone. Third- class men traveling alone, late twenties, £10 tickets. Economic migrants chasing a shot in America. Everything was stacked against them: male (last for the boats), third class (farthest from them), alone (nobody waiting or fighting for them). One in eight lived.

Cluster 7: middle-class family men (17.8% survival)

Second-class men with families, the clerks and teachers and shopkeepers traveling with a wife and kids. The wives mostly survived. The men mostly didn’t. Roughly one in six made it.

Cluster 0: solo upper-class gentlemen (27.3% survival)

First-class men, older (mid-forties), traveling alone. Wealthy bachelors, professionals. Not even money and a cabin near the boat deck could beat the gender rule, though at 27.3% they still did twice as well as third-class men. Wealth bought something, even for the men.

Survival through a different lens

This is the part that makes clustering worth it. A model tells you “being female raises survival probability by X%.” True, and completely abstract.

Clustering shows you the actual groups of humans and what happened to them:

Near-total survival (over 70%):

Middle (40 to 60%):

Near-total death (under 30%):

The gap from top to bottom is 84 percentage points. That’s not a statistic. It’s the distance between a first-class woman stepping calmly into a lifeboat and a young Irish laborer behind a locked gate below decks.

PCA visualization showing clusters and survival

The PCA plot shows the same passengers twice. Left panel colored by cluster, right panel colored by survival. They line up almost perfectly, even though the clustering never saw the survival column. The things that defined who you were on that ship are the same things that decided whether you lived.

What clustering shows that prediction doesn’t

The tragedy of large families. A model says “FamilySize over 5 lowers survival.” Clustering tells you who those families were: mostly women, very young, third class, probably not English-speaking, berthed as far from the boats as the ship allowed. Cluster 4 sitting at 11.8% while being 76.5% female blows a hole in the tidy “gender predicts survival” story.

Class cuts straight through gender. Women survived at 74% overall. But look closer: 96.2% for upper-class women, 72% for solo third-class women, 11.8% for women in large immigrant families. “Women and children first” was absolutely not applied equally.

The population itself is the story. A third of the ship was solo third-class men with basically no chance (12%). The Titanic wasn’t mainly ferrying rich people. It was carrying a working-class male workforce, plus families chasing a new life, with a thin layer of privilege on top.

The ambiguous middle is real. The young boys at 59% sit right on the decision boundary. Some were saved, some died with their families. A model calls that noise. Clustering says no, it’s a real group whose fate came down to which boat was close, whether their mother was there, which officer made the call.

So does clustering actually help the prediction?

Fair question. If I bolt cluster membership on as a feature, does my survival model get better? I ran a little arena with four setups:

# Model A: Baseline, my best 7-feature GBM
# Model B: Add cluster_id as an 8th feature
# Model C: Add cluster_id + out-of-fold cluster survival rate
# Model D: Train a separate model per cluster

The leakage trap (Model C)

Model C adds a “cluster survival rate” feature: the average survival of everyone in your cluster. Powerful, and dangerous. If you compute that rate from all the training data and then cross-validate, you’ve leaked the answer, because the survival rate includes the validation passenger’s own label. (Same trap once gave me a gorgeous CV of 98.8% and a leaderboard of 0.727. Humbling.)

The fix is out-of-fold computation. For each fold, compute the cluster survival rates using only the training portion, then apply them to the held-out part:

for train_idx, val_idx in cv.split(X, y):
    # survival rate computed ONLY from the training fold
    fold_clusters = train_clusters[train_idx]
    fold_y = y.iloc[train_idx]
    cluster_surv_map = {c: fold_y[fold_clusters == c].mean() for c in range(best_k)}
    # apply to the validation fold (no leakage)
    oof_survival[val_idx] = [cluster_surv_map[c] for c in train_clusters[val_idx]]

The results

RankModelCV Accuracyvs Baseline
1A: Baseline GBM (no clusters)0.8507 ± 0.015best
2C: GBM + cluster_id + OOF rate0.8474 ± 0.012-0.003
3B: GBM + cluster_id0.8418 ± 0.007-0.009
4D: Per-cluster models0.8350 ± 0.012-0.016

On this dataset: nope. The cluster features actually hurt. The baseline GBM already finds the gender-by-class-by-age interactions that define the clusters, so I’m just handing it noise. The per-cluster models are the worst of the bunch, because splitting 891 rows across 10 clusters leaves some with 20-odd passengers, nowhere near enough to train anything trustworthy.

Which is itself the lesson: unsupervised and supervised learning do different jobs. Supervised learning chases accuracy on a target you already know. Unsupervised learning hands you the structure of your population. Both are worth having. They answer different questions.

When clustering-as-preprocessing does pull its weight

From this and from other projects, clustering before a supervised model tends to help when:

And it mostly doesn’t when:

It always helps your understanding, though, whether or not it moves the score.

The takeaway

The Titanic is always framed as a prediction problem. Prediction tells you which features matter. Clustering tells you who was actually on the boat.

Step back and ask “what natural groups live in this data?” and you get a ship that was a third young working men with almost no chance, a thin sliver of first- class women who nearly all lived, many large immigrant families (mostly women and kids) who died worse than wealthier men, and a hard class line running straight through even the “protected” category of women. You don’t get any of that from a feature-importance bar chart.

Next time you’ve got a prediction problem, try running unsupervised learning first. Not to juice the score, but to actually understand what you’re looking at. Sometimes the clusters change the whole question.

Technical details

The clustering pipeline, start to finish:

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score

# Scale features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_train[features])

# Find optimal K
for k in range(2, 11):
    km = KMeans(n_clusters=k, random_state=42, n_init=10)
    labels = km.fit_predict(X_scaled)
    score = silhouette_score(X_scaled, labels)
    print(f"K={k}: silhouette={score:.4f}")

# Fit with the best K
kmeans = KMeans(n_clusters=10, random_state=42, n_init=20)
clusters = kmeans.fit_predict(X_scaled)

# Overlay survival (never seen by the clustering algorithm)
for c in range(10):
    mask = clusters == c
    survival_rate = y_train[mask].mean()
    print(f"Cluster {c}: {mask.sum()} passengers, {survival_rate:.1%} survival")

Full script: clustering_analysis.py.