P4 — Reading scikit-learn Code
About 55 min
Before L1.18 — Real-World Tabular ML, learn to read the workflow rather than memorize its imports. P1 and P2 cover the Python and NumPy notation. If you get every question below right, you can move to the next lesson. This optional guide, its diagnostic, and its Lab do not count toward course progress.
Quick Check
Goal
Read an ML starter from raw table to split, fitted preprocessing, predictions, validation and final test. Identify where learned state comes from and explain each output without writing a new model class.
Read method names as a workflow
model.fit(X_train, y_train) # learns fitted coefficients and preprocessing
labels = model.predict(X_test) # labels for unseen rows
features = model.named_steps["preprocess"].transform(X_test)
fit learns from data; predict produces labels after fitting; transform converts rows using an already-fitted transformer. A transformer can also expose fit_transform on training rows, but do not fit it again on the test set. A Pipeline sequences named operations, and named_steps["preprocess"] looks up an already-fitted step.
Splits and cross-validation
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.20, random_state=42, stratify=y
)
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X_train, y_train, cv=3, scoring="recall")
The four left-hand names receive aligned feature/label partitions. test_size=0.20 reserves 20%, random_state makes the random split reproducible, and stratify=y approximately preserves label proportions. cross_val_score fits fresh pipeline clones within each fold; its scores summarize cross-validation on the training/development partition, not the final test. The independent final test must not guide model selection.
Read Pipeline and ColumnTransformer nesting
numeric = Pipeline([("fill", SimpleImputer(strategy="median")),
("scale", StandardScaler())])
preprocess = ColumnTransformer([
("num", numeric, [0, 1]),
("cat", OneHotEncoder(handle_unknown="ignore"), [2]),
])
model = Pipeline([("preprocess", preprocess),
("classifier", LogisticRegression(max_iter=300))])
Inside each tuple, read step name, operation, columns. ColumnTransformer handles different columns in parallel; Pipeline connects successive processing steps. The imputer median, scaler statistics, encoder categories, and model coefficients are fitted state. A final predict applies the same transformations to the evaluation rows without learning from those rows. handle_unknown="ignore" is a policy for unseen categories, not a promise that every unknown value is meaningful.
A guided map of the actual 138-line L1.18 starter
Open the L1.18 browser Lab starter source in another tab; its 138 nonblank/blank source lines are organized into blocks. You do not need to type them from scratch.
| Lines | Read this block | Trace this question |
|---|---|---|
| 1–10 | Imports | Which parts make arrays, split data, preprocess, fit, and score? |
| 12–26 | Generate n=120 rows and label y | What is a feature versus a target? |
| 28–37 | Add np.nan and fill X[:, i] | Which columns have missing values? |
| 39–60 | Define numeric/categorical branches and candidate | Where do imputation and one-hot encoding happen? |
| 63–72 | Two stratified splits | Why 72 train, 24 validation, 24 final test? |
| 74–85 | Set recall gate, fit baseline/candidate, define metrics | Which rows influence the fitted state? |
| 87–103 | Compute validation scores and inspect fitted transforms | Why candidate.named_steps works only after fit? |
| 105–121 | Default show_final_test=False and print evidence | What is visible before model selection ends? |
| 123–138 | Optionally clone, refit and reveal final test once | Why not tune after that reveal? |
Try a reading pass that points at the exact code for class_weight="balanced", required_validation_recall=0.70, and show_final_test=False. Predict which outputs change when the class weight changes, then use the L1.18 Lab to test the hypothesis. The pipeline can prevent one class of leakage; it cannot validate the meaning of the chosen features or final-test discipline.
Predict
Guided browser Lab
The starter already defines a small mixed table, split, ColumnTransformer and Pipeline. Fill only three TODOs: fit on training rows; predict held-out labels; inspect transformed feature width. Run before and after each change. The manifest provides three progressive hints and a full answer. Reserve roughly 15 minutes for this exercise and 10 minutes for L1.18 block tracing.
Loading lab…
Quick Check
Key Takeaways
- fit learns; predict and transform use fitted state.
- Split before fitting learned preprocessing; use whole Pipeline for cross-validation.
- The L1.18 final-test switch is a one-time review boundary, not another tuning control.