본문으로 건너뛰기
L1.18

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.

  1. Before clicking Run, find required_validation_recall = 0.70. Treat that as the review rule fixed in advance: a candidate must reach at least 0.70 validation recall to remain eligible.
  2. Click Run. Confirm that the first output repeats review rule: validation recall >= 0.7.
  3. Inspect numeric_columns and categorical_columns, then confirm that imputation, scaling, and one-hot encoding live inside preprocess.
  4. Read split sizes:. The fixture uses 72 training rows, 24 validation rows, and 24 final-test rows. Confirm that the output says final-test metrics: hidden during model selection.
  5. Read validation positives: and candidate validation true positives:. There are only 4 positive validation examples, and the balanced candidate finds 3, so validation recall is 3/4 = 0.75. It passes the rule fixed in step 1.
  6. Translate that metric back into examples: changing the outcome of one positive validation row would move recall by 1/4 = 0.25.
  7. Find class_weight="balanced" inside LogisticRegression. Change only "balanced" to None.
  8. 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.792 to 0.917 and precision from about 0.429 to 1.0, while recall falls from 0.75 to 0.50. The unweighted candidate therefore fails the precommitted recall rule.
  9. Press Reset so the selected class_weight="balanced" setting is restored. At this point, model selection is finished. The setting is fixed.
  10. Find show_final_test = False. Change only False to True, then click Run once. The Lab now creates a fresh clone of the selected pipeline, fits it on all 96 development rows (72 training + 24 validation), and only then evaluates the untouched final test.
  11. Read the block labeled FINAL TEST — do not use this result to tune the model:. It should show final training rows: 96, final-test positives: 4, and final-test true positives: 4. The final-test accuracy is about 0.833, precision is 0.500, and recall is 1.000 = 4/4.
  12. Treat 4/4 as 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.

FamilyLearning ideaWhat 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 BayesCombine 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 / LassoKeep 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​

ItemRecord
Datasource/revision and feature definitions
Splitstrategy, proportions, seed, grouping or time rule
Preprocessingcolumn roles, imputation, encoding, scaling
Candidatemodel family and important hyperparameters
Selectionvalidation method and selection metric
Final evidenceuntouched 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:

  1. define the prediction moment;
  2. reject future or target-derived features;
  3. keep final evaluation outside fitting and model selection;
  4. place learned preprocessing inside the fitting boundary;
  5. compare against a baseline;
  6. use metrics that expose important errors;
  7. inspect overfitting and concrete failures;
  8. state limitations.

Quick Check

1. Why should imputation and one-hot encoding be inside the fitted pipeline?
2. Why can accuracy be misleading on an imbalanced problem?
3. What makes a model-family comparison fair?
4. What does recognition-level coverage of k-NN, Naive Bayes, SVM, Ridge, and Lasso mean here?

0 of 4 questions answered.

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

Lesson actions

Completion is stored locally on this device.

Level project unlocked: Trustworthy ML: Compare Models Without Cheating

View progress