- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Machine Learning Workflow
The Machine Learning Workflow
IntermediateLesson 1 of 9 in Machine Learning Course
What you will learn
- Describe a data set in terms of examples, features, labels and models, tell supervised from unsupervised learning and regression from classification, and turn a practical question into a well-defined prediction task.
- Describe data with features, labels and modelsName the parts of a learning problem: the examples, the features, the label, the model that turns features into predictions, and the parameters it learns from training data.
- Tell supervised from unsupervised learningDecide whether a task has labeled examples to learn from, and match common tasks to supervised or unsupervised learning.
- Tell regression from classificationDecide from the label whether a supervised task is regression or classification, and recognize binary, multiclass and probability outputs.
- Turn a practical question into a prediction taskDefine the objective, the unit of prediction, the label and the moment of prediction, and check which information is available at that moment.
- Describe data with features, labels and models
- Explain why a model has to be judged on data it did not learn from, and create training, validation and test sets that match how the model will be used.
- Explain the roles of training, validation and test setsDescribe generalization and overfitting, and use each of the three data sets for its own purpose in the workflow.
- Split data randomly and reproduciblyChoose split proportions and create training, validation and test sets with scikit-learn, including stratified and repeatable splits.
- Split data that have a time order or groupsRecognize when a random split overstates performance, and split by time or by group so that the evaluation matches real use.
- Explain the roles of training, validation and test sets
- Use scikit-learn's common estimator interface to train and apply models, build simple baselines for regression and classification, and judge every model against them on validation data.
- Use the scikit-learn estimator interfaceCreate, fit and apply estimators with fit, predict, transform and score, and pass data in the shapes scikit-learn expects.
- Build a baseline for regression and classificationBuild constant and rule-based baselines from the training data and explain what a model has to beat to be useful.
- Compare models with a baseline on validation dataFit models and baselines on the same training data, compare them on validation data with the same measure, and read what the comparison says.
- Use the scikit-learn estimator interface
- Recognize when information that would not be available at prediction time reaches the model, and keep every fitted step and modeling decision inside the training data.
- Recognize target leakageIdentify features that reveal the label or are only known after the prediction moment, and fix them without discarding legitimate strong predictors.
- Keep fitted steps and decisions inside the training dataFit every preprocessing step on training data only, recognize leakage through preprocessing, splits and repeated test use, and know why pipelines prevent it.
- Recognize target leakage
- Chain preprocessing and a model into one pipeline, prepare numeric and categorical columns differently, and run the full workflow from raw table to a final test score.
- Chain steps with PipelineBuild a pipeline from transformers and a final model, explain what fit and predict do at each step, and access and change the steps' settings.
- Prepare numeric and categorical columns with ColumnTransformerApply different preprocessing to different columns, encode categories with one-hot encoding, handle missing values and unseen categories, and check which columns reach the model.
- Run the workflow from raw table to final test scorePut framing, splitting, the baseline, the pipeline and the final test together in the right order, and avoid the mistakes that break an honest result.
- Chain steps with Pipeline
Machine Learning Workflow study guide
1Turn a question into a learning task
A useful model starts with a clear question about real examples. The same table can support several tasks, depending on what you want to predict or discover. Identify the inputs and the outcome, decide what kind of learning fits, and pin down the moment when a prediction must be made. Those choices determine which columns can enter the model and what a successful result would help someone do.
1.1 Features, labels, and learned models
A machine learning model turns an example's input values into an output. Training, also called fitting, adjusts the model using data. You supply examples of the relationship you want it to learn instead of writing a separate rule for every possible case.
Read a table as a learning problem
A row is an example: also called an observation, instance, or sample. An input column is a feature, sometimes called a predictor or attribute. The label, or target, is the value you want to predict. These roles depend on the question, so choose them before preparing the table.
Suppose 500 buildings have records of floor area in m², occupants, heating type, region, and yearly energy use in kWh. To predict energy use, the first four columns form the feature table . Its shape is (500, 4): 500 examples and four features. The label contains one energy value for each row. Keep the label out of the feature table.
The usual notation is examples and features. For example , holds its feature values and is its observed label. A prediction is written , pronounced “y-hat.” A predicted value and an observed value play different roles even when their numbers happen to match.
What a model can learn
For a numeric label, write the relationship as:
Here is the average label value for examples with those features. The error averages zero at each feature value. It need not be independent of the features: for example, errors may have a wider spread for larger buildings. Training estimates this relationship with , and a new example receives the prediction .
Reducible error comes from estimating the relationship poorly. Better features or a better fitted model can reduce it. Irreducible error is the variation that remains at the same feature values. Two otherwise identical buildings can use different amounts of energy because their occupants behave differently. A model using only those features cannot recover the missing information. Classification has a similar limit when identical features occur with different class labels.
Separate learned values from chosen settings
Parameters are learned during fitting. In linear regression, they include the slope and intercept, stored as coef_ and intercept_. Hyperparameters control how fitting works and are chosen before a fit, such as the number of neighbors in a nearest-neighbor model. Compare settings on validation data; the fitting process then learns the parameters for each setting.
Prediction asks how well a model handles new cases. Inference asks how the outcome depends on features. A model chosen for accurate prediction may be hard to interpret; a good prediction alone does not explain why a feature and outcome are related.
An arbitrary row number is a poor feature: memorizing it gives no useful information about new rows. A meaningful entity ID needs a use-case check. A store ID may help predict a known store, but cannot establish performance on new stores. Text features and missing values also need suitable preparation before most estimators can use them.
Key Takeaways
- An example is a row; features are inputs; the label is the outcome to predict.
- Parameters are learned in a fit; hyperparameters are chosen settings.
- Reducible error can shrink with better modeling; irreducible error remains at fixed features.
- Prediction concerns new cases; inference concerns relationships between features and outcomes.
- Keep the label out of the features and check identifiers against the intended use.
1.2 Learn from labels or discover structure
The first choice is whether past examples have the outcome you want to learn. Supervised learning uses labeled examples to learn a mapping from inputs to outcomes. Unsupervised learning uses features without a target label to find structure in the data.
Decide from the question
An online shop has records for 20,000 customers. It can ask, “Will this customer buy again within 90 days?” For older records, those 90 days have passed, so the shop can attach a yes/no label. Learning to predict that label is supervised learning. A new customer's label is unknown when the prediction is made; that is exactly why a prediction is useful.
The same shop can ask, “Which customers have similar buying habits?” No correct segment is recorded in advance. An algorithm groups customers from their features, making this an unsupervised task. Having transaction data does not by itself make a task supervised. The decisive issue is whether the particular target outcome is recorded for the training examples.
| Setting | What the training data supplies | What the task seeks |
|---|---|---|
| Supervised | Features and known labels | A way to predict labels for new examples |
| Unsupervised | Features without a target label | Useful structure among the examples or features |
Recognize three unsupervised tasks
Clustering groups similar examples. A customer cluster might contain frequent buyers of a narrow product range. The cluster numbers 0, 1, and 2 are names assigned by the algorithm; they do not mean low, medium, and high value. A person must inspect the groups before giving them useful interpretations.
Dimensionality reduction replaces many features with fewer combined features that retain useful information. It changes the representation of the data. Anomaly detection looks for examples that differ from the usual pattern, such as an unusual sensor reading. A flagged anomaly still needs interpretation: unusual does not necessarily mean faulty.
Classification and clustering are easy to confuse because both can output group labels. Classification learns categories defined in advance from labeled examples. Clustering forms groups from similarity without those known category answers.
Check results in a way that fits the task
For supervised learning, compare predictions with known labels held out from training. For unsupervised learning, there is no supplied correct target for each example. Use criteria matched to the task and domain knowledge. Clusters can be checked for compactness and separation, reduced features for retained information, and flagged anomalies through expert inspection. A grouping that is mathematically neat can still be unhelpful for the decision.
Labels can be expensive or slow to obtain. People may need to annotate examples, or the project may have to wait for a future outcome. Semi-supervised learning combines a small labeled collection with many unlabeled examples. Reinforcement learning is another setting: an agent learns actions from rewards, as in robot control or game playing. It does not learn solely from a fixed table of correct target answers.
Key Takeaways
- Supervised learning uses known training labels; unsupervised learning finds structure without target labels.
- Clustering forms groups; classification predicts predefined classes.
- Judge unsupervised results with task-specific checks and domain knowledge.
- Semi-supervised learning mixes labeled and unlabeled examples; reinforcement learning uses rewards.
1.3 Choose a numeric outcome or a class
Once a task is supervised, inspect the meaning of its label. Regression predicts a quantity on a numeric scale. Classification predicts membership in a fixed set of categories. The file's storage type does not decide which task you have.
Ask what a difference between labels means
Energy use in kWh, delivery time in minutes, and maximum temperature in °C are numeric quantities. A difference of 5 minutes has a meaningful size, so predicting a delivery's duration is regression. A depot code such as 1, 2, or 3 names a category. The difference between depot codes does not measure how far apart the depots are.
| Question about a delivery | Label | Task |
|---|---|---|
| How many minutes will it take? | Duration | Regression |
| Will it be more than 10 minutes late? | Late or on time | Binary classification |
| Which of four depots will handle it? | Depot name | Multiclass classification |
Binary classification has two classes; multiclass classification has more than two. The positive class is the class of interest. In fraud detection, “fraud” can be positive even though fraud is undesirable. The name identifies which outcome you are tracking, not a value judgment.
Distinguish a class from its probability
A classifier can return a predicted class or estimated probabilities. An email model might estimate a 0.83 probability of spam. predict_proba returns class probabilities, while predict returns a class label. Check the fitted estimator's classes_ to know which probability column belongs to which class.
For many classifiers, including logistic regression, the predicted class is the one with the highest estimated probability. In a binary task this corresponds to a 0.5 boundary, apart from how a tie is resolved. A probability is a numeric output, but the underlying outcome is still class membership. Logistic regression is a classifier despite its name; linear regression predicts a numeric quantity.
Choose the framing that supports the decision
Changing duration into “late” or “on time” loses information. A delivery 11 minutes late and one 3 hours late become identical labels under a “more than 10 minutes late” rule. That framing fits a decision concerned only with whether the threshold is crossed. If the amount of delay matters, preserve a numeric target.
Some outcomes allow more than one useful framing. A rating from 1 to 5 can be treated as a number, allowing a prediction such as 3.6 and preserving order. A standard classification framing treats each rating as a separate class and does not by itself express that 4 is closer to 5 than to 1. State how the prediction will be used before choosing.
The label also guides the first comparison. Regression needs an error measured by distance from the observed value, such as minutes off. Classification can begin with the fraction of correct class predictions. A constant numeric baseline predicts a training-label mean or median; a constant classification baseline predicts the most frequent training class.
Key Takeaways
- Choose regression or classification from what the label means, even when categories are stored as numbers.
- Binary tasks have two classes; multiclass tasks have more than two.
- Class probabilities are different from class labels, and logistic regression is a classifier.
- Turning a quantity into categories loses its size information.
- The prediction must suit the decision it will support.
- Match the baseline and comparison measure to the task type.
1.4 Define one prediction precisely
A broad aim such as “reduce cancellations” is not yet a prediction task. Start with the action someone will take. Then define one example, a measurable outcome, and the moment when the prediction is needed.
Write a task statement
A streaming service sends retention offers once a month. One useful task is: “For each active subscriber on the first day of the month, predict whether they cancel within the next 30 days, using account data up to the end of the previous day.”
This statement fixes three things:
- The unit of prediction is one subscriber on one monthly date. The same subscriber can appear on several dates.
- The label is cancellation in the following 30 days, recorded as yes or no.
- The prediction time is the first day of the month, before the offer decision.
The task is supervised binary classification. Old monthly records become labeled examples once their following 30 days have elapsed. A vague target such as “unhappy” would need a measurable definition before it could become a label.
Build the feature timeline
For each candidate feature, ask when its value becomes known. Viewing hours in the previous 30 days, the current plan, and months subscribed are available for the monthly decision. Support calls made during the following 30 days are not. An accurate historical table can still contain information that arrived too late for the prediction.
Use the values that existed before that monthly prediction. A database's current account status may have been updated after cancellation. Reconstructing a historical task from today's table requires care: a column name alone does not tell you when its stored value was available.
Define the comparison before fitting
Find the existing way of doing the job. Perhaps the service already flags accounts with no viewing in 14 days. That rule is a natural baseline because the model is meant to improve the same decision. Agree on success before looking at results. With a fixed number of monthly offers, success could mean reaching more subscribers who later cancel than the existing rule reaches.
A prediction is useful only when it can inform an action. If the task is applying the exact rule “parcels over 30 kg go by freight,” a learned approximation adds little. If outcomes were never recorded, a supervised model cannot simply learn the missing answers from a feature table. The project may first need to collect labels or ask a different question.
Check who and what the data represents
A table drawn from one country or an old set of subscription plans may leave out situations the model will face. Count both the rows and the important outcomes. If 2% of 10,000 subscribers cancel, there are about 200 cancellation examples, not 10,000 examples of cancellation. Splitting that table will leave fewer cancellations for training and evaluation.
Record the action, row definition, outcome window, feature cutoff, current method, and success criterion together. They provide concrete checks when a later choice of feature, split, or baseline looks attractive.
Key Takeaways
- Define the action, unit of prediction, measurable label, and prediction time.
- Build features from values available before the prediction moment.
- Use the current method as a baseline and agree on success before modeling.
- Check representation and the count of important outcomes, not just total rows.
2Create splits that match real use
A model needs a fair chance to learn and an honest test on new cases. Separate the data used for fitting from the data used for choices and final reporting. Random splits work for independent examples, but forecasts and repeated records need a different design. Learn to choose the split from the intended use, preserve feature-label alignment, and make the result reproducible without searching for a lucky shuffle.
2.1 Training, validation, and the final test
Generalization means predicting well for examples beyond those used to fit the model. A training score describes how the fitted model handles familiar examples. It cannot, by itself, establish how well it will handle new ones.
Give each set one job
| Set | Its role | What it may influence |
|---|---|---|
| Training | Fit parameters and preprocessing | Learned coefficients, means, categories, and other fitted values |
| Validation | Compare candidates during development | The chosen model, hyperparameters, and preprocessing design |
| Test | Evaluate the final choice | The reported estimate after choices are fixed |
Fit on training data, predict validation data, and compare results. Change a setting, fit again on training data, and compare again on the same validation data. The validation set influences the eventual choice through your decisions even though its rows are not passed to the model's fit method.
Recognize two kinds of poor fit
Overfitting occurs when a model learns quirks and noise in its training examples. It can have very low training error and much higher error on new data. A model that memorizes a lookup table may answer every training example perfectly while having no useful rule for an unfamiliar row.
Underfitting occurs when a model is too simple to capture the pattern. It performs poorly on both training and new data. When both scores are close to a weak baseline, also check feature quality and code: the score pattern alone does not identify the cause.
Why validation cannot be the final estimate
Imagine comparing 50 models with the same true predictive ability. Their validation scores still vary because the particular validation examples favor some predictions over others. Selecting the highest score selects some good luck as well as model quality. The winning validation score can therefore be optimistic.
An untouched test set evaluates the chosen model without having selected it. This protection depends on leaving the test out of every earlier choice. It is lost if you change the model because the test score disappointed you. Repeatedly checking the same test and keeping improvements makes it another development set; an independent final estimate then needs fresh untouched data.
Finish development before opening the test
After selecting the settings, it is common to refit on training and validation data together. Those extra examples can help estimate the parameters. The settings are fixed first; the test set remains excluded. Compare the final model and its baseline on the test set and report the result.
With little data, cross-validation can replace one fixed validation set: different parts take turns providing validation examples. A separate final test still has the same role. Whichever development method is used, a test score estimates performance for cases like the test examples. Changed customer groups, products, or conditions can make future performance different.
Key Takeaways
- Training fits parameters; validation guides choices; the test estimates final performance.
- Overfitting gives a strong training result and a much weaker result on new data.
- Trying many candidates can make the winning validation score optimistic.
- Fix the settings before any final refit and test evaluation.
- Repeated test-based changes require fresh data for an independent final estimate.
2.2 Make reproducible random splits
For independent rows drawn from the use case, a random split can give training and held-out sets from the same mix of examples. Choose proportions that leave enough data to learn and enough held-out cases to obtain stable comparisons. There is no universally correct ratio.
Make three parts with two calls
Common starting ratios include 60/20/20, 70/15/15, and 80/10/10. With millions of examples, even 1% can supply tens of thousands of evaluation cases. The useful counts depend on the task, including how many examples of a rare class remain in each part.
train_test_split shuffles by default. Pass features and labels together so each label follows its row:
from sklearn.model_selection import train_test_split
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, random_state=42
)
With 10,000 rows, the first call reserves 2,000 for testing and leaves 8,000. The second call reserves a quarter of those 8,000, giving 2,000 validation and 6,000 training rows. Using 0.2 in both calls would instead give 6,400/1,600/2,000. The second fraction is relative to the remaining data, not the original table.
If neither size argument is provided, the test fraction defaults to 25%. A two-way split of 1,000 rows then gives 750 training and 250 test rows. Return values come in the order feature parts first, then matching label parts.
Preserve the pairing and the split
An integer random_state=42 makes the shuffle repeatable for the same input and settings. It lets you compare changes using the same rows. A seed does not make a split representative or free from leakage. Trying seeds and keeping the best score selects a favorable evaluation sample.
Separate feature and label calls can align when row order, settings, and integer seed all match. One call is safer: sorting one input, changing a size, or omitting a seed can otherwise pair features with the wrong outcomes without an obvious error.
A fixed seed does not preserve membership when new rows are added. Save the test IDs or use a stable assignment based on an unchanging unique ID. This keeps familiar test cases from moving into training during a later rerun.
Keep important proportions with stratification
For classification, stratify=y preserves class shares approximately. With 50 spam emails among 1,000 emails, a 20% stratified test has 10 spam among 200 messages. A plain random test count varies; about one split in ten has 5 or fewer, or 15 or more, spam examples. Small class counts can make scores unstable even when the total set seems large.
For the three-way classification split, pass stratify=y in the first call and stratify=y_rest in the second. Stratification is not limited to labels: a regression task can split on income bands to preserve an important feature's proportions. It does not resolve time order or repeated-entity dependence; those need a split designed for that structure.
Key Takeaways
- Choose split counts for learning and stable evaluation; no ratio fits every task.
- The second split fraction applies to the remainder.
- Split features and labels together, and record the seed.
- Stratification preserves approximate class or band proportions.
- Save test membership when a data set grows; a fixed seed alone is insufficient.
- Do not select a seed because it produces a high score.
2.3 Keep future periods and new entities separate
Random splitting can make an evaluation too easy when rows are linked. Several readings from one sensor, repeated images of one patient, or neighboring days in a forecast can share information that new cases will not share. Choose the boundary that matches what “new” means for the intended prediction.
Forecast later periods from earlier ones
For a model that will predict the future, train on the earliest period, validate on a later period, and test on the latest. Daily sales from 2021 through 2025 could use 2021–2023 for training, 2024 for validation, and 2025 for testing. Each evaluation then asks the model to move forward in time.
A random split can train on days after a test day. It may also place nearly identical neighboring days on opposite sides of the split. A good score in that arrangement can reflect access to surrounding or future information that a real forecast would lack.
Sort by time and select date ranges explicitly. train_test_split(..., shuffle=False) can also separate consecutive rows, provided the input has already been sorted correctly. Turning off shuffling on an unsorted table does not create a chronological evaluation.
Evaluate on new groups when that is the task
If the model must handle new people, customers, or sensors, keep every row from an entity in one set. The entity identifier is the group. A group split tests whether the model transfers beyond entities it has already seen.
Consider 2,000 images from 400 patients, five per patient. A random image split can place one patient's images in both training and test. A 20% patient-level test instead holds out 80 patients and their 400 images, leaving 320 patients and 1,600 images for development. Equal images per patient make the row fraction match the group fraction here.
GroupShuffleSplit accepts a groups argument and holds out whole groups. Its size fraction refers to groups; with unequal numbers of rows per group, the row fraction need not match. After setting aside test groups, split the remaining groups again for training and validation. GroupKFold is the corresponding named option for grouped cross-validation.
Match the use case, not a blanket rule
| Intended prediction | Appropriate boundary |
|---|---|
| First prediction for an unseen patient | Patient groups kept separate |
| Next month's demand | Earlier and later periods kept separate |
| Next month for existing customers | Time boundary; customers may appear in several periods |
Exact duplicate records should be removed or kept together. Otherwise evaluation can include an example the model has already seen. Grouping by customer is not always the right answer: if the real task is predicting those same customers next month, preventing all repeat customers changes the question.
Finally, inspect feature construction. A time split does not fix a feature calculated from the whole time span. An average that includes future days leaks future information even when rows are in chronological order. Each historical row needs features calculated from the history available before its own prediction time.
Key Takeaways
- For forecasts, train earlier, validate later, and test latest.
- For unseen entities, keep each entity entirely within one set.
- Group proportions describe groups and can differ from row proportions.
- Remove duplicate records or keep their copies together.
- Both the split and feature construction must respect prediction time.
3Fit models and compare them with a baseline
Scikit-learn gives many models the same small set of methods, so learning the workflow transfers across algorithms. Create an estimator, fit it on training examples, and apply it to held-out rows. A baseline makes the resulting score meaningful: it shows what a simple prediction already achieves. Compare candidates on the same validation cases and measure, then use the score pattern to decide what to investigate next.
3.1 Use the estimator methods and data shapes
A scikit-learn estimator is an object that learns from data through fit. Its constructor sets hyperparameters. After fitting, a predictor produces outputs and a transformer changes the representation of the inputs.
Create, fit, and predict
A simple numeric model follows this pattern:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_val)
fit(X_train, y_train) learns from matching feature rows and labels. predict(X_val) returns predictions using those learned values. Supervised estimators use labels in fitting; unsupervised estimators generally fit from X alone. fit returns the estimator, so model = LinearRegression().fit(X_train, y_train) is also valid.
For most estimators, another fit starts a fresh fit. It is not an evaluation method. Calling it on validation data changes what the model has learned and removes the held-out role of those examples.
Keep the feature input two-dimensional
A feature table has shape (n_samples, n_features), including when there is only one feature. For a single target, the label vector has one value per example.
X = df[["floor_area_m2"]]
y = df["energy_kwh"]
The double column selection returns a one-column DataFrame. A single column selection for X returns a one-dimensional Series, which LinearRegression rejects as a feature table. For one new building, pass a table with one row and the same feature columns, not a bare number.
Inspect what was learned
Suppose training floor areas are 50, 100, and 150 m², with energy use 4,000, 7,000, and 10,000 kWh. Each extra 50 m² adds 3,000 kWh, so the fitted slope is 60 kWh per m². The intercept is 1,000 kWh. For 120 m²:
Learned attributes end with an underscore. Here coef_ contains the one slope, 60, and intercept_ is 1,000. A scaler stores learned values such as mean_ and scale_. Prediction or transformation before fitting normally raises NotFittedError because the needed learned values do not yet exist.
Choose the method for the job
| Method | Job |
|---|---|
fit | Learn from the supplied data |
predict | Return predicted labels or numeric outcomes |
predict_proba | Return class probabilities when supported |
transform | Apply a learned data transformation |
fit_transform | Learn a transformation and apply it to those same rows |
score | Compute the estimator's default evaluation measure |
Use fit_transform on training inputs and only transform on held-out inputs. The latter reuses the training statistics.
For standard classifiers, score gives accuracy; for standard regressors it gives . These are different measures. Compute MAE explicitly when that is your chosen regression comparison. Hyperparameters remain accessible through get_params() and can be changed with set_params(...) before another fit.
Key Takeaways
- Create an estimator, fit on training data, then predict held-out examples.
- Use a two-dimensional feature table even for one feature.
- Attributes ending in an underscore store learned values.
- Fit transformers on training inputs and transform held-out inputs without refitting.
- A default regression score is R², so calculate MAE explicitly when comparing by MAE.
3.2 Set a useful baseline
A baseline is a simple, reasonable prediction method used as the reference for a model. It answers, “What can we already achieve without this more complex approach?” A high-sounding score is useful only after that comparison.
Start with constant regression predictions
Two common constant baselines predict the training-label mean or median for every example. The mean minimizes squared error among constant predictions on the training labels. The median minimizes absolute error among constant predictions. That does not guarantee either has the lowest error on a particular held-out sample.
from sklearn.dummy import DummyRegressor
mean_baseline = DummyRegressor()
median_baseline = DummyRegressor(strategy="median")
mean_baseline.fit(X_train, y_train)
Both estimators ignore feature values. They still receive X so their interface matches other predictors, but their fitted prediction comes from the training labels.
Training delivery times of 22, 35, 28, 40, and 25 minutes sum to 150. The mean is 30 minutes; sorting them gives a median of 28 minutes. The mean baseline predicts 30 for every validation delivery. If observed validation times are 26, 38, 31, and 24 minutes, its absolute errors are 4, 8, 1, and 6 minutes:
The result is 4.75 minutes, in the same units as the label. Positive and negative errors must not cancel when computing this average error size.
Use the class proportions for classification
A constant classifier predicts the most frequent training class:
from sklearn.dummy import DummyClassifier
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)
If 98% of payments are legitimate, always predicting “legitimate” gets 98% accuracy on a set with that same class mix. It catches no fraud. A classifier with 97% accuracy is worse by this measure, even though 97% sounds high.
Uniform random guessing in a binary task has expected accuracy of 50%, but it is a weak reference when the classes are imbalanced. Use the most-frequent-class baseline to expose what the class mix alone makes possible. Its held-out accuracy depends on the class mix in the held-out set, not just the training share.
The default DummyClassifier() uses strategy="prior". Its class predictions match the most-frequent strategy. Its probability output gives training class proportions; "most_frequent" instead places all probability on the selected class.
Compare against the existing method too
For a forecast, “tomorrow equals today” is a persistence baseline. A known business rule can also be a strong reference. A simple fitted model on a few sensible features is a useful next baseline before adding complexity.
Learn a constant baseline from training labels only. Computing the mean from the whole table lets held-out labels shape the supposed reference prediction. Keep its training and evaluation boundaries the same as those of the candidate models.
Key Takeaways
- A baseline establishes what a simple method already achieves.
- Mean and median constant regressors learn only from training labels.
- The most frequent class is a useful accuracy baseline for imbalanced classification.
- The default classifier prior strategy returns training proportions as probabilities.
- Existing rules and persistence forecasts can be stronger references than constants.
- Match the baseline to the same fitting and evaluation boundaries as the model.
3.3 Read a fair validation comparison
A fair model comparison keeps the task, data, and measure fixed. Fit every candidate and its baseline on the same training examples. Predict the same validation examples and compute the same measure for each.
Calculate the comparison
Mean absolute error (MAE) averages the sizes of numeric prediction errors. Lower is better, and the unit matches the label. Accuracy is the fraction of predicted classes that match the observed classes. Higher is better. Use the measure suited to the framed task.
For validation deliveries taking 26, 38, 31, and 24 minutes, suppose a model predicts 27, 35, 30, and 26 minutes. Its absolute errors are 1, 3, 1, and 2 minutes:
The mean baseline's MAE on those same deliveries is 4.75 minutes. The reduction in average error is 3 minutes. Relative to the baseline:
This is an error reduction, not “63% accuracy.” Regression error and classification accuracy describe different things.
Use code that makes the measure explicit
from sklearn.metrics import mean_absolute_error
base_mae = mean_absolute_error(
y_val, mean_baseline.predict(X_val)
)
model_mae = mean_absolute_error(
y_val, model.predict(X_val)
)
For a classifier, use accuracy_score(y_val, model.predict(X_val)). Do not compare a regressor's default score with a baseline's MAE: the first is , and a larger value means something different.
Read the size and pattern of the gap
Small differences can depend on the particular evaluation cases. In a validation set of 200 rows, one extra correct prediction changes accuracy by 0.5 percentage points. A comparison of 90.0% with 90.5% is a one-prediction gap. A larger validation sample or cross-validation can give a steadier comparison before treating that lead as meaningful.
Compare training and validation results as well. A much stronger training score suggests overfitting. Both results near a weak baseline suggest underfitting, weak information in the features, or a code problem. A result below the baseline calls for checking row-label alignment, the target column, preprocessing, and feature usefulness before reaching for a more complex model.
An almost perfect validation result can also be a warning. Inspect the feature timeline and split for leakage, especially when the score exceeds what subject experts expect. A high score alone cannot tell you whether the process was honest.
Keep decisions traceable
Record each model, hyperparameters, preprocessing choices, training result, and validation result beside the baseline. Change one aspect at a time when possible so you can identify what helped. The test set stays out of this development log until the final model and settings are fixed. The eventual report gives the final test result alongside the baseline's test result on the same test examples.
Key Takeaways
- Compare the same held-out rows with the same measure after fitting on the same training data.
- Lower MAE is better; higher accuracy is better.
- An error reduction is not an accuracy score.
- Small score gaps can reflect a few validation examples.
- Use the training-validation gap and the baseline to guide debugging.
- Log experiments and leave the test set out of model selection.
4Find and prevent data leakage
A model can appear excellent because its inputs or fitting process contain answers it would never have in real use. Leakage can enter through a late-recorded feature, a preprocessing statistic, a repeated entity, or a choice guided by test scores. Learn to trace information back to when and where it became available. A sound repair restores the prediction timeline and the separation between learning and evaluation.
4.1 Check every feature against prediction time
Data leakage occurs when information that is not legitimately available for the intended prediction enters the learning process. It can make evaluation results look much better than results on genuinely new cases. Target leakage enters through features that reveal the label or its aftermath.
Trace the feature's history
A bank predicts loan default at application time. Its model reaches 99% accuracy, and its strongest input is “number of collection letters sent.” Those letters are sent after missed payments. The historical count describes what happened after the decision, so it cannot be a feature for the application-time task. At application, the count of letters for that new loan is zero.
The label itself may legitimately be observed later; training needs completed historical outcomes. The feature values must still describe the earlier prediction moment. Mixing a later label with earlier features is how a supervised forecast is built. Mixing later features into those earlier rows leaks the future.
Apply the timeline test
For each proposed input:
- Identify the prediction moment for this row.
- Identify when the value first became known.
- Check whether the stored field was later updated.
- Keep the feature only when the value used was fixed before the prediction moment.
For example, “last login date” may now show a login after the monthly prediction. An account's “current status” may already record its cancellation. Extracting today's database values for historical rows does not recreate the past.
A snapshot records the information as it stood at a particular time. Building each row from the appropriate snapshot avoids many of these errors. Where historical records exist, an as-of feature uses only records available before that row's cutoff.
Look for disguised labels
A feature does not need the target's name to reveal it. A cancellation reason recorded only for canceled accounts can expose the answer through its presence or absence. A diagnostic treatment recorded after a diagnosis can similarly disclose an outcome the model is supposed to predict beforehand.
A column that is empty for one class and filled for another deserves investigation. So does a single feature that appears to explain almost every answer. These patterns are warning signs, not reasons to delete a column without understanding its meaning and timing.
Repair the information, not just the score
Remove the collection-letter count for the new loan. If useful history exists, replace it with “late payments on earlier loans before this application date.” That is a different feature: it describes prior behavior legitimately available at the decision. Rebuild the historical rows with that cutoff and reevaluate.
A strong predictor can be entirely legitimate. Last year's energy use is available before predicting this year's use. Its strength does not make it leakage. Decide from the task, timing, and meaning of the field.
If a model performs far worse on fresh cases than in validation, investigate this timeline alongside the split. A pipeline cannot turn a late-recorded feature into an early one; the feature table itself must first represent the information the real prediction would have.
Key Takeaways
- Target leakage uses a label-revealing or late-recorded feature.
- Historical labels may be known later; historical features must respect the earlier prediction cutoff.
- Inspect updates, missingness patterns, and the meaning of unusually strong features.
- Repair features with historical snapshots or an as-of cutoff.
- A strong feature is legitimate when its information was available for the intended prediction.
4.2 Keep held-out information out of fitting
Leakage can occur even when every column was available on time. Train–test contamination occurs when a fitted step learns from held-out rows before evaluation. The feature values themselves can leak information, even without using held-out labels.
Split before learning preprocessing
Imputers learn fill values. Scalers learn means and spreads. Encoders learn categories. Feature selection, dimension reduction, and learned outlier cutoffs also absorb information from the data passed to fit. Fit them on training rows only, then apply the learned transformation to validation, test, and new rows.
Suppose training measurements are 30, 50, and 40 kg. A mean imputer learns 40 kg. Held-out measurements are 100, 120, and one missing value. Fitting on every known value would instead give:
That 68 kg fill value depends on the held-out inputs. The correct missing held-out value is filled with the 40 kg mean learned from training.
Reuse one scale
Training values 10, 20, and 30 have mean 20. StandardScaler uses a standard deviation calculated with division by the number of training values:
A held-out value of 40 is transformed with those training statistics:
Refitting on held-out values both lets them influence preprocessing and gives them a different coordinate scale. transform applies the training scale without relearning it.
Keep feature selection within the boundary too
With thousands of random features, some will correlate with a random label by chance. Selecting the most related features using all labels before splitting gives the selection process access to test answers. A simulation with 200 rows and 10,000 noise features produced roughly 80% test accuracy when selection used all rows, compared with roughly 50% when selection used training rows only. The apparent skill came from the selection process seeing the held-out answers.
Merely leaving y_test out of a final model's fit is therefore insufficient. Every earlier fitted choice must obey the same boundary. Include those steps in the object that is fitted.
Protect decisions and splits
Human decisions can absorb test information too. Inspecting test patterns to choose features is data snooping. Repeatedly changing a model to improve its test score uses the test as validation. Use development data for those choices, and reserve the test for the final fixed procedure.
Repeated entities and future periods can also cross a random split. Keep unseen entities in separate groups and use chronological boundaries for forecasts. A pipeline does not choose those boundaries for you.
A Pipeline fits its preprocessing and model on the rows passed to its fit. At prediction it transforms new inputs using the learned training values. Put every fitted preparation step inside it and pass only training data during development. If a scaler was already fitted on the full table, wrapping the model afterward leaves the contamination in place.
Key Takeaways
- Split before learning imputation, scaling, encoding, or feature selection.
- Transform held-out inputs using values learned from training.
- Feature selection can leak test labels before model fitting even starts.
- Test-guided human choices also contaminate final evaluation.
- A pipeline protects included fitted steps only when its fit receives the proper training data.
- Time and group boundaries still require an appropriate split.
5Build and run one complete pipeline
A pipeline keeps preprocessing and prediction together, so every new row follows the same fitted path. Real tables need different preparation for numeric and categorical columns, followed by a model that can consume the combined output. Build those branches explicitly, check which columns reach the estimator, and run the whole workflow through baseline comparison, final refitting, and one untouched test evaluation.
5.1 Chain fitted steps with Pipeline
A scikit-learn Pipeline is a sequence of named steps that behaves as one estimator. Every step before the last must transform data. The final step is usually a predictor. This lets the same object fit a complete learning procedure and predict from raw feature rows.
Build the chain
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = Pipeline([
("scaler", StandardScaler()),
("model", LogisticRegression())
])
The scaler learns a mean and standard deviation for each numeric feature. The classifier learns from the scaled output. This simple chain assumes the supplied features are numeric and do not require imputation.
make_pipeline(StandardScaler(), LogisticRegression()) constructs the same sequence with automatic names: "standardscaler" and "logisticregression". Choose explicit names when shorter names make inspection and settings easier to read.
Follow a fit through the steps
When you call pipe.fit(X_train, y_train), the pipeline fits and transforms the training features at each intermediate step. It passes the transformed output to the next step, then fits the final model. A pipeline with an imputer, scaler, and model first fills gaps using training values, then learns the scale of that filled training table, then fits the predictor.
At pipe.predict(X_val), intermediate steps only transform. They do not fit again. The final predictor receives the transformed validation table and returns predictions. Labels are not needed to generate predictions.
Suppose a fitted scaler learned mean 20 and standard deviation about 8.165 from values 10, 20, and 30. A validation value of 40 becomes about 2.449 on that scale. The pipeline reuses those training statistics even if the validation values have a different mean. That is the intended test of a procedure learned from training.
Inspect steps and change settings
A fitted step can be reached by name or position:
pipe.named_steps["model"]
pipe["model"].coef_
pipe[-1]
The first and last expressions select the model; the middle one reads its learned coefficients. Names also provide a path to hyperparameters. The step name, two underscores, and the parameter name identify a setting:
pipe.set_params(model__C=0.5)
pipe.fit(X_train, y_train)
C is a hyperparameter of the classifier. set_params changes the setting; the subsequent fit learns the model for that setting. This naming scheme can address preprocessing settings as well as model settings.
Include all learned preparation
The leakage protection comes from fitting the entire chain on the correct rows. Fitting a scaler on the whole table before making a pipeline has already used held-out information. Put the scaler itself inside the pipeline instead.
The chain also keeps transformations consistent: new tables enter through the same path as validation and test tables. It cannot check whether a feature was recorded after the outcome, whether a random split mixes patients, or whether you selected settings using test results. Those decisions define the data the chain receives.
Key Takeaways
- Intermediate pipeline steps transform data; the final step usually predicts.
- Pipeline fit learns preprocessing and the model from the supplied training data.
- Pipeline predict reuses fitted transformations on new inputs.
- Use named steps for inspection and step__parameter names for settings.
- Place every learned preparation step inside the fitted chain.
5.2 Prepare mixed columns with ColumnTransformer
A raw table often combines numeric measurements and text categories. A ColumnTransformer applies separate transformations to selected column groups, then places their outputs side by side for the model.
Define numeric and categorical branches
A numeric branch can fill missing values with the median and then scale each column. The median is less sensitive to extreme values than the mean, which is SimpleImputer's default strategy. Scaling matters for models that use distances or penalties.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
num_pipe = make_pipeline(
SimpleImputer(strategy="median"),
StandardScaler()
)
cat_pipe = make_pipeline(
SimpleImputer(strategy="most_frequent"),
OneHotEncoder(handle_unknown="ignore")
)
preprocess = ColumnTransformer([
("num", num_pipe, ["floor_area_m2", "occupants"]),
("cat", cat_pipe, ["heating_type", "region"])
])
The categorical branch fills gaps with the most frequent training category before encoding. Each branch is fitted only when the containing procedure is fitted on training data.
Follow one-hot encoding
One-hot encoding creates one 0/1 column for each learned category. With heating categories electric, gas, and heat pump, a gas building becomes 0, 1, 0 across those columns. If training contains three heating categories and four regions, the two numeric columns plus the encoded categories produce nine columns:
get_feature_names_out() identifies the output columns. Typical names include num__floor_area_m2 and cat__heating_type_gas. The default encoder sorts categories, so do not infer column meanings from the order in which categories happened to appear in the raw rows.
With handle_unknown="ignore", an unseen heating category such as district heating gets zeros in all three heating columns. It does not create a fourth column or get assigned to gas. The default unknown-category behavior is an error. Ignoring unknown categories keeps prediction possible, but it gives the model no newly learned effect for that category.
Check which columns survive
The default remainder="drop" discards columns not listed in any branch. This can intentionally exclude an identifier, but it can also remove a useful column you forgot to list. remainder="passthrough" preserves unlisted columns unchanged and can accidentally admit an ID or a leaky feature.
Lists of column names are explicit. make_column_selector(dtype_include="number") can select numeric columns by type, but a numeric ID would qualify too. Always inspect the columns that actually reach the model.
Assigning unordered regions codes 1, 2, and 3 in one linear-model feature imposes equal output steps between neighboring codes. The regions have no such numeric spacing. One-hot encoding avoids that assumption. Even ordered categories such as small, medium, and large need defensible spacing before integer codes serve as a quantitative scale.
Finish by placing the column transformer inside a model pipeline: Pipeline([("prep", preprocess), ("model", LinearRegression())]).
Key Takeaways
- ColumnTransformer prepares selected groups separately and combines their outputs.
- Impute numeric and categorical gaps with appropriate training-derived values.
- One-hot encoding creates category indicator columns without an artificial numeric ordering.
- An ignored unseen category becomes all zeros within that feature’s learned columns.
- Check output names and the remainder setting for missing or unwanted columns.
- Fit the column transformer inside the pipeline with the model.
5.3 Run from a raw table to a final report
Combine the workflow in the order that protects the final evaluation. Define the decision and prediction time, select legitimate inputs, split the data, and build the baseline and pipeline. Development choices use validation results; final reporting uses the untouched test.
Separate inputs and outcomes, then split
For independent building records, suppose df contains the feature columns used in preprocess, an ID, and energy use:
X = df.drop(columns=["energy_kwh", "building_id"])
y = df["energy_kwh"]
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, random_state=42
)
The label and arbitrary ID are excluded. Use a time or group split instead when the intended use requires it. These calls reserve 20% for validation and 20% for testing, with 60% for training.
Fit and compare
from sklearn.metrics import mean_absolute_error
from sklearn.dummy import DummyRegressor
baseline = DummyRegressor().fit(X_train, y_train)
pipe = Pipeline([
("prep", preprocess),
("model", LinearRegression())
]).fit(X_train, y_train)
baseline_mae = mean_absolute_error(
y_val, baseline.predict(X_val)
)
pipeline_mae = mean_absolute_error(
y_val, pipe.predict(X_val)
)
A baseline validation MAE of 2,400 kWh against a pipeline MAE of 1,100 kWh means an average-error reduction of 1,300 kWh, about 54%. After checking the features and split for leakage, this is evidence that the pipeline improves on a constant prediction for the validation task.
Change one design choice at a time and log its training and validation scores. A different imputation strategy, input feature, or estimator belongs in this loop. Keep the test set closed while comparing these candidates.
Fix settings, refit, and test once
After choosing the final design, training and validation data can be combined for a fresh fit. X_rest and y_rest already contain exactly those rows in this random-split example:
pipe.fit(X_rest, y_rest)
baseline.fit(X_rest, y_rest)
test_mae = mean_absolute_error(
y_test, pipe.predict(X_test)
)
baseline_test_mae = mean_absolute_error(
y_test, baseline.predict(X_test)
)
Refitting the baseline on the same development data keeps the final comparison aligned. No settings are changed in response to the test result. A disappointing test result is still the result of the fixed procedure; revising after seeing it needs fresh untouched data for another independent final estimate.
Report both test scores, their units, the split design and proportions, and the seed where relevant. State whether examples were independent, held out by group, or separated by time so someone can understand what the result estimates.
The fitted pipeline can now predict a new table with the same feature columns: pipe.predict(new_df). It fills gaps, scales values, and encodes categories using what the final fit learned. New labels are unnecessary for prediction; they are needed later to assess how those predictions performed.
Key Takeaways
- Frame the task and choose valid inputs before splitting and fitting.
- Compare the baseline and complete pipeline on validation data.
- Fix settings before refitting on training plus validation data.
- Evaluate the final model and baseline on the same untouched test set.
- Report scores together with units and the split design.
- Pass new raw feature tables through the fitted pipeline.
Machine Learning Workflow examples
1Frame a prediction before choosing a model
16 steps
- 1IntroductionBegin with the decision
A table does not tell you which model to build. First decide what a prediction would help someone do.
Follow a small building example from rows and columns to a precise outcome. Then compare it with a task that has no target labels; learning from known labels is supervised learning. You will identify the information a model learns from and the answer it predicts (the label), choose a numeric (regression) or categorical outcome, and set the time cutoff that makes the prediction useful.
- 2ExampleFind the inputs and the outcome
A building table has 500 rows and five columns: area in m², occupants, heating type, region, and yearly energy use in kWh. The task is to predict energy use.
Each building is an example. Four columns are input features; energy use is the label. The feature table has shape (500, 4), and the label vector has 500 matching values. Including energy use among the inputs would give the model its own answer.
- 3ExplanationSeparate fitting from choosing settings
A model is a function learned from examples. Fitting learns its parameters, such as a line's slope and intercept.
A hyperparameter is chosen before a fit and controls learning, such as a nearest-neighbor model's neighbor count. To compare settings, fit each candidate on training examples and assess its predictions on validation examples. One fit learns parameters for one selected set of settings.
- 4Key InsightRecognize variation the inputs cannot explain
For a numeric label, separates the average relationship from variation at fixed inputs. Fitting estimates the average relationship.
Two buildings with identical recorded features may still use different energy because of unrecorded behavior. Better fitting can reduce estimation error, but cannot distinguish those identical input rows. This remaining variation is irreducible error for those features.
- 5ChallengeRead a different feature table
A table of 180 machines contains mass, age, workshop, and a numeric repair-duration target. An arbitrary record number is also present. After removing the target and record number, what shape should the feature table have, and why remove the record number?
---reveal---
Its shape is (180, 3): 180 examples and three inputs. An arbitrary record number can support memorization of familiar rows without a useful meaning for new machines.
- 6ExplanationLearn with a recorded target
Suppose a shop wants to predict whether a customer buys again within 90 days. Older records have that completed outcome, so they supply yes/no labels.
This is supervised learning: known historical targets teach the mapping from features to outcomes. New customers do not yet have their future labels. Their missing future answers are the reason the shop needs predictions, not a reason to call the training unsupervised.
- 7ExplanationDiscover groups without group answers
The shop can instead group customers with similar purchase habits. No correct segment label was recorded in advance. That is clustering, an unsupervised task.
Other unsupervised tasks include making fewer combined features and finding unusual examples. Their results need domain interpretation and checks suited to the task. Cluster numbers name groups; they do not establish an ordering or tell you what each group means.
- 8ChallengeDistinguish two tasks on the same table
A transit operator has journey features and a recorded route label. One project predicts the known route; another ignores that label and discovers groups of similar journeys. Which project is supervised, and why?
---reveal---
Predicting the recorded route is supervised because the label supplies target answers. Discovering similarity groups is unsupervised. The existence of a label somewhere in the table does not make every possible task on that table supervised.
- 9ConnectionRecognize two other learning settings
Labels may require expert work or a wait for future outcomes. Semi-supervised learning combines a small labeled collection with many unlabeled examples to learn the target.
Reinforcement learning instead trains an agent to choose actions from rewards during interaction. These settings differ in the learning signal. Neither the number of rows nor a model's name determines which signal a project actually uses.
- 10ExampleLet the target choose the task
From one delivery table, you can predict minutes of travel, whether the delivery is over 10 minutes late, or which of four depots handles it.
Minutes are a numeric quantity, so the first task is regression. Late/on-time has two classes, so it is binary classification. Four depot names make multiclass classification. Depot codes remain categories even if stored as integers.
- 11TipRead probabilities without changing the task
A classifier can estimate a probability for each class.
predict_probareturns these estimates;predictreturns the selected class. Checkclasses_to match probability columns to labels.A numeric probability does not make the task regression: the outcome is still a category. Logistic regression is a classifier. For many classifiers, the selected class has the highest probability.
- 12ChallengeChoose a label for the decision
A repair team needs to reserve a number of technician minutes for each job. One proposal predicts job duration; another predicts only "under 30 minutes" or "30 minutes and above." Which label preserves the information needed for scheduling, and what task is it?
---reveal---
Duration in minutes preserves the estimated amount of work, so use regression. The two-category label discards differences within each group and cannot express whether a long job needs 35 or 150 minutes.
- 13ExampleSet a prediction cutoff
A streaming service plans monthly offers. Define one row as an active subscriber on the first day of a month and the target as cancellation in the next 30 days.
Features use information up to the previous day's end: previous viewing hours, plan, and time subscribed. Calls during the following month arrive too late. Historical labels can come from that later window, but the features must describe the earlier cutoff.
- 14ExplanationConnect the prediction to an action
The existing rule flags subscribers with no viewing in 14 days. That rule supplies a practical baseline because the model is meant to improve the same offer decision.
Agree on success before modeling: for the same number of offers, reach more subscribers who later cancel. Also check representation and outcome counts. A large table with only 2% cancellations contains far fewer cancellation examples than its total row count suggests.
- 15ChallengeWrite a complete warning task
A rental service sends a warning each morning for currently rented machines likely to break in the next seven days. Its history includes daily usage logs and repair-completion dates. Define one row, the label, and the feature cutoff.
---reveal---
One row is a currently rented machine at a morning prediction. The label is breakdown within the next seven days. Inputs use logs available before that morning; a future repair-completion date cannot be an input, even though later records can establish the historical outcome.
- 16RecapUse a task statement to check the table
A task statement joins an action, a row definition, an outcome, and a prediction time. It lets you decide which columns are legitimate before any fitting begins.
Use known labels for supervised learning and the label's meaning to choose regression or classification. Without target labels, ask what structure would be useful and how it could be checked. Keep parameters learned in fitting separate from settings chosen during development.
2Design an honest split
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what counts as a new case
- 2ExplanationGive each part its job
- 3ExampleRead a training-validation gap
- 4Key InsightSelection makes a score optimistic
- 5ChallengeProtect the final comparison
- 6ExampleReserve the test first
- 7ExampleTake validation from the remainder
- 8ChallengeFind a second-stage fraction
- 9TipPreserve rare-class representation
- 10TipKeep membership stable as rows arrive
- 11ExplanationPlace future periods after the past
- 12ExampleHold out whole entities
- 13ChallengeMatch the split to the actual use
- 14ChallengeRepair a forecast rehearsal
- 15RecapMake the split answer the intended question
3Fit, predict, and beat a simple reference
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive a score a reference point
- 2ExplanationUse the shared estimator pattern
- 3ExampleRead learned coefficients
- 4ChallengeChoose the apply-only method
- 5TipName the measure explicitly
- 6ExampleLearn a constant from training labels
- 7ExampleRecognize an easy classification score
- 8ChallengeCalculate a majority reference
- 9ConnectionCompare with the method already in use
- 10ExampleFind absolute errors before averaging
- 11ExampleExpress improvement against the baseline
- 12Key InsightRead the gap before adding complexity
- 13ChallengeAudit a claimed improvement
- 14RecapKeep the comparison fair
4Trace and repair leakage
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrace information through the workflow
- 2ExampleSpot an answer hidden in a feature
- 3TipInspect the value that existed at the cutoff
- 4ChallengeKeep legitimate history
- 5Key InsightCheck empty fields for hidden outcomes
- 6ExampleLearn a fill value within training
- 7ExampleApply one learned coordinate scale
- 8ExplanationKeep selection and decisions within development
- 9ChallengeDiagnose a misleading repair
- 10ChallengeChoose what a pipeline can repair
- 11RecapRepair the route the information took
5Assemble and run a complete pipeline
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBuild one path from raw rows to predictions
- 2ExplanationPut learned steps in order
- 3ExampleFollow a fit and a prediction
- 4ChallengeChange a nested setting
- 5ExplanationAssign different preparation to column types
- 6ExamplePrepare numeric gaps and scales
- 7ExampleTurn categories into indicator columns
- 8ChallengeCount outputs and handle an unseen value
- 9TipInspect what reaches the model
- 10ExampleSplit the raw feature table
- 11ExampleAttach the preparation to a model
- 12ExampleCompare before making changes
- 13ChallengeHandle the final refit
- 14TipReport an interpretable test result
- 15ConnectionPredict new raw rows
- 16ChallengeAudit the whole sequence
- 17RecapKeep fitting and evaluation in their proper places
Machine Learning Workflow practice questions
Set 1: Identify the task and build the first comparison10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
trips supply that feature and the target "minutes"?Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
pipe.predict(X_val) runs?Show answerHide answer
Question 10 of 10
handle_unknown="ignore". An unlisted record ID is present and remainder is left at its default. A new row has an unseen machine type and a known region. What reaches the model?Show answerHide answer
Set 2: Choose valid inputs and fair evaluation data10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
coef_. Its neighbor-based competitor was created with n_neighbors=9. How are these values classified?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
X and y normally be passed together to train_test_split?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
DummyRegressor(strategy="median") predict?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Diagnose scores and complete the learning sequence10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
C hyperparameter to 2 before refitting?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Audit preprocessing and challenge apparent improvements10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
DummyClassifier() uses its default strategy on training labels that are 75% "ready" and 25% "blocked." What are its prediction and probability behavior for a new row?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Resolve workflow problems in new projects10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
handle_unknown="ignore". How does it represent a new "yellow" value for this feature?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
score(X_val, y_val) = 0.82, while a baseline reports MAE = 5 kg on the same rows. How should an analyst compare them by MAE?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accuracy
Anomaly detection
As-of feature
B
Baseline
Binary classification
C
Class probability
Classification
Clustering
ColumnTransformer
Cross-validation
D
Data leakage
Data snooping
Development pool
Dimensionality reduction
Duplicate record
E
Estimator
Example
Experiment log
F
Feature
Feature selection
Feature-table shape
Final refit
Final test report
Fitting
G
Generalization
Group
Group-based split
H
Historical snapshot
Hyperparameter
I
Imputation
Inference
Intermediate step
Irreducible error
L
Label
Learned attribute
M
Majority-class baseline
Mean absolute error
Mean baseline
Median baseline
Model
Multiclass classification
N
Named step
Nested parameter
O
One-hot encoding
Outcome window
Overfitting
P
Parameter
Persistence forecast
Pipeline
Positive class
Prediction
Prediction time
Predictor
Preprocessing statistic
R
Random seed
Random split
Reducible error
Regression
Reinforcement learning
Relative error reduction
Remainder setting
S
Scaling
Semi-supervised learning
Split proportion
Stable test membership
Stratification
Success criterion
Supervised learning
T
Target leakage
Test set
Time-based split
Train–test contamination
Training set
Transformer
U
Underfitting
Unit of prediction
Unseen category
Unsupervised learning
V
Validation set
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.