Skip to main content

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

1. Which call learns a model from training rows?
2. Why call train_test_split before fitting preprocessing?
3. What is the benefit of putting scaling inside Pipeline?
4. What does cross_val_score do?

0 of 4 questions answered.

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.

LinesRead this blockTrace this question
1–10ImportsWhich parts make arrays, split data, preprocess, fit, and score?
12–26Generate n=120 rows and label yWhat is a feature versus a target?
28–37Add np.nan and fill X[:, i]Which columns have missing values?
39–60Define numeric/categorical branches and candidateWhere do imputation and one-hot encoding happen?
63–72Two stratified splitsWhy 72 train, 24 validation, 24 final test?
74–85Set recall gate, fit baseline/candidate, define metricsWhich rows influence the fitted state?
87–103Compute validation scores and inspect fitted transformsWhy candidate.named_steps works only after fit?
105–121Default show_final_test=False and print evidenceWhat is visible before model selection ends?
123–138Optionally clone, refit and reveal final test onceWhy 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

After Pipeline.fit(X_train, y_train), which step is safe on held-out test rows?

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

1. When using cross_val_score with an imputer and classifier, what should be passed?
2. A held-out row has a new category and OneHotEncoder(handle_unknown='ignore'). What should happen?
3. Two candidates were compared on validation. When should final-test results influence which one is selected?
4. Where are fitted numeric imputer statistics after Pipeline.fit?

0 of 4 questions answered.

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.