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…
- CoursePython For Machine Learning
- Lesson14 of 16
- Video11 min
- FormatJupyter notebook · 21 code cells
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!")
# 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)
# Strings hold text or words, while integers store numbers.
favorite_color = input("What is your favorite color? ")
print("You chose", favorite_color)
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)
# A dictionary for a Titanic passenger
passenger1 = {"name": "Eva", "age": 11, "survived": True}
print(passenger1)
# 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()
# What does the data contain?
print(df.columns.tolist())
print("Survived counts:")
print(df['Survived'].value_counts())
# Picking important features for prediction
features = ["Pclass", "Sex", "Age", "SibSp", "Fare"]
target = "Survived"
data = df[features + [target]].copy()
data.head()
# Checking for missing values
print(data.isnull().sum())
# 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())
# 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)
# Test the model and see how well it predicts survivors
score = model.score(X_test, y_test)
print("Accuracy:", score)
# 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.")
# Try a feature: importance for the model
print(pd.Series(model.feature_importances_, index=features))
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)
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.



