Predicting Titanic Survival: A Beginner's Machine Learning Walkthrough with Python

2022-08-07

Loading the Data

I began by importing the foundational libraries: NumPy and pandas for numerical and data manipulation tasks. Next, I loaded the training and test datasets provided by Kaggle. To get a feel for the data, I viewed the first few rows using.head(). This showed me essential features like Survived, Pclass, Name, Sex, Age, Fare, and more. The training set includes the target variable Survived, while the test set does not, we'll use it later for predictions.

import numpy as np 
import pandas as pd

trainData = pd.read_csv("train.csv")
testData = pd.read_csv("test.csv")
trainData.head()
testData.head()

Understanding the Data and Exploring Survival Correlation

To better understand the structure and summary statistics of the training dataset .describr(), .info(). From this, I learned that several features (Age, Cabin, Embarked) have missing values. There are a mix of numerical and categorical variables: 7 numerical (like Age, Fare) and 5 categorical (like Sex, Embarked, Cabin).

My next step was to explore assumptions about who survived. I used common sense and historical context to guide my exploration. First, I looked at the Pclass feature to see if it correlated with survival. This revealed a clear pattern: passengers in 1st class had a 62.9% survival rate, compared to 47.3% in 2nd class and only 24.2% in 3rd class. The wealthier you were, the better your odds. Next, I grouped by gender, females had a staggering 74.2% survival rate, while males had just 18.9%. This aligned with the "women and children first" narrative often associated with Titanic lore. I then checked aged where I did visulize the survival distribution by age using seaborn:

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

g = sns.FacetGrid(trainData, col='Survived')
g.map(plt.hist, 'Age', bins=20)

This plot revealed a higher survival rate among younger children, though the age cut-off wasn't immediately clear from the histogram alone. I also examined the relationship between family size onboard (via Parch, which counts parents/children) and survival. Passengers with 1–3 relatives on board had better survival rates, but too many or none decreased the odds. To gain more visual insights, I looked at Pclass, Embarked, and Sex across survival.

grid = sns.FacetGrid(trainData, col='Survived', row='Pclass')
grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend()

grid = sns.FacetGrid(trainData, row='Embarked', height=2.2, aspect=1.6)
grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep')
grid.add_legend()

These visuals helped identify further trends, like higher fares correlating with survival in some embarkation ports.

Cleaning and Feature Engineering

Some columns were noisy or sparsely populated — especially Ticket and Cabin. I decided to drop them.

trainData = trainData.drop(["Ticket", "Cabin"], axis=1)
testData = testData.drop(["Ticket", "Cabin"], axis=1)

I then engineered a new feature: Title, extracted from the Name field. Titles like "Mr", "Mrs", and "Miss" might hold predictive power. After checking the frequency of titles across genders, I grouped rare titles under a common labe.

totalDataSet = [trainData, testData]
for d in totalDataSet:
d['Title'] = d.Name.str.extract(' ([A-Za-z]+)\.', expand=False)

for d in totalDataSet:
d['Title'] = d['Title'].replace(['Lady', 'Countess','Capt', 'Col',
'Don', 'Dr', 'Major', 'Rev', 'Sir',
'Jonkheer', 'Dona'], 'Rare')
d["Title"] = d["Title"].replace(["Mlle", "Ms"], "Miss")
d["Title"] = d["Title"].replace("Mme", "Mrs")

Titles also showed strong correlation with survival. To prepare for model training, I converted titles into ordinal numerical values. I dropped the original Name column as it was know irrelevan and converting the title column (and other field like sex) into numerical values.

titleOrdData = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5}
for d in totalDataSet:
d['Title'] = d['Title'].map(titleOrdData)
d['Title'] = d['Title'].fillna(0)

Handling Missing Values in the Titanic Dataset

After our initial data cleaning and feature engineering, the next major task is to deal with missing values. A quick .info() call earlier revealed that several key features have null entries — namely, Age, Embarked, and Fare. Each of these needs to be treated carefully.

The Age column has quite a few missing entries in both the training and test datasets. Since age is a continuous variable and likely correlated with other features (like Pclass and Sex), I decided to use a more nuanced approach to fill these gaps. I observed that passengers’ age might vary by class and gender. To impute missing ages, I calculated median age values grouped by both Sex and Pclass. 

for dataset in totalDataSet:
dataset['Age'] = dataset['Age'].fillna(dataset.groupby(['Sex', 'Pclass'])['Age'].transform('median'))

This means, for example, that missing ages for third-class males would be filled with the median age of other third-class males. This approach preserves patterns in the data and avoids skewing distributions.

There were two missing values in the Embarked column. To find out more about them, I isolated those rows. Both passengers had very similar fares (around $80) and were in first class. To determine their most likely embarkation point, I visualized the fare distribution by embarkation port. It turned out that passengers paying similar fares in first class most often embarked at 'C' (Cherbourg). So I filled in the missing values accordingly. After this, I converted the Embarked feature into numerical form for model readiness.

There was a single missing Fare value in the test dataset. Again, I checked the corresponding passenger's class and embarked port. This passenger was in third class and embarked from ‘S’. I used the median fare for this group to fill the missing value. This simple imputation avoids inserting outliers or bias while allowing the model to use the Fare feature effectively.

Feature Scaling and Model Building

As the next crucial step, you applied feature scaling using StandardScaler from sklearn. This standardization ensures all features share a common scale, improving model training, especially for algorithms like SVM or logistic regression.

I started by separating the target variable from the training set and selecting the features for modeling.

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(xTrain)
X_test = sc.transform(xTest)

This preprocessing ensures a level playing field for all features and helps models converge more quickly and accurately.

With the features scaled, I began training different models to compare performance. Here's how that looked

Logistic Regression
Support Vector Machine (SVM)
from sklearn.svm import SVC
svc = SVC()
svc.fit(X_train, yTrain)
acc_svc = round(svc.score(X_train, yTrain) * 100, 2)

83.61
K-Nearest Neighbors (KNN)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, yTrain)
acc_knn = round(knn.score(X_train, yTrain) * 100, 2)

88.22
Gaussian Naive Bayes
from sklearn.naive_bayes import GaussianNB
gaussian = GaussianNB()
gaussian.fit(X_train, yTrain)
acc_gaussian = round(gaussian.score(X_train, yTrain) * 100, 2)

78.23

Model Comparison Summary


ModelTraining Accuracy
Logistic Regression81.37%
SVM (SVC)83.61%
K-Nearest Neighbors88.22%
Gaussian NB78.23%

KNN leads the pack on training accuracy, though you’ll want to validate these on a holdout set or via cross-validation to check generalization.

Edit: Looking Back with New Eyes

I originally completed this Titanic machine learning project almost a year after finishing my undergraduate degree in Computer Science. At the time, I was working full-time as a front-end web developer and beginning to explore the world of data science more seriously. This project marked one of my first deep dives into real-world data analysis and machine learning, and while I’m proud of what I achieved back then, revisiting it now with fresh eyes,especially after starting my MSc in Data Science & Analytics at Royal Holloway, University of London. It has made me realise just how much I missed the first time around.

Looking back, I can see I had a decent handle on the fundamentals: cleaning data, handling missing values logically, and performing basic exploratory analysis. But when it came to the machine learning side, I was still quite early in my journey. My model experimentation was limited—I only tried a handful of classifiers like logistic regression, SVM, and KNN, and mainly judged performance using training accuracy.

Since beginning my master’s, I’ve gained a much broader and deeper understanding of machine learning. If I were to redo this project today, I’d definitely take a more rigorous and expansive approach.

    • Explore more models: Decision trees, neural networks, and powerful ensemble methods like Random Forest or XGBoost were completely off my radar at the time.
    • Use proper evaluation techniques: Instead of relying solely on training accuracy, I’d implement cross-validation and use grid search to fine-tune hyperparameters, while being careful to avoid data leakage.
    • Evaluate performance more thoroughly: Beyond accuracy, I now know the importance of looking at precision, recall, F1-score, and ROC AUC, especially when dealing with imbalanced datasets.
    • Dig deeper into feature importance and interpretation: Tools like SHAP values or permutation importance would have helped me better understand what was driving predictions.

      In short, this project is a clear snapshot of where I was in my data journey at the time: curious, logical, and ready to learn, but with a long way still to go. Revisiting it now has not only shown me how far I’ve come, but also reaffirmed my passion for this field. The Titanic dataset may be over a century old, but for me, it’s been a launchpad into the modern world of data science.
      Here is a link to the github repository.

      More posts connected by shared tags or overlapping topics.

      Web Scraping Series (Part 1): The Basics of Web Scraping

      Read post

      Web Scraping Series Part 2 Dynamic Pages and Browser Automation with Selenium

      Read post