"""Assignment 1: Preprocessing and linear models -- reference solution. Runs the assignment end to end exactly as written (content/assignments/01.md): seven Titanic predictors, stratified 80/20 split with random_state=42, one ColumnTransformer, dummy / logistic / k-NN compared with 5-fold stratified CV, GridSearchCV on F1, one final evaluation on the test set. The printed numbers are the ones quoted in the assignment's "Check your numbers" box, so re-run this after any scikit-learn upgrade. """ import time import numpy as np import pandas as pd import seaborn as sns from sklearn.compose import ColumnTransformer from sklearn.dummy import DummyClassifier from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.metrics import ( accuracy_score, confusion_matrix, f1_score, precision_score, recall_score, ) from sklearn.model_selection import ( GridSearchCV, StratifiedKFold, cross_validate, train_test_split, ) from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder, StandardScaler # ---------------------------------------------------------------- data df = sns.load_dataset("titanic") columns = ["survived", "pclass", "sex", "age", "sibsp", "parch", "fare", "embarked"] df = df[columns] X = df.drop(columns="survived") y = df["survived"] # ---------------------------------------------------------------- Part 1 print("Part 1 -- inspect") print(f" rows: {len(df)}, predictors: {X.shape[1]}") missing = X.isnull().sum() print(f" missing: {missing[missing > 0].to_dict()}") print(f" survived: {y.mean():.3f}") assert len(df) == 891 and X.shape[1] == 7 assert missing.to_dict() == {"pclass": 0, "sex": 0, "age": 177, "sibsp": 0, "parch": 0, "fare": 0, "embarked": 2} # pclass is ordinal with three levels; L3 treats it as categorical and so do we. num_cols = ["age", "sibsp", "parch", "fare"] cat_cols = ["pclass", "sex", "embarked"] # ---------------------------------------------------------------- Part 2 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) print(f"\nPart 2 -- split: {len(X_train)} train / {len(X_test)} test") assert (len(X_train), len(X_test)) == (712, 179) # ---------------------------------------------------------------- Part 3 preprocessor = ColumnTransformer([ ("num", Pipeline([ ("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler()), ]), num_cols), ("cat", Pipeline([ ("imputer", SimpleImputer(strategy="most_frequent")), ("encoder", OneHotEncoder(handle_unknown="ignore")), ]), cat_cols), ]) n_features_out = preprocessor.fit_transform(X_train).shape[1] print(f"\nPart 3 -- preprocessor fits; {n_features_out} columns after encoding") assert n_features_out == 12 # 4 numeric + 3 pclass + 2 sex + 3 embarked def make_pipeline(model): # The estimator step is named "model" so grids can use "model__C" etc. return Pipeline([("prep", preprocessor), ("model", model)]) # ---------------------------------------------------------------- Part 4 cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) scoring = ["accuracy", "f1"] candidates = { "dummy": DummyClassifier(strategy="most_frequent"), "logistic": LogisticRegression(max_iter=1000), "knn": KNeighborsClassifier(), } print("\nPart 4 -- 5-fold stratified CV on the training data") print(f" {'model':10s} {'accuracy':>16s} {'f1':>16s}") part4 = {} for name, model in candidates.items(): res = cross_validate(make_pipeline(model), X_train, y_train, cv=cv, scoring=scoring) acc, f1 = res["test_accuracy"], res["test_f1"] part4[name] = (acc.mean(), acc.std(), f1.mean(), f1.std()) print(f" {name:10s} {acc.mean():8.3f} +/- {acc.std():.3f} {f1.mean():8.3f} +/- {f1.std():.3f}") assert part4["dummy"][2] == 0.0, "most-frequent dummy never predicts survived" assert part4["logistic"][0] > part4["dummy"][0] + 0.1 assert part4["knn"][0] > part4["dummy"][0] + 0.1 # ---------------------------------------------------------------- Part 5 print("\nPart 5 -- GridSearchCV, selection metric F1") grids = { "logistic": ( LogisticRegression(max_iter=1000), {"model__C": [0.01, 0.1, 1, 10, 100]}, ), "knn": ( KNeighborsClassifier(), {"model__n_neighbors": [3, 5, 11, 21, 41], "model__weights": ["uniform", "distance"]}, ), } searches = {} for name, (model, grid) in grids.items(): t0 = time.perf_counter() search = GridSearchCV(make_pipeline(model), grid, cv=cv, scoring="f1", n_jobs=-1) search.fit(X_train, y_train) elapsed = time.perf_counter() - t0 searches[name] = search print(f" {name}: best {search.best_params_} CV f1 {search.best_score_:.3f} ({elapsed:.1f}s)") table = pd.DataFrame(search.cv_results_)[["params", "mean_test_score", "std_test_score"]] for _, row in table.iterrows(): print(f" {row['mean_test_score']:.3f} +/- {row['std_test_score']:.3f} {row['params']}") # C = 0.01 underfits; everything from C = 0.1 upwards ties within ~0.003, so # the tie-break rule picks the simplest (most penalised) of the tied settings. # k-NN's best k sits inside the grid, not at an edge -- the check L7 asks for. log_table = pd.DataFrame(searches["logistic"].cv_results_) tied = log_table[log_table["param_model__C"] >= 0.1]["mean_test_score"] assert tied.max() - tied.min() < 0.01, "C >= 0.1 no longer tie" assert log_table["mean_test_score"].iloc[0] < tied.min() - 0.05, "C = 0.01 no longer underfits" knn_best_k = searches["knn"].best_params_["model__n_neighbors"] assert knn_best_k not in (3, 41), f"k-NN best k={knn_best_k} sits at a grid edge" # ---------------------------------------------------------------- Part 6 # Choose by CV evidence alone: the better of the two tuned searches. best_name = max(searches, key=lambda k: searches[k].best_score_) final = searches[best_name].best_estimator_ # already refitted on all training data y_pred = final.predict(X_test) acc = accuracy_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) prec = precision_score(y_test, y_pred) rec = recall_score(y_test, y_pred) cm = confusion_matrix(y_test, y_pred) baseline_acc = DummyClassifier(strategy="most_frequent").fit(X_train, y_train).score(X_test, y_test) print(f"\nPart 6 -- final model: {best_name} {searches[best_name].best_params_}") print(f" test accuracy {acc:.3f} (dummy {baseline_acc:.3f})") print(f" test f1 {f1:.3f} precision {prec:.3f} recall {rec:.3f}") print(f" confusion matrix [[TN FP] [FN TP]]:\n {cm.tolist()}") fn, fp = cm[1, 0], cm[0, 1] print(f" false negatives (missed survivors): {fn}, false positives: {fp}") assert acc > baseline_acc + 0.1 assert abs(baseline_acc - 0.615) < 0.01 print("\nOK")