Skip to main content
LearnMLAcademy
All project handbooks
FREE COMPLETE PROJECTBeginnerSelf-paced • save checkpoints

Can You Survive the Titanic? Build a Machine Learning Predictor

Start with an empty folder. Inspect the real Titanic training table, build a leakage-safe preprocessing pipeline, compare five classifiers with cross-validation, tune the winner, evaluate once on an untouched test set, save the complete pipeline and use it inside a Streamlit browser application.

The practical problem: can historical passenger details help us predict survival?

Imagine you are given a table of Titanic passengers. For every row, you know the passenger's ticket class, recorded sex, age, family counts, fare and boarding port, and you also know the historical outcome: Survived = 1 or Did not survive = 0. Your job is to build a classifier that learns statistical patterns from the known rows and then accepts a new seven-field passenger profile.

The difficult part is not simply calling RandomForestClassifier.fit(). The data contains missing values, text categories and features measured on different scales. We must prevent the final test passengers from influencing preprocessing, compare several model families fairly, choose a useful metric, tune only with training data, and finally package the exact fitted preprocessing + model into an application.

1 · Understand

Inspect 891 historical rows and identify the target, missing values and visible survival patterns.

2 · Learn safely

Lock away 179 passengers, then learn imputation, encoding, scaling and model parameters only from training rows.

3 · Prove it

Compare five classifiers with training-only cross-validation, tune the winner, then use the holdout exactly once.

4 · Deliver

Save the complete fitted pipeline and connect it to a Streamlit form that predicts one hypothetical passenger profile.

Passenger table
→
80/20 split
→
Preprocessing pipeline
→
5-model CV
→
Tune winner
→
Final holdout
→
Saved pipeline
→
Streamlit app

See the learning problem before writing the model

A classifier needs useful patterns, not magic. The verified chart below uses only the 712 training rows and asks a simple question: how did survival rate differ across recorded sex and ticket class? The bars are visibly different. That is exactly the kind of relationship a classifier can learn from multiple features at the same time.

Training-only visual intuition: survival rate by sex and class

Training-only Titanic survival-rate bar chart grouped by recorded sex and ticket class
Generated only from training rows after the split. We use it to understand the problem without allowing the final 179-passenger holdout to guide model choices.
Open original-size screenshot (opens in a new tab)

The chart shows association in this historical dataset; it does not prove that any one field caused an individual's outcome. Later, the model combines seven fields and we evaluate how well those learned associations generalize to unseen rows.

What you will build

A real classification project and browser app. A user enters seven passenger fields and the saved model returns a predicted class plus a model survival estimate. The app uses the exact preprocessing learned during training.

Tools you will actually use

PythonVS CodeJupyterLabPandasNumPyMatplotlibScikit-learnJoblibStreamlitGitGitHubKaggle

Verified reference result

Winner

Random Forest

Accuracy

81.01%

Precision

81.82%

Recall

65.22%

F1

0.7258

These numbers came from the executed project: 712 training rows, 179 untouched final-test rows, five training-only cross-validation folds and a fixed random seed of 42. The final confusion matrix was [[100, 10], [24, 45]].

How the whole system fits together

Training: Kaggle train.csv → notebook inspection → 80/20 stratified split → preprocessing pipeline → five-model cross-validation → Random Forest tuning → one final holdout evaluation → saved Joblib pipeline.
Prediction: Streamlit form → one seven-field DataFrame → saved preprocessing pipeline → Random Forest → predicted class + model probability → browser result.

Training and prediction are separate jobs. The app never learns a new median, encoder or model from the person using it. It only loads the trusted pipeline that was already trained.

Step 1: Install Python on Windows

What: Python runs the notebook, training program, tests and Streamlit app.

Why: Every later command depends on the Python interpreter and its package manager.

Do this

  1. Browser

    Open your browser and go to the official Python downloads page.
  2. Install a current 64-bit Python 3 release. The verified build used Python 3.13.16.
  3. If the installer offers command-line/PATH integration, enable it.
  4. Open Start → type PowerShell → open it.
  5. Run python --version.
    You should see: A Python 3 version, not “command not found”.
Verify PythonpowershellRunnable
python --version

Check before continuing

PowerShell prints Python 3.13.x when you run python --version.

Step 2: Install VS Code and the Python extension

What: VS Code will hold the folders, Python files and terminal used in the project.

Why: Keeping all project files under one visible folder makes it easier to understand what each file does.

Do this

  1. Download and install Visual Studio Code from its official website.
  2. Open VS Code and click the Extensions icon in the left activity bar.
  3. Search Python, choose the extension published by Microsoft and click Install.

Check before continuing

VS Code opens and the Microsoft Python extension shows as installed.

Step 3: Create the project folder structure

What: We separate source code, raw data, generated models, notebook work, outputs and tests.

Why: A clear structure teaches which files are inputs, which are source code and which are generated artifacts.

Do this

  1. In VS Code choose File → Open Folder... and create/open titanic-survival-predictor.
  2. Choose Terminal → New Terminal.
  3. Run the folder commands below only if you have not already created the folders in Explorer.
Create the folderspowershellRunnable
mkdir titanic-survival-predictor
cd titanic-survival-predictor
mkdir data
mkdir models
mkdir notebooks
mkdir outputs
mkdir src
mkdir tests
Checkpoint folder treetextOutput
titanic-survival-predictor/
├── data/
├── models/
├── notebooks/
├── outputs/
├── src/
├── tests/
├── app.py
├── requirements.txt
└── .gitignore

Check before continuing

Explorer shows data, models, notebooks, outputs, src and tests.

Step 4: Create a private Python environment and install exact packages

What: A virtual environment gives this project its own package versions.

Why: It prevents another Python project on your laptop from silently changing this project's behavior.

Create requirements.txt at the project root, paste the exact verified dependencies below and save it.

requirements.txttextConfiguration
# Tested together on Windows x64 with Python 3.13.16.
pandas==3.0.6
numpy==2.5.3
scikit-learn==1.9.1
matplotlib==3.11.2
joblib==1.6.0
streamlit==1.65.0
jupyterlab==4.6.4
nbclient==0.11.0
Create .venv and install packagespowershellRunnable
py -3.13 -m venv .venv
.\.venv\Scripts\Activate.ps1
python --version
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip check

If PowerShell blocks activation, you can run the environment's Python directly rather than weakening machine-wide security settings.

Check before continuing

The terminal starts with (.venv), python --version works and pip check reports no broken requirements.

Step 5: Download the Titanic training data from Kaggle

What: The project uses Kaggle's Titanic competition training table as the learner dataset.

Why: train.csv contains both passenger information and the known Survived label needed for supervised learning.

Do this

  1. Open the Kaggle Titanic competition Data page in your browser.
  2. Sign in yourself and accept/review any competition rules Kaggle requires.
  3. Download the competition files and extract them.
  4. Copy only train.csv into this project's data folder.
    You should see: Explorer shows data/train.csv.

Where the learner gets the Titanic files

Kaggle Titanic data page captured while preparing the project
Real Kaggle page evidence captured during project preparation. Kaggle sign-in/rule acceptance is personal; the handbook does not fake that step.
Open original-size screenshot (opens in a new tab)

The verified engineering run used a disclosed public mirror because its automation environment was not signed in to Kaggle. CI reproduces that exact recorded file by hash; the learner path remains Kaggle.

Check before continuing

The project contains data/train.csv with 891 rows, 12 columns and a Survived column.

Step 6: Open JupyterLab and inspect the first rows

What: We inspect the raw table before training anything.

Why: A model should never be built from a dataset whose shape, columns and missing values you have not checked.

Do this

  1. Run python -m jupyterlab from the activated project terminal.
  2. In the browser file list open notebooks/01_titanic_exploration.ipynb.
  3. Run cells with Shift+Enter. Save with Ctrl+S.
Load the CSVpythonRunnable
from pathlib import Path
import pandas as pd

ROOT = Path.cwd()
if ROOT.name == "notebooks":
    ROOT = ROOT.parent

df = pd.read_csv(ROOT / "data" / "train.csv")
df.head()

Check before continuing

The notebook shows the first five passengers and columns including Pclass, Sex, Age, Fare and Survived.

Step 7: Measure shape, missing values and the target

What: We quantify what is missing and whether the two classes are balanced.

Why: Missing values determine preprocessing. Class counts influence which evaluation metrics deserve attention.

Inspect schema, missingness and targetpythonRunnable
print("Rows, columns:", df.shape)
print("Columns:", ", ".join(df.columns))
df.info()

df.isna().sum().to_frame("Missing values")

df["Survived"].value_counts().sort_index().to_frame("Passengers")
Verified notebook checkpointstextOutput
Rows, columns: (891, 12)
Age missing: 177
Cabin missing: 687
Embarked missing: 2
Survived=0: 549
Survived=1: 342

Check before continuing

You can explain 891×12, Age=177 missing, Cabin=687 missing, Embarked=2 missing, and target counts 549 vs 342.

Step 8: Choose seven features and lock away the final test set

What: Inputs are Pclass, Sex, Age, SibSp, Parch, Fare, Embarked; the target is Survived.

Why: The target must never appear among the features. We also split before learning imputation/scaling/encoding so the final test set cannot influence preprocessing.

Create the stratified 80/20 splitpythonRunnable
from sklearn.model_selection import train_test_split

features = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
X = df[features]
y = df["Survived"]

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.20,
    random_state=42,
    stratify=y,
)

print("Training:", X_train.shape, "Final test:", X_test.shape)
print("Training survival rate:", round(y_train.mean(), 4))
print("Final test survival rate:", round(y_test.mean(), 4))
print("Disjoint row indexes:", set(X_train.index).isdisjoint(X_test.index))
Verified split outputtextOutput
Training: (712, 7) Final test: (179, 7)
Training survival rate: 0.3834
Final test survival rate: 0.3855
Disjoint row indexes: True

Now look for a pattern before training: run this small training-only group calculation. It tells you the percentage surviving for each recorded sex/ticket-class combination.

Training-only survival patternpythonRunnable
eda = X_train.copy()
eda["Survived"] = y_train

rates = (
    eda.groupby(["Sex", "Pclass"])["Survived"]
       .mean()
       .mul(100)
       .round(1)
)
print(rates)

Training-only exploratory chart

Real bar chart of Titanic survival rate by ticket class using training rows only
Generated from the 712 training rows after the split. We can explore patterns here without using the final 179-row holdout to guide modeling decisions.
Open original-size screenshot (opens in a new tab)

Check before continuing

Training is 712×7, final test is 179×7, the row indexes do not overlap, and both survival rates are about 38%.

Step 9: Build train_model.py in four understandable pieces

What: Instead of starting with a wall of code, build the training logic mentally in four connected blocks.

Why: Each block solves one problem. If you understand those problems first, the final file becomes a readable assembly rather than something to copy blindly.

Part A — turn messy columns into model-ready numbers

Numeric columns get median imputation and scaling. Categorical columns get most-frequent imputation and one-hot encoding. The two branches are joined by ColumnTransformer.

A · make_preprocessor()pythonRunnable
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

NUMERIC = ["Age", "SibSp", "Parch", "Fare"]
CATEGORICAL = ["Pclass", "Sex", "Embarked"]

def make_preprocessor():
    numeric_steps = Pipeline([
        ("fill_missing", SimpleImputer(strategy="median")),
        ("scale", StandardScaler()),
    ])
    categorical_steps = Pipeline([
        ("fill_missing", SimpleImputer(strategy="most_frequent")),
        ("encode", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
    ])
    return ColumnTransformer([
        ("numbers", numeric_steps, NUMERIC),
        ("categories", categorical_steps, CATEGORICAL),
    ])

Part B — define fair model candidates

Every candidate is wrapped around the same preprocessing. That means Logistic Regression, KNN, SVM, Decision Tree and Random Forest are compared on the same input preparation.

B · candidates + pipelinepythonRunnable
def make_candidates():
    return {
        "Logistic Regression": LogisticRegression(max_iter=1000, random_state=SEED),
        "K-Nearest Neighbors": KNeighborsClassifier(n_neighbors=7),
        "Support Vector Machine": SVC(C=1.0, kernel="rbf", random_state=SEED),
        "Decision Tree": DecisionTreeClassifier(max_depth=5, random_state=SEED),
        "Random Forest": RandomForestClassifier(
            n_estimators=200,
            min_samples_leaf=2,
            random_state=SEED,
        ),
    }

def make_pipeline(model):
    return Pipeline([
        ("prepare", make_preprocessor()),
        ("model", clone(model)),
    ])

Part C — compare with repeated training-only evidence

Five-fold stratified cross-validation repeatedly changes which training rows act as validation rows. We rank model families by mean F1 instead of one lucky split.

C · compare_models()pythonRunnable
def compare_models(X_train, y_train):
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
    rows = []

    for name, model in make_candidates().items():
        scores = cross_validate(
            make_pipeline(model),
            X_train,
            y_train,
            cv=cv,
            scoring=SCORING,
            error_score="raise",
        )
        rows.append({
            "model": name,
            "f1": float(scores["test_f1"].mean()),
            "f1_std": float(scores["test_f1"].std()),
        })

    return pd.DataFrame(rows).sort_values("f1", ascending=False)

Part D — tune the winner, still without the holdout

GridSearchCV changes settings of the winning family inside training folds. Only after this search finishes do we evaluate once on the untouched test passengers.

D · tuning patternpythonRunnable
grids = {
    "Random Forest": {
        "model__max_depth": [5, 8, None],
        "model__min_samples_leaf": [1, 2, 4],
    },
}

search = GridSearchCV(
    make_pipeline(make_candidates()["Random Forest"]),
    grids["Random Forest"],
    scoring=SCORING,
    refit="f1",
    cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED),
)
search.fit(X_train, y_train)
Open the complete verified train_model.py when you are ready to assemble the file

The full source below is still copyable, but it comes after the architecture. Read the four blocks above first, then use this as the final assembled version.

Complete src/train_model.pypythonRunnable
"""Train the Titanic pipeline from the project root: python src/train_model.py."""

# handbook: imports
from pathlib import Path
import json
import platform
import hashlib
import joblib
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate, GridSearchCV
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    confusion_matrix, ConfusionMatrixDisplay, make_scorer,
)

# handbook: data
ROOT = Path(__file__).resolve().parents[1]
FEATURES = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']
NUMERIC = ['Age', 'SibSp', 'Parch', 'Fare']
CATEGORICAL = ['Pclass', 'Sex', 'Embarked']
SEED = 42


def load_and_split():
    data_path = ROOT / 'data' / 'train.csv'
    if not data_path.is_file():
        raise FileNotFoundError('Put Kaggle Titanic train.csv inside the data folder first.')
    df = pd.read_csv(data_path)
    required = set(FEATURES + ['Survived'])
    if not required.issubset(df.columns):
        raise ValueError('Wrong CSV: train.csv must include the features and Survived.')
    if len(df) != 891 or df.shape[1] != 12:
        raise ValueError('This handbook expects the original 891-row, 12-column train.csv.')
    if df['Survived'].isna().any() or set(df['Survived'].unique()) != {0, 1}:
        raise ValueError('Survived must contain only the known labels 0 and 1.')
    X = df[FEATURES]
    y = df['Survived']
    return train_test_split(X, y, test_size=0.2, stratify=y, random_state=SEED)


# handbook: numeric
def make_preprocessor():
    numeric_steps = Pipeline([
        ('fill_missing', SimpleImputer(strategy='median')),
        ('scale', StandardScaler()),
    ])
    # handbook: categorical
    categorical_steps = Pipeline([
        ('fill_missing', SimpleImputer(strategy='most_frequent')),
        ('encode', OneHotEncoder(handle_unknown='ignore', sparse_output=False)),
    ])
    # handbook: combine
    return ColumnTransformer([
        ('numbers', numeric_steps, NUMERIC),
        ('categories', categorical_steps, CATEGORICAL),
    ])


# handbook: models
def make_candidates():
    return {
        'Logistic Regression': LogisticRegression(max_iter=1000, random_state=SEED),
        'K-Nearest Neighbors': KNeighborsClassifier(n_neighbors=7),
        'Support Vector Machine': SVC(C=1.0, kernel='rbf', random_state=SEED),
        'Decision Tree': DecisionTreeClassifier(max_depth=5, random_state=SEED),
        'Random Forest': RandomForestClassifier(n_estimators=200, min_samples_leaf=2, random_state=SEED),
    }


def make_pipeline(model):
    return Pipeline([('prepare', make_preprocessor()), ('model', clone(model))])


# handbook: compare
SCORING = {
    'accuracy': 'accuracy',
    'precision': make_scorer(precision_score, zero_division=0),
    'recall': make_scorer(recall_score, zero_division=0),
    'f1': make_scorer(f1_score, zero_division=0),
}


def compare_models(X_train, y_train):
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
    rows = []
    for name, model in make_candidates().items():
        print(f'Comparing {name} ...', flush=True)
        scores = cross_validate(
            make_pipeline(model), X_train, y_train,
            cv=cv, scoring=SCORING, error_score='raise',
        )
        row = {'model': name}
        for metric in SCORING:
            row[metric] = float(scores[f'test_{metric}'].mean())
        row['f1_std'] = float(scores['test_f1'].std())
        rows.append(row)
    comparison = pd.DataFrame(rows).sort_values('f1', ascending=False, kind='stable')
    comparison.to_csv(ROOT / 'outputs' / 'model_comparison.csv', index=False)
    print(comparison.to_string(index=False, float_format=lambda value: f'{value:.4f}'))
    return comparison


# handbook: tune
def tune_winner(name, X_train, y_train):
    grids = {
        'Logistic Regression': {'model__C': [0.1, 1.0, 10.0]},
        'K-Nearest Neighbors': {'model__n_neighbors': [5, 7, 11], 'model__weights': ['uniform', 'distance']},
        'Support Vector Machine': {'model__C': [0.5, 1.0, 3.0], 'model__gamma': ['scale', 0.1]},
        'Decision Tree': {'model__max_depth': [3, 5, 8], 'model__min_samples_leaf': [1, 4]},
        'Random Forest': {'model__max_depth': [5, 8, None], 'model__min_samples_leaf': [1, 2, 4]},
    }
    search = GridSearchCV(
        make_pipeline(make_candidates()[name]), grids[name],
        scoring=SCORING, refit='f1',
        cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED),
        error_score='raise',
    )
    search.fit(X_train, y_train)
    pd.DataFrame(search.cv_results_).to_csv(ROOT / 'outputs' / 'tuning_results.csv', index=False)
    print('Selected by mean CV F1:', name)
    print('Best settings:', search.best_params_)
    print(f'Best tuning CV F1: {search.best_score_:.4f}')
    return search


# handbook: evaluate
def evaluate_final(pipeline, X_test, y_test):
    predictions = pipeline.predict(X_test)
    metrics = {
        'accuracy': accuracy_score(y_test, predictions),
        'precision': precision_score(y_test, predictions, zero_division=0),
        'recall': recall_score(y_test, predictions, zero_division=0),
        'f1': f1_score(y_test, predictions, zero_division=0),
    }
    matrix = confusion_matrix(y_test, predictions, labels=[0, 1])
    print('Final held-out test (179 passengers):')
    for name, value in metrics.items():
        print(f'  {name}: {value:.4f}')
    print('Confusion matrix (rows actual, columns predicted; order 0, 1):')
    print(matrix)
    fig, ax = plt.subplots(figsize=(7, 5))
    ConfusionMatrixDisplay(matrix, display_labels=['Did not survive (0)', 'Survived (1)']).plot(
        ax=ax, cmap='Blues', colorbar=False, values_format='d',
    )
    ax.set_title('Final held-out test: 179 passengers')
    fig.tight_layout()
    fig.savefig(ROOT / 'outputs' / 'confusion_matrix.png', dpi=160)
    plt.close(fig)
    return metrics, matrix.tolist()


# handbook: save
def save_and_reload(pipeline):
    model_path = ROOT / 'models' / 'titanic_pipeline.joblib'
    model_path.parent.mkdir(exist_ok=True)
    joblib.dump(pipeline, model_path)
    # Only load a file you made or trust. joblib is not a safe format for strangers' files.
    reloaded = joblib.load(model_path)
    examples = pd.DataFrame([
        {'Pclass': 1, 'Sex': 'female', 'Age': 29.0, 'SibSp': 0, 'Parch': 0, 'Fare': 80.0, 'Embarked': 'S'},
        {'Pclass': 3, 'Sex': 'male', 'Age': 35.0, 'SibSp': 0, 'Parch': 0, 'Fare': 8.0, 'Embarked': 'S'},
    ])[FEATURES]
    before = pipeline.predict(examples)
    after = reloaded.predict(examples)
    assert (before == after).all(), 'Saved and reloaded predictions differ.'
    examples['prediction'] = after
    if hasattr(reloaded, 'predict_proba'):
        positive_index = list(reloaded.classes_).index(1)
        examples['survival_probability'] = reloaded.predict_proba(examples.drop(columns='prediction'))[:, positive_index]
    examples.to_csv(ROOT / 'outputs' / 'example_predictions.csv', index=False)
    print('Saved and reloaded: models/titanic_pipeline.joblib')
    print(examples.to_string(index=False))



def save_training_eda(X_train, y_train):
    """Save a training-only visual that makes the classification problem intuitive."""
    frame = X_train.copy()
    frame["Survived"] = y_train.to_numpy()

    labels = []
    rates = []
    for sex in ["female", "male"]:
        for pclass in [1, 2, 3]:
            group = frame[(frame["Sex"] == sex) & (frame["Pclass"] == pclass)]
            labels.append(f"{sex.title()}\\nClass {pclass}")
            rates.append(float(group["Survived"].mean() * 100))

    fig, ax = plt.subplots(figsize=(9, 5))
    bars = ax.bar(labels, rates)
    ax.set_ylim(0, 100)
    ax.set_ylabel("Survival rate in training rows (%)")
    ax.set_title("Training-only survival pattern by sex and ticket class")
    ax.bar_label(bars, labels=[f"{value:.1f}%" for value in rates], padding=3)
    fig.tight_layout()
    fig.savefig(ROOT / "outputs" / "survival_by_sex_class.png", dpi=160)
    plt.close(fig)


# handbook: run
def main():
    X_train, X_test, y_train, y_test = load_and_split()
    print(f'Training rows: {len(X_train)} | Final test rows: {len(X_test)}')
    print(f'Training survival rate: {y_train.mean():.4f}')
    prepared = make_preprocessor().fit_transform(X_train)
    print(f'Prepared training shape: {prepared.shape}')
    print('Candidates:', ', '.join(make_candidates()))
    (ROOT / 'outputs').mkdir(exist_ok=True)
    save_training_eda(X_train, y_train)
    comparison = compare_models(X_train, y_train)
    name = comparison.iloc[0]['model']
    search = tune_winner(name, X_train, y_train)
    # GridSearchCV refits the winning settings on all 712 training rows, not the holdout.
    final_pipeline = search.best_estimator_
    metrics, matrix = evaluate_final(final_pipeline, X_test, y_test)
    save_and_reload(final_pipeline)
    report = {
        'python': platform.python_version(), 'scikit_learn': sklearn.__version__,
        'data_sha256': hashlib.sha256((ROOT / 'data' / 'train.csv').read_bytes()).hexdigest(),
        'features': FEATURES, 'seed': SEED, 'training_rows': len(X_train), 'test_rows': len(X_test),
        'selected_model': name, 'best_params': search.best_params_,
        'best_cv_f1': float(search.best_score_), 'test_metrics': metrics, 'confusion_matrix': matrix,
        'majority_baseline_test_accuracy': float((y_test == y_train.mode()[0]).mean()),
    }
    (ROOT / 'outputs' / 'metrics.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
    fig, ax = plt.subplots(figsize=(8, 4))
    ax.barh(comparison['model'], comparison['f1'], xerr=comparison['f1_std'], color='#0f766e', capsize=4)
    ax.invert_yaxis()
    ax.set(xlabel='Mean F1 (five training-only folds)', xlim=(0, 1), title='Model comparison before tuning')
    fig.tight_layout()
    fig.savefig(ROOT / 'outputs' / 'model_comparison.png', dpi=150)
    plt.close(fig)


if __name__ == '__main__':
    main()

Checkpoint: the complete training file exists

Real Visual Studio Code window showing the verified Titanic train_model.py file
Captured from the real project after the verified build. Use it as a visual check that your final training file is in the correct src folder.
Open original-size screenshot (opens in a new tab)

Check before continuing

You can explain what preprocessing, candidate models, cross-validation and tuning each contribute before opening the full reference file.

Step 10: Understand preprocessing before comparing models

Imputation replaces a missing numeric value with the training median and a missing category with the training mode.

Standard scaling centers/scales numeric columns for algorithms such as Logistic Regression, KNN and SVM.

One-hot encoding converts categories into numeric indicator columns. handle_unknown="ignore" prevents a new category from crashing inference.

All of these live inside the Scikit-learn pipeline, so a validation fold never teaches its own information to the preprocessing fitted on a training fold.

Check before continuing

You can explain what happens to a missing Age, an Embarked category and a numeric value before the classifier receives them.

Step 11: Compare five classifier families with training-only cross-validation

Why F1: Survival is not a perfectly balanced target. F1 combines precision and recall for the positive class, so a model cannot look good merely by predicting the majority class.

Run the complete program from the project root:

Train, compare, tune and evaluatepowershellRunnable
python src/train_model.py
ModelCV accuracyCV precisionCV recallCV F1
Random Forest0.81600.79780.70340.7463
Support Vector Machine0.81740.80430.69580.7447
Logistic Regression0.80200.76520.69970.7301
K-Nearest Neighbors0.79920.77980.67020.7194
Decision Tree0.80340.80670.64480.7153

Real five-model comparison

Real bar chart comparing five Titanic classifiers by training-only cross-validation F1
Generated by the verified training program. Random Forest's mean F1 was 0.7463, narrowly ahead of SVM at 0.7447.
Open original-size screenshot (opens in a new tab)

Checkpoint: compare the exact generated rows

Real Visual Studio Code window showing the generated Titanic model_comparison.csv file
This is the CSV written by the same training run. It lets a learner visually confirm the five model rows and their recorded cross-validation metrics.
Open original-size screenshot (opens in a new tab)

Check before continuing

Your comparison contains five rows and Random Forest has the highest mean F1.

Step 12: Tune Random Forest without touching the holdout

What: GridSearchCV tries nine combinations of three depth values and three minimum-leaf values while keeping 200 trees.

Why: The model family won first; only then do we tune its settings. The final test set still stays sealed.

Verified tuning resulttextOutput
Selected by mean CV F1: Random Forest
Best settings: {'model__max_depth': None, 'model__min_samples_leaf': 2}
Best tuning CV F1: 0.7463

Checkpoint: the tuning search wrote its real results

Real Visual Studio Code window showing the generated Titanic GridSearchCV tuning_results.csv file
The generated file contains every tried hyperparameter combination and its cross-validation scores, so the best settings are traceable instead of appearing magically.
Open original-size screenshot (opens in a new tab)

Tuning did not improve on the existing baseline settings. That is a valid result: tuning is an experiment, not a promise that the score must rise.

Check before continuing

The output reports Random Forest, max_depth=None, min_samples_leaf=2 and best CV F1 ≈ 0.7463.

Step 13: Evaluate once on the untouched 179-passenger test set

Final holdout confusion matrix

Real Titanic final holdout confusion matrix with 100 true negatives, 10 false positives, 24 false negatives and 45 true positives
Rows are actual labels and columns are predictions. Order is 0 = did not survive, 1 = survived.
Open original-size screenshot (opens in a new tab)
Accuracy = (100 + 45) / 179 = 81.01%. Overall fraction classified correctly.
Precision = 45 / (45 + 10) = 81.82%. Of predicted survivors, how many actually survived?
Recall = 45 / (45 + 24) = 65.22%. Of actual survivors, how many did the model find?
F1 = 2×45 / (2×45 + 10 + 24) = 0.7258. Balance between precision and recall.

The majority-class baseline accuracy was only 61.45%, so 81.01% is meaningfully better than always predicting the most common class. It still does not make the model historically certain or causal.

Checkpoint: final metrics are recorded

Real Visual Studio Code window showing Titanic metrics.json from the verified holdout evaluation
The generated JSON records row counts, model choice, tuned settings, holdout metrics, confusion matrix, seed and dataset fingerprint from the verified run.
Open original-size screenshot (opens in a new tab)

Check before continuing

You can calculate accuracy, precision, recall and F1 from the confusion matrix instead of treating them as magic numbers.

Step 14: Save and reload the complete pipeline

What: Joblib serializes the fitted preprocessing and Random Forest together.

Why: Saving only the classifier would lose the learned medians, scaling values and category mapping. The app needs the whole pipeline.

The verified reload produced opposite labels for two synthetic passenger profiles, proving inference survives serialization. Only load Joblib files you created or trust.

Checkpoint: saved-model predictions survive reload

Real Visual Studio Code window showing the Titanic example_predictions.csv generated after saving and reloading the pipeline
The real output file shows the two example passenger profiles, their predicted labels and model survival scores after reloading the saved pipeline.
Open original-size screenshot (opens in a new tab)

Check before continuing

The terminal reports Saved and reloaded: models/titanic_pipeline.joblib and two example predictions are reproduced after reload.

Step 15: Create the Streamlit browser application

What: The browser form collects the same seven raw fields expected by the saved pipeline.

Why: This is the inference boundary: user input becomes one DataFrame row, then the saved pipeline performs every trained transformation and predicts.

app.py — complete Streamlit applicationpythonRunnable
"""Run from the project root with: python -m streamlit run app.py"""

# handbook: load
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import streamlit as st

ROOT = Path(__file__).resolve().parent
MODEL_PATH = ROOT / 'models' / 'titanic_pipeline.joblib'
FEATURES = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']

st.set_page_config(page_title='Titanic Survival Predictor', page_icon='🚢', layout='centered')
st.title('Can you survive the Titanic?')
st.write('Build a passenger profile, then ask the trained model for a prediction.')
st.caption('Educational experiment • historical data • not a statement of anyone’s actual fate')

if not MODEL_PATH.is_file():
    st.error('The saved model is missing. Train it before using this app.')
    st.code('python src/train_model.py', language='powershell')
    st.write('Run that command in your project terminal, wait for it to finish, then refresh this page.')
    st.stop()


@st.cache_resource
def load_pipeline(modified_ns):
    # modified_ns invalidates the cache if you retrain and overwrite the model.
    # Never load a joblib file supplied by someone you do not trust.
    return joblib.load(MODEL_PATH)


pipeline = load_pipeline(MODEL_PATH.stat().st_mtime_ns)

# handbook: form
with st.form('passenger'):
    left, right = st.columns(2)
    with left:
        pclass = st.selectbox('Ticket class', [1, 2, 3], format_func=lambda value: f'Class {value}', key='pclass')
        sex = st.selectbox('Sex recorded in the dataset', ['female', 'male'], key='sex')
        age = st.number_input('Age in years', min_value=0.0, max_value=100.0, value=29.0, step=0.5, key='age')
        age_unknown = st.checkbox('Age is unknown', key='age_unknown')
    with right:
        sibsp = st.number_input('Siblings / spouses aboard', min_value=0, max_value=8, value=0, step=1, key='sibsp')
        parch = st.number_input('Parents / children aboard', min_value=0, max_value=6, value=0, step=1, key='parch')
        fare = st.number_input('Ticket fare (historical pounds)', min_value=0.0, max_value=600.0, value=80.0, step=1.0, key='fare')
        embarked = st.selectbox('Boarding port', ['S', 'C', 'Q'],
            format_func=lambda value: {'S': 'Southampton', 'C': 'Cherbourg', 'Q': 'Queenstown'}[value], key='embarked')
    submitted = st.form_submit_button('Predict survival', type='primary')

# handbook: predict
if submitted:
    passenger = pd.DataFrame([{
        'Pclass': pclass, 'Sex': sex, 'Age': np.nan if age_unknown else age,
        'SibSp': sibsp, 'Parch': parch, 'Fare': fare, 'Embarked': embarked,
    }])[FEATURES]
    prediction = int(pipeline.predict(passenger)[0])
    if prediction == 1:
        st.success('Model prediction: Survived')
    else:
        st.info('Model prediction: Did Not Survive')
    if hasattr(pipeline, 'predict_proba'):
        positive_index = list(pipeline.classes_).index(1)
        probability = float(pipeline.predict_proba(passenger)[0, positive_index])
        st.metric('Model survival estimate', f'{probability:.1%}')
        st.caption('This is a model score, not a calibrated guarantee or historical certainty.')
    st.write('Inputs sent to the complete saved pipeline:')
    st.dataframe(passenger, hide_index=True)
    if age_unknown:
        st.caption('Unknown age was passed as a missing value; the saved training median filled it.')

st.divider()
st.caption('The model uses seven fields. It cannot know lifeboat access, chance, or the full historical circumstances. Do not use it for real safety decisions.')
Follow the prediction: form widgets → seven raw values → DataFrame in the exact feature order →pipeline.predict() for the class → predict_proba() for the model score → Streamlit result. The app never calls fit().

Check before continuing

The project root contains app.py with the complete source below.

Step 16: Run the app and make two real predictions

Start StreamlitpowershellRunnable
python -m streamlit run app.py

Keep the terminal running. Open the local address Streamlit prints, normally http://localhost:8501.

The real application

Real running Titanic Streamlit app before submitting a prediction
Captured automatically from the running Streamlit server during verification, not drawn or generated.
Open original-size screenshot (opens in a new tab)

Prediction example A

Real Titanic Streamlit prediction showing the survived result for the default first-class female profile
The default verified profile produces the project's Survived class and its model score.
Open original-size screenshot (opens in a new tab)

Prediction example B

Real Titanic Streamlit prediction showing the did-not-survive result for a third-class male profile
A contrasting third-class male profile produces the opposite class, verifying the full input → pipeline → result path.
Open original-size screenshot (opens in a new tab)

Check before continuing

The browser loads the form and you can produce both a Survived and Did Not Survive result without an exception.

Step 17: Run automated project and app tests

What: Tests check schema, split integrity, training-only preprocessing statistics, five-model comparison, saved predictions, recomputed metrics, missing/unseen inputs and Streamlit behavior.

Why: A screenshot can look correct while the underlying data path is wrong. Tests verify the contracts that matter.

tests/test_project.py — complete verification suitepythonRunnable
"""Verify the completed project without fitting or changing the saved artifacts.

After adding data/train.csv and running src/train_model.py, use:
    python -m unittest discover -s tests -v
"""

import hashlib
import importlib.util
import json
import os
from pathlib import Path
import unittest
from unittest.mock import patch

import joblib
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from streamlit.testing.v1 import AppTest

os.environ.setdefault('MPLBACKEND', 'Agg')

ROOT = Path(__file__).resolve().parents[1]
FEATURES = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']
NUMERIC = ['Age', 'SibSp', 'Parch', 'Fare']
CATEGORICAL = ['Pclass', 'Sex', 'Embarked']
CSV_COLUMNS = [
    'PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age',
    'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked',
]


def load_training_module():
    spec = importlib.util.spec_from_file_location('titanic_train_model', ROOT / 'src' / 'train_model.py')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


class CompletedProjectTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.training = load_training_module()
        cls.data = pd.read_csv(ROOT / 'data' / 'train.csv')
        cls.report = json.loads((ROOT / 'outputs' / 'metrics.json').read_text(encoding='utf-8'))
        # This file was produced locally by this project, not uploaded by a stranger.
        cls.pipeline = joblib.load(ROOT / 'models' / 'titanic_pipeline.joblib')
        cls.examples = pd.read_csv(ROOT / 'outputs' / 'example_predictions.csv')
        cls.X_train, cls.X_test, cls.y_train, cls.y_test = cls.training.load_and_split()

    def test_original_training_table_schema_and_recorded_fingerprint(self):
        self.assertEqual(self.data.shape, (891, 12))
        self.assertEqual(self.data.columns.tolist(), CSV_COLUMNS)
        self.assertTrue(self.data['PassengerId'].is_unique)
        self.assertEqual(set(self.data['Survived'].unique()), {0, 1})
        digest = hashlib.sha256((ROOT / 'data' / 'train.csv').read_bytes()).hexdigest()
        self.assertEqual(digest, self.report['data_sha256'])

    def test_split_is_disjoint_complete_stratified_and_has_exact_features(self):
        self.assertEqual(self.X_train.shape, (712, 7))
        self.assertEqual(self.X_test.shape, (179, 7))
        self.assertEqual(self.X_train.columns.tolist(), FEATURES)
        self.assertEqual(self.X_test.columns.tolist(), FEATURES)
        self.assertEqual(self.report['features'], FEATURES)
        self.assertEqual(self.report['training_rows'], 712)
        self.assertEqual(self.report['test_rows'], 179)
        self.assertEqual(self.report['seed'], self.training.SEED)
        self.assertEqual(set(self.X_train.index) & set(self.X_test.index), set())
        self.assertEqual(set(self.X_train.index) | set(self.X_test.index), set(self.data.index))
        pd.testing.assert_index_equal(self.X_train.index, self.y_train.index)
        pd.testing.assert_index_equal(self.X_test.index, self.y_test.index)
        pd.testing.assert_series_equal(self.y_train, self.data.loc[self.X_train.index, 'Survived'])
        pd.testing.assert_series_equal(self.y_test, self.data.loc[self.X_test.index, 'Survived'])
        self.assertLess(abs(self.y_train.mean() - self.y_test.mean()), 0.01)

    def test_pipeline_contains_numeric_and_categorical_preprocessing(self):
        self.assertIsInstance(self.pipeline, Pipeline)
        self.assertEqual(list(self.pipeline.named_steps), ['prepare', 'model'])
        self.assertEqual(self.pipeline.feature_names_in_.tolist(), FEATURES)
        prepare = self.pipeline.named_steps['prepare']
        self.assertIsInstance(prepare, ColumnTransformer)
        column_groups = {name: columns for name, _, columns in prepare.transformers_}
        self.assertEqual(column_groups['numbers'], NUMERIC)
        self.assertEqual(column_groups['categories'], CATEGORICAL)
        numbers = prepare.named_transformers_['numbers']
        categories = prepare.named_transformers_['categories']
        self.assertIsInstance(numbers.named_steps['fill_missing'], SimpleImputer)
        self.assertEqual(numbers.named_steps['fill_missing'].strategy, 'median')
        self.assertIsInstance(numbers.named_steps['scale'], StandardScaler)
        self.assertIsInstance(categories.named_steps['fill_missing'], SimpleImputer)
        self.assertEqual(categories.named_steps['fill_missing'].strategy, 'most_frequent')
        self.assertIsInstance(categories.named_steps['encode'], OneHotEncoder)
        self.assertEqual(categories.named_steps['encode'].handle_unknown, 'ignore')

    def test_saved_preprocessing_statistics_come_from_training_rows(self):
        prepare = self.pipeline.named_steps['prepare']
        numbers = prepare.named_transformers_['numbers']
        training_medians = self.X_train[NUMERIC].median()
        np.testing.assert_allclose(numbers.named_steps['fill_missing'].statistics_, training_medians)
        filled_training = self.X_train[NUMERIC].fillna(training_medians)
        np.testing.assert_allclose(numbers.named_steps['scale'].mean_, filled_training.mean())
        self.assertEqual(int(numbers.named_steps['scale'].n_samples_seen_), len(self.X_train))
        categories = prepare.named_transformers_['categories']
        for column, statistic in zip(CATEGORICAL, categories.named_steps['fill_missing'].statistics_):
            with self.subTest(column=column):
                self.assertEqual(statistic, self.X_train[column].mode().iloc[0])

    def test_five_candidate_families_and_training_cv_comparison(self):
        expected = {
            'Logistic Regression': LogisticRegression,
            'K-Nearest Neighbors': KNeighborsClassifier,
            'Support Vector Machine': SVC,
            'Decision Tree': DecisionTreeClassifier,
            'Random Forest': RandomForestClassifier,
        }
        candidates = self.training.make_candidates()
        self.assertEqual(set(candidates), set(expected))
        for name, classifier_type in expected.items():
            with self.subTest(model=name):
                self.assertIsInstance(candidates[name], classifier_type)
        comparison = pd.read_csv(ROOT / 'outputs' / 'model_comparison.csv')
        self.assertEqual(len(comparison), 5)
        self.assertEqual(set(comparison['model']), set(expected))
        self.assertTrue(comparison['f1'].is_monotonic_decreasing)
        for metric in ['accuracy', 'precision', 'recall', 'f1']:
            self.assertTrue(comparison[metric].between(0, 1).all())
        self.assertEqual(self.report['selected_model'], comparison.iloc[0]['model'])
        self.assertIsInstance(self.pipeline.named_steps['model'], expected[self.report['selected_model']])

    def test_loaded_model_reproduces_saved_example_predictions(self):
        features = self.examples[FEATURES]
        predictions = self.pipeline.predict(features)
        np.testing.assert_array_equal(predictions, self.examples['prediction'].to_numpy())
        # These two completed-project examples intentionally exercise opposite labels.
        self.assertEqual(predictions.tolist(), [1, 0])
        self.assertEqual(self.pipeline.classes_.tolist(), [0, 1])
        positive_index = list(self.pipeline.classes_).index(1)
        probabilities = self.pipeline.predict_proba(features)[:, positive_index]
        np.testing.assert_allclose(probabilities, self.examples['survival_probability'], rtol=0, atol=1e-12)

    def test_manual_confusion_counts_and_metrics_match_saved_report(self):
        # Predict only: never call evaluate_final(), which writes charts, or fit().
        actual = self.y_test.to_numpy()
        predicted = self.pipeline.predict(self.X_test)
        tn = int(((actual == 0) & (predicted == 0)).sum())
        fp = int(((actual == 0) & (predicted == 1)).sum())
        fn = int(((actual == 1) & (predicted == 0)).sum())
        tp = int(((actual == 1) & (predicted == 1)).sum())
        self.assertEqual([[tn, fp], [fn, tp]], self.report['confusion_matrix'])
        self.assertEqual(tn + fp + fn + tp, 179)
        calculated = {
            'accuracy': (tn + tp) / (tn + fp + fn + tp),
            'precision': tp / (tp + fp) if tp + fp else 0,
            'recall': tp / (tp + fn) if tp + fn else 0,
            'f1': 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0,
        }
        for name, value in calculated.items():
            with self.subTest(metric=name):
                self.assertAlmostEqual(value, self.report['test_metrics'][name], places=12)
        majority_label = self.y_train.mode().iloc[0]
        baseline = float((self.y_test == majority_label).mean())
        self.assertAlmostEqual(baseline, self.report['majority_baseline_test_accuracy'], places=12)

    def test_batch_accepts_missing_values_and_unseen_categories(self):
        rows = pd.DataFrame([
            {'Pclass': 3, 'Sex': 'male', 'Age': np.nan, 'SibSp': 0, 'Parch': 0, 'Fare': np.nan, 'Embarked': np.nan},
            {'Pclass': 4, 'Sex': 'unseen', 'Age': 22.0, 'SibSp': 1, 'Parch': 0, 'Fare': 7.25, 'Embarked': 'unseen'},
            {'Pclass': np.nan, 'Sex': np.nan, 'Age': np.nan, 'SibSp': np.nan, 'Parch': np.nan, 'Fare': np.nan, 'Embarked': np.nan},
        ], columns=FEATURES)
        transformed = self.pipeline.named_steps['prepare'].transform(rows)
        self.assertEqual(transformed.shape, (3, 12))
        self.assertTrue(np.isfinite(transformed).all())
        predicted = self.pipeline.predict(rows)
        self.assertEqual(predicted.shape, (3,))
        self.assertTrue(set(predicted).issubset({0, 1}))
        probabilities = self.pipeline.predict_proba(rows)
        self.assertTrue(np.isfinite(probabilities).all())
        self.assertTrue(((probabilities >= 0) & (probabilities <= 1)).all())
        np.testing.assert_allclose(probabilities.sum(axis=1), 1)

    def test_absent_feature_column_is_rejected_not_silently_guessed(self):
        # Missing cell values are supported; a missing input field is a schema error.
        with self.assertRaises(ValueError):
            self.pipeline.predict(self.examples[FEATURES].drop(columns='Age'))


class StreamlitAppTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.examples = pd.read_csv(ROOT / 'outputs' / 'example_predictions.csv')
        cls.pipeline = joblib.load(ROOT / 'models' / 'titanic_pipeline.joblib')

    def open_app(self):
        app = AppTest.from_file(str(ROOT / 'app.py'), default_timeout=30).run()
        self.assertEqual(len(app.exception), 0, [error.message for error in app.exception])
        return app

    def submit_passenger(self, app, passenger, age_unknown=False):
        app.selectbox(key='pclass').set_value(int(passenger['Pclass']))
        app.selectbox(key='sex').set_value(passenger['Sex'])
        app.number_input(key='age').set_value(float(passenger['Age']))
        app.checkbox(key='age_unknown').set_value(age_unknown)
        app.number_input(key='sibsp').set_value(int(passenger['SibSp']))
        app.number_input(key='parch').set_value(int(passenger['Parch']))
        app.number_input(key='fare').set_value(float(passenger['Fare']))
        app.selectbox(key='embarked').set_value(passenger['Embarked'])
        buttons = [button for button in app.button if button.label == 'Predict survival']
        self.assertEqual(len(buttons), 1)
        buttons[0].click().run()
        self.assertEqual(len(app.exception), 0, [error.message for error in app.exception])
        return app

    def assert_estimate(self, app, probability):
        metrics = [metric for metric in app.metric if metric.label == 'Model survival estimate']
        self.assertEqual(len(metrics), 1)
        self.assertEqual(metrics[0].value, f'{probability:.1%}')

    def test_form_returns_both_contrasting_saved_example_predictions(self):
        app = self.open_app()
        self.assertEqual(len(app.metric), 0, 'Do not show a prediction before submitting the form.')
        for _, passenger in self.examples.iterrows():
            with self.subTest(prediction=int(passenger['prediction'])):
                self.submit_passenger(app, passenger)
                if passenger['prediction'] == 1:
                    self.assertIn('Model prediction: Survived', [message.value for message in app.success])
                    self.assertEqual(len(app.info), 0)
                else:
                    self.assertIn('Model prediction: Did Not Survive', [message.value for message in app.info])
                    self.assertEqual(len(app.success), 0)
                self.assert_estimate(app, passenger['survival_probability'])
                self.assertEqual(app.dataframe[0].value.columns.tolist(), FEATURES)
                np.testing.assert_allclose(app.dataframe[0].value[NUMERIC].to_numpy(dtype=float),
                                           passenger[NUMERIC].to_numpy(dtype=float).reshape(1, -1))

    def test_unknown_age_is_sent_as_missing_and_still_predicts(self):
        passenger = self.examples.iloc[0]
        app = self.submit_passenger(self.open_app(), passenger, age_unknown=True)
        self.assertTrue(pd.isna(app.dataframe[0].value.iloc[0]['Age']))
        expected_input = self.examples.iloc[[0]][FEATURES].copy()
        expected_input.loc[:, 'Age'] = np.nan
        positive_index = list(self.pipeline.classes_).index(1)
        probability = self.pipeline.predict_proba(expected_input)[0, positive_index]
        self.assert_estimate(app, probability)
        self.assertTrue(any('saved training median' in caption.value for caption in app.caption))

    def test_missing_model_shows_training_instruction_without_mutating_files(self):
        model_path = ROOT / 'models' / 'titanic_pipeline.joblib'
        original_is_file = Path.is_file
        checked_missing_model = []

        def pretend_only_model_is_absent(path):
            if path == model_path:
                checked_missing_model.append(path)
                return False
            return original_is_file(path)

        # Simulate absence for the app's existence check; never move/delete the model.
        with patch.object(Path, 'is_file', autospec=True, side_effect=pretend_only_model_is_absent):
            app = self.open_app()
        self.assertTrue(checked_missing_model)
        self.assertTrue(any('saved model is missing' in message.value.lower() for message in app.error))
        self.assertIn('python src/train_model.py', [code.value for code in app.code])
        self.assertEqual(len(app.button), 0)
        self.assertEqual(len(app.metric), 0)
        self.assertTrue(model_path.is_file())


if __name__ == '__main__':
    unittest.main()
Run the testspowershellRunnable
python -m unittest discover -s tests -v

Check before continuing

The test command completes without failures after training has created the local model file.

Step 18: Understand the finished project folder

titanic-survival-predictor/
├── data/train.csv # local input, not committed
├── models/titanic_pipeline.joblib # generated locally
├── notebooks/01_titanic_exploration.ipynb
├── outputs/model_comparison.csv
├── outputs/model_comparison.png
├── outputs/confusion_matrix.png
├── outputs/metrics.json
├── src/train_model.py
├── tests/test_project.py
├── app.py
├── requirements.txt
└── .gitignore

Checkpoint: finished project workspace

Real Visual Studio Code window showing the finished Titanic project workspace
A real VS Code view of the completed project confirms where source, tests, outputs and documentation live before the learner publishes the source repository.
Open original-size screenshot (opens in a new tab)

The reproducible source is what matters. Raw Kaggle data and generated Joblib artifacts stay out of Git so the repository does not redistribute data or binaries unnecessarily.

Check before continuing

You can explain which files are source, which are inputs and which are generated outputs.

Step 19: Put the finished source project on GitHub

Create .gitignore first:

.gitignoretextConfiguration
.venv/
__pycache__/
.ipynb_checkpoints/
data/*.csv
models/*.joblib
.streamlit/secrets.toml
*.log
Git/GitHub commandspowershellRunnable
git init
git add .
git status
git commit -m "Build Titanic survival predictor"
git branch -M main
git remote add origin https://github.com/YOUR-USERNAME/titanic-survival-predictor.git
git push -u origin main

Always read git status before committing. Never commit passwords, API keys, secrets, a virtual environment or an untrusted serialized model.

Check before continuing

GitHub shows your source/notebook/output evidence but not .venv, raw CSV or generated Joblib model.

Now prove you understand the implementation

Do at least two of these after reproducing the reference build. Record what changed and why.

Exercise 1 — Change the selection metric. Compare what wins if you sort by recall instead of F1. Explain why that changes what “best” means.
Exercise 2 — Add FamilySize. Create FamilySize = SibSp + Parch + 1 as an optional experiment, retrain and compare cross-validation F1. Do not use the holdout to decide whether to keep it.
Exercise 3 — Remove scaling from the numeric branch. Compare what happens to Logistic Regression/KNN/SVM versus tree models and explain why.
Exercise 4 — Break inference safely. Temporarily rename your local Joblib file, start Streamlit, read the recovery instruction, restore the file and retry.

Common problems and exact fixes

python/py is not recognized: reopen PowerShell after installation. If still missing, rerun the Python installer and enable its command-line integration.

Activate.ps1 is blocked: use the explicit environment Python, for example .\.venv\Scripts\python.exe -m pip install -r requirements.txt, rather than changing machine-wide security policy.

train.csv not found: confirm the file is exactly data/train.csv and that the terminal is at the project root.

Wrong CSV error: the handbook expects the classic 891-row, 12-column training file with Survived. Kaggle's competition test.csv has no target and cannot replace it.

ModuleNotFoundError: activate .venv and rerun python -m pip install -r requirements.txt.

Saved model is missing: run python src/train_model.py successfully before starting Streamlit.

Prediction crashes after changing features: training and app input schemas must agree. Retrain the pipeline and update the app together.

How to explain this project in an interview

Why a Pipeline?

It keeps imputation, scaling/encoding and the classifier together so cross-validation learns preprocessing only from training folds and inference reuses the exact fitted transformations.

Why stratify?

The split preserves roughly the same survival proportion in training and holdout sets, reducing accidental class-ratio drift.

Why F1 for model selection?

The target is moderately imbalanced, and F1 forces us to consider both survivor precision and survivor recall instead of only overall accuracy.

Why Random Forest?

It had the highest mean 5-fold CV F1 (0.7463) among the five candidate families. SVM was very close at 0.7447, so the evidence does not imply Random Forest is universally better.

Why is the holdout special?

It remained unused during model-family selection and tuning, then was evaluated once as the final test.

What is the biggest limitation?

The model uses a small historical dataset and seven fields. Passenger/family grouping and unmodeled historical circumstances mean this is a teaching classifier, not a causal or safety system.

What would change in a real production classification system?

You would add a formally versioned data contract, stronger group-aware validation where related records can leak information, probability calibration if scores are used as probabilities, threshold selection tied to business costs, drift monitoring, model/version logging, automated retraining and rollback, authentication, observability and human review for consequential use.

This Titanic project deliberately stops at a safe educational Streamlit demo. The historical label is not something to use for real-world safety decisions.

Implementation mastery check

You are finished when you can answer these without copying the handbook.

What is the target and what are the seven input features?
Why is Cabin not used in this baseline?
Why split before fitting imputers or encoders?
What exactly does stratify=y protect against?
What happens to a missing Age inside the pipeline?
Why do Logistic Regression/KNN/SVM care more about scaling than trees?
How does 5-fold cross-validation work here?
Why did we select by F1 rather than holdout accuracy?
How close was SVM to Random Forest?
How do 100, 10, 24 and 45 produce the four final metrics?
What is saved inside titanic_pipeline.joblib?
How does app.py turn form fields into a prediction?
Why must the app never refit preprocessing?
What would you change before using this pattern for a real business problem?

Complete-project checkpoint

Raw Kaggle training table inspected
Missing values and target distribution understood
Stratified train/holdout split created
Preprocessing kept inside a Pipeline
Five model families compared by 5-fold CV
Random Forest tuned on training data only
Final holdout evaluated once
Accuracy, precision, recall and F1 derived from the matrix
Complete pipeline saved and reloaded
Streamlit app uses the saved pipeline
Automated tests verify data/model/app contracts
Real app screenshots captured by verification
Source project is GitHub-ready
You can explain and modify the implementation

Your build checkpoints — Titanic Survival Predictor

Keep the full handbook and all source code visible above. These optional checkpoints help you track what you can actually build and explain. Progress is saved only in this browser.

0 of 5 checkpoints completed

Predict → change → observe → explain

Before: Predict how passenger class and fare may affect the result before running the app.

Try: Change one passenger input at a time while keeping the others fixed.

Show your evidence: Record both predicted survival probabilities and explain what changed.

Environment setup on your computer

Unzip the source first, open its project folder in VS Code, then read its README for dataset/download instructions. Python 3.13 is the documented starting version for this project; follow its README if it specifies a more exact patch release.

Windows PowerShell commands
py -3.13 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe -m pip check
macOS / Linux commands
python3.13 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python -m pip check

No global package installation or machine-wide policy changes are necessary. For Windows, explicit environment Python avoids PowerShell activation-policy issues. PyTorch or downloaded datasets may require substantial disk space.

Optional: publish a small demo safely
  1. Finish the local test, save a screenshot and check your actual saved model or index works after restart.
  2. Use a repository you control. Exclude API keys, .env files, personal uploads, unlicensed datasets and generated sensitive artifacts.
  3. Choose a host that supports your actual Python and system dependencies. If a model or data file is generated locally, plan a permitted and reproducible build step before expecting a cloud demo to start.
  4. Test the real hosted application on desktop and mobile, including invalid inputs, empty answers, missing model files and service restarts.
  5. Do not expose a paid AI key or an unrestricted inference endpoint to the public; add user authentication, rate limits and spending limits first. Keep a local-only demonstration if you cannot protect it.

This is an optional safety checklist, not a claim that any project already has a public deployed demo.

Important limitation: Kaggle competition data requires an account and acceptance of its rules; synthetic examples are not substitute evaluation data.