Real-World Tabular ML: Pipelines and Model Review
About 38 min
First time reading scikit-learn pipelines? Complete optional P4 — Reading scikit-learn Code before this lesson; its starter map and browser Lab do not count toward progress.
Goal
By the end of this lesson, you can build a leak-safe tabular preprocessing pipeline for numeric and categorical features, handle missing values, evaluate class imbalance with more than accuracy, and review several model families under the same split and evidence rules.
Real tables are rarely clean numeric matrices
A realistic table may contain numeric features, categorical features, missing values, identifiers, and a target.
A model cannot safely learn from it until we define how each feature type is processed.
The important idea is not a collection of preprocessing tricks. It is one fitting boundary: every data-dependent transformation must learn only from the training portion used at that stage.
Missing values need an explicit rule
An imputer fills missing values using a repeatable strategy.
For a numeric column, one simple choice is the training median. For a categorical column, one choice is the most frequent training category or a fixed missing category.
When the fill value depends on data, it is learned preprocessing.
Therefore:
split first -> fit imputer on training data -> reuse it on validation/test data
Computing a median from the entire dataset before the split leaks evaluation information.
Categories need a numeric representation
A category such as plan type = basic / plus / pro is not an ordered number. Mapping them to 1 / 2 / 3 would invent spacing that the data did not give us.
One-hot encoding creates separate indicator columns instead.
Unknown categories at evaluation time need an explicit policy; a robust pipeline should not crash merely because a valid new category appears.
Different columns can need different preprocessing
Numeric columns may need imputation and, for scale-sensitive models, standardization.
Categorical columns may need imputation and one-hot encoding.
A ColumnTransformer lets those branches happen in one fitted object before the model.
The full procedure becomes:
raw table -> column-specific preprocessing -> model
When this object is fitted inside cross-validation, each fold learns its imputers, encoders, and scalers only from that fold's training rows.
Class imbalance changes what accuracy means
Suppose only 5% of examples belong to the positive class.
A model that always predicts the majority class gets 95% accuracy while finding none of the positives.
Class imbalance is not automatically a reason to resample or reweight. It is first an evaluation and data-understanding problem.
Ask about class frequencies, decision costs, precision, recall, the confusion matrix, split quality, and whether there are enough positive examples to support a reliable estimate.
Only then decide whether class weights, sampling, thresholds, or more data are appropriate.
Run a leak-safe mixed-type pipeline
The Lab creates a deterministic table with numeric columns, categorical columns, missing values, and an imbalanced target. It keeps model selection and final evaluation separate:
training rows -> fit candidate models during selection
validation rows -> compare settings using a rule fixed in advance
training + validation rows -> refit the chosen model after settings are fixed
final test rows -> one final check
The starter keeps the final-test metrics out of the output while you experiment. That is deliberate: once a test result guides another model change, the test has joined the development process.
- Before clicking Run, find
required_validation_recall = 0.70. Treat that as the review rule fixed in advance: a candidate must reach at least0.70validation recall to remain eligible. - Click Run. Confirm that the first output repeats
review rule: validation recall >= 0.7. - Inspect
numeric_columnsandcategorical_columns, then confirm that imputation, scaling, and one-hot encoding live insidepreprocess. - Read
split sizes:. The fixture uses72training rows,24validation rows, and24final-test rows. Confirm that the output saysfinal-test metrics: hidden during model selection. - Read
validation positives:andcandidate validation true positives:. There are only4positive validation examples, and the balanced candidate finds3, so validation recall is3/4 = 0.75. It passes the rule fixed in step 1. - Translate that metric back into examples: changing the outcome of one positive validation row would move recall by
1/4 = 0.25. - Find
class_weight="balanced"insideLogisticRegression. Change only"balanced"toNone. - Before running, predict whether accuracy, precision, and recall must all move in the same direction. Click Run. On this fixture, validation accuracy rises from about
0.792to0.917and precision from about0.429to1.0, while recall falls from0.75to0.50. The unweighted candidate therefore fails the precommitted recall rule. - Press Reset so the selected
class_weight="balanced"setting is restored. At this point, model selection is finished. The setting is fixed. - Find
show_final_test = False. Change onlyFalsetoTrue, then click Run once. The Lab now creates a fresh clone of the selected pipeline, fits it on all96development rows (72training +24validation), and only then evaluates the untouched final test. - Read the block labeled
FINAL TEST — do not use this result to tune the model:. It should showfinal training rows: 96,final-test positives: 4, andfinal-test true positives: 4. The final-test accuracy is about0.833, precision is0.500, and recall is1.000 = 4/4. - Treat
4/4as a small-sample result, not proof of perfect future recall. Do not change the model because of this final-test result. If you start another tuning cycle, you need a new untouched final evaluation set.
Python used here: several from-imports, named pipeline steps and a data table with missing cells (P1 — imports, P2 — arrays).
Loading lab…
A pipeline makes fitting order reproducible. It does not guarantee that the features are valid or that the split matches the future task. When a validation or test set is small, translate metrics back into example counts before treating a small numerical difference as strong evidence. Use validation evidence for model choices, freeze those choices, refit the final model on the available development data, and preserve final-test evidence for the end.
Review multiple model families under the same rules
You now know several candidate families:
- a trivial baseline;
- logistic regression;
- a decision tree;
- Random Forest;
- gradient boosting.
A fair review keeps the information boundary and evaluation conditions consistent.
Do not choose a model merely because one headline metric is highest.
Ask whether every candidate used the same allowed information, whether model selection stayed away from the final test set, which metrics match decision costs, whether gains repeat across validation folds, whether there is an overfitting gap, and what complexity or explainability tradeoff comes with the gain.
Optional recognition map: four classical families you should know exist
The core Level 1 build uses a deliberately small set of model families so you can compare them carefully. The wider classical-ML landscape is larger. The families below are recognition-level extensions: you should know the learning idea and the experiment assumptions they introduce, but this Lesson does not claim that you have implemented or mastered them.
| Family | Learning idea | What changes in a fair comparison |
|---|---|---|
| k-nearest neighbors (k-NN) | Predict from nearby training examples instead of fitting one global equation or tree. | Distance depends on feature scale and the choice of k; prediction can also become expensive when the training set is large. |
| Naive Bayes | Combine class probabilities with feature evidence under a simplifying conditional-independence assumption. | The probability model and feature representation matter; the independence assumption can be useful even when it is not literally true. |
| Support vector machine (SVM) | Choose a decision boundary with a wide margin; kernels can represent some nonlinear boundaries through a different similarity space. | Scaling, regularization, kernel choice, and dataset size can materially change behavior and cost. |
| Ridge / Lasso | Keep a linear-model objective but add a penalty that discourages large coefficients. Ridge uses an L2 penalty; Lasso uses an L1 penalty that can drive some coefficients to zero. | The regularization strength becomes another fitted choice that must stay inside the validation process. |
These are not a ladder where the bottom row is “more advanced” or universally better. They encode different assumptions. A local-neighbor method can be useful when nearby examples really are informative. A linear model with Ridge can be easier to audit than a more flexible model. An SVM can create a strong margin on one dataset and be awkward on another. The only defensible comparison is the same one you have used throughout Level 1: keep the information boundary fixed, tune only on allowed training/validation evidence, and measure the errors that matter for the task.
Ridge and Lasso are especially useful for keeping the family map straight. They are not replacements for linear regression in the sense that a tree is a different model shape. They are regularized linear-model extensions: the prediction is still built from weighted features, but the training objective now also charges the model for coefficient size.
Record enough to reproduce the comparison
| Item | Record |
|---|---|
| Data | source/revision and feature definitions |
| Split | strategy, proportions, seed, grouping or time rule |
| Preprocessing | column roles, imputation, encoding, scaling |
| Candidate | model family and important hyperparameters |
| Selection | validation method and selection metric |
| Final evidence | untouched final-test metrics plus failure analysis |
Another learner should be able to reconstruct the comparison without guessing.
A high score is a result, not a trust argument
A trustworthy model review is a chain of evidence:
- define the prediction moment;
- reject future or target-derived features;
- keep final evaluation outside fitting and model selection;
- place learned preprocessing inside the fitting boundary;
- compare against a baseline;
- use metrics that expose important errors;
- inspect overfitting and concrete failures;
- state limitations.
Quick Check
Key Takeaways
- Real-world tabular ML needs explicit handling for numeric, categorical, and missing values.
- Imputation, encoding, and scaling must respect the training boundary.
- One-hot encoding represents categories without inventing numeric order.
- Class imbalance requires metrics and error analysis beyond headline accuracy.
- Baseline, logistic regression, tree, Random Forest, and boosting candidates should be compared under the same evidence rules.
- k-NN, Naive Bayes, SVM, Ridge, and Lasso are important classical families to recognize, but seeing them here is not the same as mastering them.
- After model settings are chosen from validation evidence, a fresh final model can be refit on the combined training and validation data before one untouched test evaluation.
- Reproducible pipelines make a comparison auditable but cannot repair an invalid prediction problem.
Next Lesson
You are ready for the Level Project, Trustworthy ML: Compare Models Without Cheating. The project carries this lesson forward with numeric and categorical columns, intentional missing values, a minority positive class, fitted preprocessing inside every candidate pipeline, and several classical model families compared without changing the split, leakage rules, or review standard.
References
- scikit-learn, ColumnTransformer for heterogeneous data.
- scikit-learn, Imputation of missing values.
- scikit-learn, OneHotEncoder.
- scikit-learn, Pipeline.
- scikit-learn, Common pitfalls and recommended practices.
- scikit-learn, Model selection and evaluation.
- scikit-learn, Nearest Neighbors.
- scikit-learn, Naive Bayes.
- scikit-learn, Support Vector Machines.
- scikit-learn, Linear models with coefficient regularization.
Completion is stored locally on this device.
Level project unlocked: Trustworthy ML: Compare Models Without Cheating