Mathew K Analytics

Lesson 14 · Python For Machine Learning

Titanic Survival Prediction with Python: Data Analysis & Machine Learning Basics

In this lesson, we will use Python to predict who survived the Titanic. We will start from the basics, explain every concept, and work together step by…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Welcome to Python for Absolute Beginners: Titanic Survival Prediction#

In this lesson, we will use Python to predict who survived the Titanic. We will start from the basics, explain every concept, and work together step by step. No previous coding or machine learning experience is needed!

Let us begin.

What is Python?#

Python is a popular programming language. People use it to create websites, analyze data, automate tasks, and make predictions. It is known for being easy to read and learn.

We will write real Python code in this lesson.

# Let us print a welcome message
print("Hello, Titanic explorers!")
Hello, Titanic explorers!
# Let us import the warning filter to keep our notebook clean
import warnings
warnings.filterwarnings("ignore")

Variables and Data Types#

Variables let us store information. We use them to keep track of things, like a person's age. Python can work with different types of data, such as numbers and words.

# Let us save a name and an age
name = "Eva"
age = 11
print(name)
print(age)
Eva
11
# Strings hold text or words, while integers store numbers.
favorite_color = input("What is your favorite color? ")
print("You chose", favorite_color)
You chose blue
 

Lists and Dictionaries#

Lists are ways to store many items in order. Dictionaries store pairs of information, like a name and a phone number. We will use both with the Titanic data.

# A list of passenger names
passengers = ["Eva", "John", "Lucy"]
print(passengers)
['Eva', 'John', 'Lucy']
# A dictionary for a Titanic passenger
passenger1 = {"name": "Eva", "age": 11, "survived": True}
print(passenger1)
{'name': 'Eva', 'age': 11, 'survived': True}
# Data setup
import pandas as pd
titanic_url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"
df = pd.read_csv(titanic_url)
print("Data shape:", df.shape)
df.head()
Data shape: (891, 12)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S
# What does the data contain?
print(df.columns.tolist())
print("Survived counts:")
print(df['Survived'].value_counts())
['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked']
Survived counts:
Survived
0    549
1    342
Name: count, dtype: int64
# Picking important features for prediction
features = ["Pclass", "Sex", "Age", "SibSp", "Fare"]
target = "Survived"
data = df[features + [target]].copy()
data.head()
Pclass Sex Age SibSp Fare Survived
0 3 male 22.0 1 7.2500 0
1 1 female 38.0 1 71.2833 1
2 3 female 26.0 0 7.9250 1
3 1 female 35.0 1 53.1000 1
4 3 male 35.0 0 8.0500 0
# Checking for missing values
print(data.isnull().sum())
Pclass        0
Sex           0
Age         177
SibSp         0
Fare          0
Survived      0
dtype: int64
# Let us fill missing ages with the average age
mean_age = data['Age'].mean()
data['Age'] = data['Age'].fillna(mean_age)

Data Preparation and Simple Analysis#

Now our data is ready. Let us look at some simple patterns before we build a prediction.

# Find average survival by passenger class
print(data.groupby("Pclass")["Survived"].mean())
Pclass
1    0.629630
2    0.472826
3    0.242363
Name: Survived, dtype: float64
# Let us turn words into numbers so a model can understand them
data['Sex'] = data['Sex'].map({'male': 0, 'female': 1})
# Split into train and test sets
from sklearn.model_selection import train_test_split
X = data[features]
y = data[target]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Building a Simple Prediction Model#

Let us predict survival using a Decision Tree. A machine learning model finds patterns in the data and helps us guess outcomes.

# Train a Decision Tree predictor
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)
DecisionTreeClassifier(random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
# Test the model and see how well it predicts survivors
score = model.score(X_test, y_test)
print("Accuracy:", score)
Accuracy: 0.7541899441340782
# Predict survival for a new passenger you create
my_passenger = [[3, 1, 12.0, 0, 10.5]]  # 3rd class, female, 12 years, alone, cheap ticket
result = model.predict(my_passenger)
if result[0] == 1:
    print("Survived!")
else:
    print("Did not survive.")
    
Survived!
# Try a feature: importance for the model
print(pd.Series(model.feature_importances_, index=features))
Pclass    0.115226
Sex       0.310140
Age       0.256219
SibSp     0.060720
Fare      0.257695
dtype: float64

Extra: Visualizing a Decision Tree#

Visualization makes patterns easier to understand. Let us see the structure of our decision tree.

# Visualize a simple tree (text form)
from sklearn.tree import export_text
tree_rules = export_text(model, feature_names=features)
print(tree_rules)
|--- Sex <= 0.50
|   |--- Age <= 6.50
|   |   |--- SibSp <= 2.50
|   |   |   |--- class: 1
|   |   |--- SibSp >  2.50
|   |   |   |--- Age <= 2.50
|   |   |   |   |--- class: 0
|   |   |   |--- Age >  2.50
|   |   |   |   |--- Age <= 3.50
|   |   |   |   |   |--- class: 1
|   |   |   |   |--- Age >  3.50
|   |   |   |   |   |--- class: 0
|   |--- Age >  6.50
|   |   |--- Pclass <= 1.50
|   |   |   |--- Fare <= 387.66
|   |   |   |   |--- Fare <= 26.14
|   |   |   |   |   |--- class: 0
|   |   |   |   |--- Fare >  26.14
|   |   |   |   |   |--- Fare <= 134.64
|   |   |   |   |   |   |--- Age <= 27.50
|   |   |   |   |   |   |   |--- Age <= 23.00
|   |   |   |   |   |   |   |   |--- Age <= 17.50
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |--- Age >  17.50
|   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |--- Age >  23.00
|   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |--- Age >  27.50
|   |   |   |   |   |   |   |--- Fare <= 26.42
|   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- Fare >  26.42
|   |   |   |   |   |   |   |   |--- Fare <= 115.44
|   |   |   |   |   |   |   |   |   |--- Age <= 75.00
|   |   |   |   |   |   |   |   |   |   |--- Age <= 60.50
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 10
|   |   |   |   |   |   |   |   |   |   |--- Age >  60.50
|   |   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |--- Age >  75.00
|   |   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |--- Fare >  115.44
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |--- Fare >  134.64
|   |   |   |   |   |   |--- class: 0
|   |   |   |--- Fare >  387.66
|   |   |   |   |--- class: 1
|   |   |--- Pclass >  1.50
|   |   |   |--- Fare <= 51.70
|   |   |   |   |--- Age <= 32.25
|   |   |   |   |   |--- Age <= 31.50
|   |   |   |   |   |   |--- Age <= 13.00
|   |   |   |   |   |   |   |--- SibSp <= 2.50
|   |   |   |   |   |   |   |   |--- SibSp <= 0.50
|   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |--- SibSp >  0.50
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- SibSp >  2.50
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |--- Age >  13.00
|   |   |   |   |   |   |   |--- Fare <= 23.35
|   |   |   |   |   |   |   |   |--- Fare <= 22.89
|   |   |   |   |   |   |   |   |   |--- Age <= 29.35
|   |   |   |   |   |   |   |   |   |   |--- Age <= 28.75
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 13
|   |   |   |   |   |   |   |   |   |   |--- Age >  28.75
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 4
|   |   |   |   |   |   |   |   |   |--- Age >  29.35
|   |   |   |   |   |   |   |   |   |   |--- Age <= 30.50
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 8
|   |   |   |   |   |   |   |   |   |   |--- Age >  30.50
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 2
|   |   |   |   |   |   |   |   |--- Fare >  22.89
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- Fare >  23.35
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |--- Age >  31.50
|   |   |   |   |   |   |--- Fare <= 20.93
|   |   |   |   |   |   |   |--- Fare <= 8.21
|   |   |   |   |   |   |   |   |--- Fare <= 7.99
|   |   |   |   |   |   |   |   |   |--- Fare <= 7.80
|   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |--- Fare >  7.80
|   |   |   |   |   |   |   |   |   |   |--- Fare <= 7.88
|   |   |   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |   |   |--- Fare >  7.88
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 2
|   |   |   |   |   |   |   |   |--- Fare >  7.99
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- Fare >  8.21
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |--- Fare >  20.93
|   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |--- Age >  32.25
|   |   |   |   |   |--- Age <= 61.50
|   |   |   |   |   |   |--- Fare <= 13.25
|   |   |   |   |   |   |   |--- Fare <= 12.76
|   |   |   |   |   |   |   |   |--- Fare <= 7.91
|   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |--- Fare >  7.91
|   |   |   |   |   |   |   |   |   |--- Fare <= 7.99
|   |   |   |   |   |   |   |   |   |   |--- SibSp <= 1.00
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 2
|   |   |   |   |   |   |   |   |   |   |--- SibSp >  1.00
|   |   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |--- Fare >  7.99
|   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |--- Fare >  12.76
|   |   |   |   |   |   |   |   |--- Age <= 45.00
|   |   |   |   |   |   |   |   |   |--- Age <= 40.50
|   |   |   |   |   |   |   |   |   |   |--- Age <= 36.50
|   |   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |   |--- Age >  36.50
|   |   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |--- Age >  40.50
|   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |--- Age >  45.00
|   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |--- Fare >  13.25
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |--- Age >  61.50
|   |   |   |   |   |   |--- Age <= 66.00
|   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |--- Age >  66.00
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |--- Fare >  51.70
|   |   |   |   |--- Fare <= 63.02
|   |   |   |   |   |--- Age <= 30.85
|   |   |   |   |   |   |--- Age <= 27.00
|   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |--- Age >  27.00
|   |   |   |   |   |   |   |--- Age <= 28.85
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |--- Age >  28.85
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |--- Age >  30.85
|   |   |   |   |   |   |--- class: 1
|   |   |   |   |--- Fare >  63.02
|   |   |   |   |   |--- class: 0
|--- Sex >  0.50
|   |--- Pclass <= 2.50
|   |   |--- Age <= 2.50
|   |   |   |--- Fare <= 88.78
|   |   |   |   |--- class: 1
|   |   |   |--- Fare >  88.78
|   |   |   |   |--- class: 0
|   |   |--- Age >  2.50
|   |   |   |--- Age <= 27.50
|   |   |   |   |--- Age <= 24.50
|   |   |   |   |   |--- Fare <= 13.40
|   |   |   |   |   |   |--- Fare <= 12.50
|   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |--- Fare >  12.50
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |--- Fare >  13.40
|   |   |   |   |   |   |--- class: 1
|   |   |   |   |--- Age >  24.50
|   |   |   |   |   |--- Fare <= 90.78
|   |   |   |   |   |   |--- Fare <= 17.43
|   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |--- Fare >  17.43
|   |   |   |   |   |   |   |--- Age <= 26.00
|   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- Age >  26.00
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |--- Fare >  90.78
|   |   |   |   |   |   |--- class: 0
|   |   |   |--- Age >  27.50
|   |   |   |   |--- Age <= 49.50
|   |   |   |   |   |--- class: 1
|   |   |   |   |--- Age >  49.50
|   |   |   |   |   |--- Age <= 50.50
|   |   |   |   |   |   |--- Fare <= 27.36
|   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |--- Fare >  27.36
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |--- Age >  50.50
|   |   |   |   |   |   |--- class: 1
|   |--- Pclass >  2.50
|   |   |--- Fare <= 23.35
|   |   |   |--- Fare <= 15.37
|   |   |   |   |--- Fare <= 8.04
|   |   |   |   |   |--- Fare <= 7.74
|   |   |   |   |   |   |--- Fare <= 6.99
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |--- Fare >  6.99
|   |   |   |   |   |   |   |--- Fare <= 7.59
|   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- Fare >  7.59
|   |   |   |   |   |   |   |   |--- Fare <= 7.64
|   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |--- Fare >  7.64
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |--- Fare >  7.74
|   |   |   |   |   |   |--- Age <= 25.50
|   |   |   |   |   |   |   |--- Age <= 22.50
|   |   |   |   |   |   |   |   |--- Age <= 21.50
|   |   |   |   |   |   |   |   |   |--- Fare <= 7.89
|   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |--- Fare >  7.89
|   |   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |--- Age >  21.50
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- Age >  22.50
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |--- Age >  25.50
|   |   |   |   |   |   |   |--- Age <= 37.35
|   |   |   |   |   |   |   |   |--- Age <= 27.50
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |--- Age >  27.50
|   |   |   |   |   |   |   |   |   |--- Age <= 28.85
|   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |--- Age >  28.85
|   |   |   |   |   |   |   |   |   |   |--- Fare <= 7.81
|   |   |   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |   |   |--- Fare >  7.81
|   |   |   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- Age >  37.35
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |--- Fare >  8.04
|   |   |   |   |   |--- Age <= 9.25
|   |   |   |   |   |   |--- Fare <= 10.80
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |--- Fare >  10.80
|   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |--- Age >  9.25
|   |   |   |   |   |   |--- SibSp <= 0.50
|   |   |   |   |   |   |   |--- Fare <= 8.67
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |--- Fare >  8.67
|   |   |   |   |   |   |   |   |--- Age <= 25.50
|   |   |   |   |   |   |   |   |   |--- Age <= 20.00
|   |   |   |   |   |   |   |   |   |   |--- Fare <= 12.15
|   |   |   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |   |   |--- Fare >  12.15
|   |   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |--- Age >  20.00
|   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |--- Age >  25.50
|   |   |   |   |   |   |   |   |   |--- Age <= 29.35
|   |   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |   |--- Age >  29.35
|   |   |   |   |   |   |   |   |   |   |--- Age <= 29.85
|   |   |   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |   |   |   |--- Age >  29.85
|   |   |   |   |   |   |   |   |   |   |   |--- truncated branch of depth 3
|   |   |   |   |   |   |--- SibSp >  0.50
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |--- Fare >  15.37
|   |   |   |   |--- Age <= 29.35
|   |   |   |   |   |--- Age <= 25.00
|   |   |   |   |   |   |--- SibSp <= 2.50
|   |   |   |   |   |   |   |--- SibSp <= 1.50
|   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |--- SibSp >  1.50
|   |   |   |   |   |   |   |   |--- Age <= 9.38
|   |   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |   |   |--- Age >  9.38
|   |   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |--- SibSp >  2.50
|   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |--- Age >  25.00
|   |   |   |   |   |   |--- class: 0
|   |   |   |   |--- Age >  29.35
|   |   |   |   |   |--- Age <= 30.35
|   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |--- Age >  30.35
|   |   |   |   |   |   |--- Age <= 32.00
|   |   |   |   |   |   |   |--- Fare <= 19.26
|   |   |   |   |   |   |   |   |--- class: 0
|   |   |   |   |   |   |   |--- Fare >  19.26
|   |   |   |   |   |   |   |   |--- class: 1
|   |   |   |   |   |   |--- Age >  32.00
|   |   |   |   |   |   |   |--- class: 1
|   |   |--- Fare >  23.35
|   |   |   |--- Age <= 5.50
|   |   |   |   |--- Age <= 3.50
|   |   |   |   |   |--- class: 0
|   |   |   |   |--- Age >  3.50
|   |   |   |   |   |--- class: 1
|   |   |   |--- Age >  5.50
|   |   |   |   |--- class: 0

Challenge: Test Yourself!#

Try making your own passenger. Change values for class, sex, age, siblings, or fare. Predict if your passenger survives.

What happens if you change the age or class? Try with your friends!

Recap: What We Learned#

Python lets us work with real-world data and make predictions. We learned about variables, lists, dictionaries, and working with data tables. Our model uses clues from the data to guess if someone survived. Practice helps you get better at these skills!

Thank You & Next Steps#

Thanks for learning Python and Titanic prediction with us. Remember, trying things out is the best way to learn. Keep practicing and you will be coding faster each time.

If you want more lessons, please subscribe to our channel and click the bell to get updates.

See you next time!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.