# Titanic and Iris Case Studies

The canonical teaching datasets, small and clean enough to make a full modelling workflow visible end to end.

**Rests on:** Two-Class and Multiclass Classifiers

*Machine Learning · Machine Learning Foundations*


## Why learn this

Before you can build any artificial intelligence system, you must see the entire workflow once, end to end, with data small enough to hold in your head. The Titanic and Iris datasets are exactly that: two classic examples that let you run the whole process — loading data, cleaning it, splitting it, training a model, and evaluating it — all on a single screen. Master this and you are ready for the next steps in your Machine Learning Foundations. These datasets are the training ground; the skills you learn here transfer directly to the messy data you will meet in practice, such as predicting which customers will leave (Churn Prediction) or identifying diseases in crops.


## The intuition

Imagine you have never cooked a dish before. You would not start with a complex ten-ingredient recipe; you would practice with something simple, like dal or scrambled eggs, to learn the basic techniques — chopping, boiling, seasoning — without the chaos of a full kitchen. Titanic and Iris are the dal and scrambled eggs of machine learning. They are small, clean, and simple enough that you can see every step of the cooking process. 

Titanic gives you a list of passengers (with details like age, sex, ticket class, and whether they survived) and asks you to predict survival. Iris gives you measurements of flower petals and sepals and asks you to identify the species. The goal is not to achieve world-record accuracy on these particular datasets; it is to see how the entire machine learning workflow fits together, from raw data to final prediction, in a way you can follow line by line. Once you have done that, you can handle real-world data that is messier, larger, and more ambiguous.


## An analogy

Think of a recipe book. It starts with a simple recipe, say, boiling an egg, to teach you the basics of boiling. Then it moves to scrambled eggs, then omelette, and only later to a full biryani. Titanic and Iris are the 'boiling an egg' of machine learning. They are deliberately simple so that the technique is visible. Just as boiling an egg teaches you about heat and timing without the complexity of multiple ingredients, Titanic teaches you about predicting one of two possible outcomes (survive or not) without the complexity of a thousand features. Iris teaches you about predicting one of three possible categories with just four numerical measurements. But here is where the analogy breaks down: a recipe book is a fixed sequence, whereas in machine learning you can skip steps and come back.


## Definition

Titanic and Iris are two small, canonical datasets used to teach the complete machine learning workflow — from loading and cleaning data, to splitting into training and test sets, to training a model and evaluating it — because every step can be inspected and understood in a few minutes.


## How it connects

You are starting your Machine Learning Foundations with no prior exposure. This concept sits at the very beginning, before you meet any specific algorithm. However, it lays the groundwork for everything that follows: Linear Regression (which predicts continuous values like house prices) and Logistic Regression (which predicts one of two possible outcomes like churn or survival). The train-validate-test discipline you learn here is the backbone of all supervised learning (predicting a known answer from labeled examples), and the bias-variance tradeoff you will study later is directly visible when you see a model that does too well on training data but poorly on new data.


## The mathematics

The mathematics behind these case studies is not complex calculus or matrix algebra; it is arithmetic and simple counting. The branch of mathematics this concept draws on is statistics, specifically descriptive statistics and basic probability. Why statistics? Because machine learning is about making decisions under uncertainty, and statistics gives us the tools to measure and handle that uncertainty. For Titanic, we are predicting a binary outcome (survived or not). For Iris, we are predicting one of three categories (species). The key operations are counting, averaging, and comparing proportions. For example, to evaluate a model, we count how many predictions were correct and divide by the total to get accuracy. To understand the data, we calculate means (averages) of features like age or petal length. To find a simple rule, we might look at the proportion of passengers who survived given they were female versus male. These are all operations you can do by hand with a pencil, and they are the foundation of the more advanced mathematics you will meet later (like the dot product and derivatives in neural networks). But here, we stay with arithmetic, so that you can see the entire workflow without getting lost in symbols.

To make this concrete, let us define what we are measuring. Suppose we have a dataset with n passengers. The letter n stands for the total number of people in our list. For each person i (where i is just an index to identify them: 1st person, 2nd person, etc.), let x_i be the age of passenger i. The notation x_i, read 'x sub i', means the value of the variable x for the i-th individual. Let y_i be their survival status, coded as 1 if they survived and 0 if they did not.

The average age is calculated by adding up all the ages and dividing by the number of people. In symbols, this is written as the sum of all x_i divided by n. We denote this average as x-bar (x̄). The survival rate is calculated similarly: we add up all the survival statuses (which effectively counts the number of survivors since only 1s contribute to the sum) and divide by n. This gives us the proportion of people who survived.

Later, when you build a model, you will use similar arithmetic to compute accuracy: (number of correct predictions) / (total predictions). These are simple descriptive statistics.


## A worked example

Let's take Titanic. We have a small subset of 5 passengers. Their names, ages, and survival status (1 = survived, 0 = died) are as follows: Passenger A (age 30, survived=1), Passenger B (age 40, survived=0), Passenger C (age 20, survived=1), Passenger D (age 60, survived=0), Passenger E (age 10, survived=0). We want to calculate the average age and the survival rate.

Step 1: Sum of ages. We add the age of each passenger together. 
30 + 40 + 20 + 60 + 10 = 160.
This sum represents the total years lived by this group.

Step 2: Average age. We divide the sum of ages by the number of passengers. There are n = 5 passengers.
160 / 5 = 32.
The average age is 32 years.

Step 3: Count survivors. We look at the survival status y_i for each passenger. 
Passenger A: 1 (survived)
Passenger B: 0 (died)
Passenger C: 1 (survived)
Passenger D: 0 (died)
Passenger E: 0 (died)
We add these values: 1 + 0 + 1 + 0 + 0 = 2.
There are 2 survivors.

Step 4: Survival rate. We divide the number of survivors by the total number of passengers.
2 / 5 = 0.4.
To express this as a percentage, we multiply by 100: 0.4 * 100 = 40%.

Result: The average age of these 5 passengers is 32 years, and the survival rate is 40%.


## From scratch, in Python

```python
# We'll use Python's built-in data structures: lists and dictionaries.
# A list is an ordered collection, e.g., [1, 2, 3].
# A dictionary is a collection of key-value pairs, e.g., {'name': 'Alice'}.

# Titanic data: a list of dictionaries, each representing a passenger.
passengers = [
    {'name': 'A', 'age': 30, 'survived': 1},
    {'name': 'B', 'age': 40, 'survived': 0},
    {'name': 'C', 'age': 20, 'survived': 1},
    {'name': 'D', 'age': 60, 'survived': 0},
    {'name': 'E', 'age': 10, 'survived': 0}
]

# Calculate average age.
total_age = 0
for p in passengers:
    total_age = total_age + p['age']
average_age = total_age / len(passengers)
print('Average age:', average_age)

# Calculate survival rate.
total_survived = 0
for p in passengers:
    total_survived = total_survived + p['survived']
survival_rate = total_survived / len(passengers)
print('Survival rate:', survival_rate)
```


## The same thing, with a framework

In practice, you would use a library like pandas (for data manipulation) and scikit-learn (for machine learning). Here is a glimpse:

```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

# Load Iris dataset
df = pd.read_csv('iris.csv')
X = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]
y = df['species']

# Split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train a decision tree
model = DecisionTreeClassifier()
model.fit(X_train, y_train)

# Evaluate
accuracy = model.score(X_test, y_test)
print('Accuracy:', accuracy)
```

Under the hood, pandas is doing the same list-of-dictionaries but optimised for tabular data. train_test_split shuffles and splits the data into two parts. The decision tree fits a model to the training data. The score method computes the accuracy on the test data. All the arithmetic is exactly the counting and division you did by hand.


## What the code does

We start with a list of dictionaries. Each dictionary represents one passenger with three keys: 'name', 'age', and 'survived'. We use a for loop to iterate over each passenger. The variable 'p' takes each dictionary in turn. To get the age, we use p['age']. We add it to a running total 'total_age'. After the loop, we divide by len(passengers), which is 5, to get the average. Similarly, we sum the 'survived' values (1 or 0) and divide to get the proportion. This is the essence of data handling: store data in structured containers, loop over them, and aggregate numbers.


## Common misconceptions

**The goal is the highest accuracy on these datasets** — If I get 99% accuracy on Titanic or Iris, I'm a great data scientist.

These datasets are small and clean. High accuracy on them does not prove you can handle real-world messy data. In fact, Iris is so nearly separable that even simple methods do well, so high accuracy tells you little about the model's quality. In fact: The point of these datasets is to learn the workflow, not to achieve a record. Focus on understanding each step, and remember that real data will challenge you far more.

**Real data is like this** — All datasets look like Titanic and Iris — neatly organised, with clear labels.

Real data often has missing values, irrelevant columns, inconsistent formats, and noise. The Titanic dataset has been cleaned and curated; your own data will not be. In fact: Treat these as pedagogical toys. As your notes say, 'Real data is never this cooperative.' Always expect to spend time cleaning and preparing data.

**A single split is enough** — I split the data once into train and test, and that's the final word on my model's performance.

A single split can give a lucky (or unlucky) result. Using cross-validation (multiple splits) gives a more reliable estimate. The train-validate-test discipline is more nuanced than one split. In fact: Learn to use multiple splits (e.g., k-fold cross-validation) to get a stable estimate of performance.

**A model that works on Iris will work on any data** — Since my model got 95% on Iris, it will also get 95% on my client's data.

Iris is nearly linearly separable by some features. Real problems are rarely that easy. The model's assumptions (e.g., linear boundaries) may not hold elsewhere. In fact: Always evaluate on data similar to your target problem. Transferring performance across datasets is not valid.


## In short

Titanic and Iris are teaching datasets that let you see the entire machine learning workflow end to end. You learn to load data, compute simple statistics (average, survival rate), split into train/test, train a model, and evaluate accuracy. The mathematics is basic arithmetic and counting. The code uses lists and dictionaries in Python. Real-world applications use the same pipeline, but real data is messier. Remember: these datasets are for learning, not for bragging rights, and victory on them does not guarantee victory on real problems.


## Where this is used

These two datasets are not used directly in production AI systems, but they are the gateway to every real-world application. The workflow you learn here — data cleaning, splitting, training, evaluating — is exactly what a developer does when building a recommendation system, a fraud detector, or a model inside a large language model pipeline. For example, in large language models like ChatGPT, before the neural network is trained, the data is organised into structured pairs (input text, output text) similar to how Titanic pairs features with labels. The train-validation-test split is used to ensure the model generalises, not just memorises. In small language models that run on phones, the same discipline applies to smaller datasets. In retrieval-augmented generation (RAG), you might use Iris-like data to test a classification component that routes queries. In agentic systems that plan and call tools, you might use a simple model trained on a small dataset to decide which tool to call. In everyday applied machine learning, whether it is predicting customer churn, detecting crop disease from images, or forecasting sales, the same pipeline holds. A developer writes code that loads a CSV, cleans it (handling missing values, encoding categories), splits it, trains a model, and evaluates accuracy. What breaks when done badly? If you forget to split the data, your model will appear perfect on training data but fail on new data (a classic bias-variance tradeoff mistake). If you use a dataset that is not representative (like Iris, which is nearly separable), your model may be flattered and you will think it is better than it is. This is why your notes emphasize that Iris 'flatters weak methods.'


---

Read this on the web: https://basavapurushottam.com/learn-ai/titanic-and-iris-case-studies
