The Machine Learning Workflow

Learn the steps that come before any clever algorithm: framing a question as a prediction task, choosing between supervised and unsupervised learning and between regression and classification, and splitting data into training, validation and test sets that give an honest score. Build simple baselines that every model has to beat, learn to spot data leakage before it inflates your results, and put preprocessing and a model together in a scikit-learn pipeline that runs from a raw table to a final test score.

IntermediateLesson 1 of 9 in Machine Learning Course

What you will learn

  1. 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 models
      Name 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 learning
      Decide whether a task has labeled examples to learn from, and match common tasks to supervised or unsupervised learning.
    • Tell regression from classification
      Decide 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 task
      Define the objective, the unit of prediction, the label and the moment of prediction, and check which information is available at that moment.
  2. 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 sets
      Describe generalization and overfitting, and use each of the three data sets for its own purpose in the workflow.
    • Split data randomly and reproducibly
      Choose 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 groups
      Recognize when a random split overstates performance, and split by time or by group so that the evaluation matches real use.
  3. 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 interface
      Create, 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 classification
      Build 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 data
      Fit models and baselines on the same training data, compare them on validation data with the same measure, and read what the comparison says.
  4. 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 leakage
      Identify 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 data
      Fit every preprocessing step on training data only, recognize leakage through preprocessing, splits and repeated test use, and know why pipelines prevent it.
  5. 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 Pipeline
      Build 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 ColumnTransformer
      Apply 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 score
      Put framing, splitting, the baseline, the pipeline and the final test together in the right order, and avoid the mistakes that break an honest result.

Machine Learning Workflow study guide

5 chapters

1

Turn 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 X. Its shape is (500, 4): 500 examples and four features. The label y contains one energy value for each row. Keep the label out of the feature table.

The usual notation is n examples and p features. For example i, xi holds its feature values and yi is its observed label. A prediction is written y^, 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:

Y=f(X)+ε

Here f(X) 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 f^, and a new example receives the prediction y^=f^(x).

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.

SettingWhat the training data suppliesWhat the task seeks
SupervisedFeatures and known labelsA way to predict labels for new examples
UnsupervisedFeatures without a target labelUseful 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 deliveryLabelTask
How many minutes will it take?DurationRegression
Will it be more than 10 minutes late?Late or on timeBinary classification
Which of four depots will handle it?Depot nameMulticlass 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.
2

Create 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
SetIts roleWhat it may influence
TrainingFit parameters and preprocessingLearned coefficients, means, categories, and other fitted values
ValidationCompare candidates during developmentThe chosen model, hyperparameters, and preprocessing design
TestEvaluate the final choiceThe 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 predictionAppropriate boundary
First prediction for an unseen patientPatient groups kept separate
Next month's demandEarlier and later periods kept separate
Next month for existing customersTime 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.
3

Fit 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²:

y^=1000+60×120=8200

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
MethodJob
fitLearn from the supplied data
predictReturn predicted labels or numeric outcomes
predict_probaReturn class probabilities when supported
transformApply a learned data transformation
fit_transformLearn a transformation and apply it to those same rows
scoreCompute 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 R2. 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:

MAE=4+8+1+64=4.75

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:

MAE=1+3+1+24=1.75

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:

4.75−1.754.75×100≈63%

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 R2, 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.
4

Find 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:

  1. Identify the prediction moment for this row.
  2. Identify when the value first became known.
  3. Check whether the stored field was later updated.
  4. 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:

30+50+40+100+1205=68

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:

σ=(−10)2+02+1023≈8.165

A held-out value of 40 is transformed with those training statistics:

40−20200/3≈2.449

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.
5

Build 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:

2+3+4=9

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

5 Walkthroughs

1

Frame a prediction before choosing a model

16 steps
Turn a table into a well-defined learning task, then check labels, task type, and prediction time.
  1. 1
    IntroductionBegin 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.

  2. 2
    ExampleFind 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.

  3. 3
    ExplanationSeparate 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.

  4. 4
    Key InsightRecognize variation the inputs cannot explain

    For a numeric label, Y=f(X)+ε 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.

  5. 5
    ChallengeRead 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.

  6. 6
    ExplanationLearn 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.

  7. 7
    ExplanationDiscover 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.

  8. 8
    ChallengeDistinguish 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.

  9. 9
    ConnectionRecognize 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.

  10. 10
    ExampleLet 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.

  11. 11
    TipRead probabilities without changing the task

    A classifier can estimate a probability for each class. predict_proba returns these estimates; predict returns the selected class. Check classes_ 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.

  12. 12
    ChallengeChoose 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.

  13. 13
    ExampleSet 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.

  14. 14
    ExplanationConnect 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.

  15. 15
    ChallengeWrite 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.

  16. 16
    RecapUse 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.

2

Design an honest split

15 steps
Choose fitting and evaluation boundaries from the way new predictions will be made.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what counts as a new case
  2. 2
    ExplanationGive each part its job
  3. 3
    ExampleRead a training-validation gap
  4. 4
    Key InsightSelection makes a score optimistic
  5. 5
    ChallengeProtect the final comparison
  6. 6
    ExampleReserve the test first
  7. 7
    ExampleTake validation from the remainder
  8. 8
    ChallengeFind a second-stage fraction
  9. 9
    TipPreserve rare-class representation
  10. 10
    TipKeep membership stable as rows arrive
  11. 11
    ExplanationPlace future periods after the past
  12. 12
    ExampleHold out whole entities
  13. 13
    ChallengeMatch the split to the actual use
  14. 14
    ChallengeRepair a forecast rehearsal
  15. 15
    RecapMake the split answer the intended question
3

Fit, predict, and beat a simple reference

14 steps
Use estimator methods, calculate a baseline comparison, and interpret training and validation results.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive a score a reference point
  2. 2
    ExplanationUse the shared estimator pattern
  3. 3
    ExampleRead learned coefficients
  4. 4
    ChallengeChoose the apply-only method
  5. 5
    TipName the measure explicitly
  6. 6
    ExampleLearn a constant from training labels
  7. 7
    ExampleRecognize an easy classification score
  8. 8
    ChallengeCalculate a majority reference
  9. 9
    ConnectionCompare with the method already in use
  10. 10
    ExampleFind absolute errors before averaging
  11. 11
    ExampleExpress improvement against the baseline
  12. 12
    Key InsightRead the gap before adding complexity
  13. 13
    ChallengeAudit a claimed improvement
  14. 14
    RecapKeep the comparison fair
4

Trace and repair leakage

11 steps
Find late features and contaminated preparation, then restore the intended information boundaries.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrace information through the workflow
  2. 2
    ExampleSpot an answer hidden in a feature
  3. 3
    TipInspect the value that existed at the cutoff
  4. 4
    ChallengeKeep legitimate history
  5. 5
    Key InsightCheck empty fields for hidden outcomes
  6. 6
    ExampleLearn a fill value within training
  7. 7
    ExampleApply one learned coordinate scale
  8. 8
    ExplanationKeep selection and decisions within development
  9. 9
    ChallengeDiagnose a misleading repair
  10. 10
    ChallengeChoose what a pipeline can repair
  11. 11
    RecapRepair the route the information took
5

Assemble and run a complete pipeline

17 steps
Prepare mixed columns, follow fit and predict, and finish with a fixed-design test comparison.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild one path from raw rows to predictions
  2. 2
    ExplanationPut learned steps in order
  3. 3
    ExampleFollow a fit and a prediction
  4. 4
    ChallengeChange a nested setting
  5. 5
    ExplanationAssign different preparation to column types
  6. 6
    ExamplePrepare numeric gaps and scales
  7. 7
    ExampleTurn categories into indicator columns
  8. 8
    ChallengeCount outputs and handle an unseen value
  9. 9
    TipInspect what reaches the model
  10. 10
    ExampleSplit the raw feature table
  11. 11
    ExampleAttach the preparation to a model
  12. 12
    ExampleCompare before making changes
  13. 13
    ChallengeHandle the final refit
  14. 14
    TipReport an interpretable test result
  15. 15
    ConnectionPredict new raw rows
  16. 16
    ChallengeAudit the whole sequence
  17. 17
    RecapKeep fitting and evaluation in their proper places

Machine Learning Workflow practice questions

50 Practice Questions in 5 sets

Set 1: Identify the task and build the first comparison10 Practice Questions

Question 1 of 10

A table has 720 water samples. Each row contains temperature, depth, acidity, and measured salt concentration. Salt concentration is the target. What is the shape of the feature table?
  1. (720, 1)
  2. (720, 3)
  3. (720, 4)
  4. (3, 720)
Show answerHide answer
Answer: B
There are 720 examples and three input columns, so the feature table has shape (720, 3). Salt concentration belongs in the label vector. Counting all four measured columns as features would put the answer the model should predict into its inputs.

Question 2 of 10

A museum groups visitors by similarities in their visit histories. No visitor has a recorded segment label. What learning setting fits this task?
  1. Supervised regression
  2. Reinforcement learning
  3. Unsupervised learning
  4. Supervised classification
Show answerHide answer
Answer: C
The museum is discovering structure without known segment answers, so this is unsupervised learning. Classification would require predefined class labels for training. Producing group numbers does not turn clusters into classes learned from labeled examples.

Question 3 of 10

A model predicts a package category stored as 10, 20, or 30. The values identify three packaging types. What supervised task is this?
  1. Multiclass classification
  2. Numeric regression
  3. Unsupervised clustering
  4. Binary classification
Show answerHide answer
Answer: A
The codes name three predefined categories, so this is multiclass classification. Their numeric storage does not make the task regression: a difference of 10 between codes is not a measured amount. Clustering would discover groups without these known category labels.

Question 4 of 10

A team uses a held-out set to choose between two model settings. What role does that set have?
  1. Training set
  2. Unlabeled feature set
  3. Final test set
  4. Validation set
Show answerHide answer
Answer: D
The set guides a model choice, so it is validation data. A final test must stay out of that choice to estimate the fixed model afterward. Calling a set a test set does not preserve its independence when the team uses its results to select settings.

Question 5 of 10

Training durations are 8, 10, 12, 18, and 42 minutes. An analyst chooses the constant that minimizes training absolute error. For a validation job lasting 9 minutes, what prediction and absolute error result?
  1. Predict 18 minutes; error 9 minutes.
  2. Predict 12 minutes; error −3 minutes.
  3. Predict 10 minutes; error 1 minute.
  4. Predict 12 minutes; error 3 minutes.
Show answerHide answer
Answer: D
The median, 12 minutes, minimizes training absolute error among constant predictions. Its distance from the 9-minute validation outcome is 3 minutes. The mean is 18 minutes, but it minimizes squared training error instead of the absolute-error criterion requested here.

Question 6 of 10

A linear regressor expects one feature named "distance_km". How should a pandas table trips supply that feature and the target "minutes"?
  1. X = trips[["minutes"]]; y = trips["distance_km"]
  2. X = trips[["distance_km"]]; y = trips["minutes"]
  3. X = trips["distance_km"]; y = trips["minutes"]
  4. X = trips[["distance_km", "minutes"]]; y = trips["minutes"]
Show answerHide answer
Answer: B
The double column selection keeps the feature input two-dimensional, while the target is a one-dimensional Series. A single feature still needs a table with one column. Including "minutes" in that table would also leak the target into the features.

Question 7 of 10

Training labels contain 680 "pass" and 120 "fail" cases. A validation set has 170 "pass" and 30 "fail" cases. What validation accuracy does a most-frequent-class baseline achieve?
  1. 85%
  2. 80%
  3. 50%
  4. 15%
Show answerHide answer
Answer: A
The baseline learns to predict "pass" from the training majority. That prediction is correct for 170 of 200 validation cases, giving 85% accuracy. A 50% reference ignores the unequal class frequencies and sets a much weaker bar for this task.

Question 8 of 10

An equipment model predicts failure at the start of a shift. Its table includes a repair code entered after a failure during that shift. How should this column be treated?
  1. Fill its missing entries before using it.
  2. Keep it if it improves validation accuracy.
  3. Remove it from the shift-start features.
  4. Keep it after scaling all code values.
Show answerHide answer
Answer: C
The repair code becomes known after the outcome the model must predict, so it leaks target information into a shift-start task. Scaling or imputing it changes its representation, not its availability. A stronger validation score cannot make that late information legitimate.

Question 9 of 10

A pipeline contains a scaler and a classifier and has been fitted on training rows. What happens when pipe.predict(X_val) runs?
  1. Fit a new scale, then predict classes.
  2. Reuse the fitted scale, then predict classes.
  3. Reuse the fitted scale, then refit classes.
  4. Fit a new scale, then refit the classifier.
Show answerHide answer
Answer: B
Prediction passes validation rows through the scaler with the values learned from training, then calls the fitted classifier. Refitting the scale on validation rows would absorb held-out information and change the representation. Pipeline prediction performs neither of those new fits.

Question 10 of 10

Training has two numeric inputs, four machine types, and three regions. A ColumnTransformer scales the numeric inputs and one-hot encodes both categorical inputs with no categories dropped and 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?
  1. Ten columns; machine indicators all zero.
  2. Ten columns; a new machine indicator is one.
  3. Nine columns; a new machine indicator is one.
  4. Nine columns; machine indicators all zero.
Show answerHide answer
Answer: D
The fitted output has two numeric, four machine, and three region columns, for nine total. The default remainder drops the unlisted ID. An unseen machine type becomes zeros in the existing machine columns; it does not expand the fitted feature space.
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

A library will send reminders each Monday to borrowers likely to return an item late during the next seven days. What row definition matches that decision?
  1. One returned item with its final overdue days.
  2. One borrower with a lifetime lateness total.
  3. One branch with a monthly reminder count.
  4. One active loan on a Monday prediction date.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A fitted linear model stores a slope in coef_. Its neighbor-based competitor was created with n_neighbors=9. How are these values classified?
  1. Slope: parameter; 9: hyperparameter.
  2. Both values are chosen hyperparameters.
  3. Both values are learned parameters.
  4. Slope: hyperparameter; 9: parameter.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A manufacturer has 12 readings from each machine and wants to predict for machines absent from training. How should it split the readings?
  1. Keep each machine in every evaluation set.
  2. Randomly hold out readings within each machine.
  3. Hold out whole machines in separate sets.
  4. Stratify readings by their numeric row IDs.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Why should X and y normally be passed together to train_test_split?
  1. To keep every outcome class equally frequent.
  2. To keep each feature row paired with its label.
  3. To keep all feature values on the same scale.
  4. To keep all entity groups in separate sets.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

On the same validation rows, observed transit times are 14, 22, 18, and 30 minutes. A model predicts 16, 19, 18, and 27. The baseline MAE is 4 minutes. How does the model compare by MAE?
  1. It matches the baseline at 4 minutes.
  2. It worsens MAE by 2 minutes.
  3. It improves MAE by 2 minutes.
  4. It improves MAE by 3 minutes.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Training processing times are 6, 8, 9, 12, and 30 minutes. What constant does DummyRegressor(strategy="median") predict?
  1. 9 minutes
  2. 12 minutes
  3. 8 minutes
  4. 13 minutes
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A model for unseen devices selects features against all labels, scales the full table, then randomly splits individual readings from repeated devices. The final model fits only the training part. What redesign is needed for an independent final evaluation?
  1. Hold out readings, fit selection and scaling within training, and test fresh readings.
  2. Hold out devices, retain full-table selected features, and fit scaling within training.
  3. Hold out devices, fit selection within training, and retain the full-table fitted scale.
  4. Hold out devices, fit selection and scaling within training, and test fresh devices.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A model predicts next week’s electricity use. It uses last week’s completed meter total and next week’s final invoice adjustment. What input choice respects the prediction time?
  1. Remove both inputs because they concern energy use.
  2. Keep the meter total; remove the invoice adjustment.
  3. Remove the meter total; keep the invoice adjustment.
  4. Keep both inputs if neither directly equals the target.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A team fixes one pipeline design after validation. It wants to use all development rows, where the imputation median differs from the original training median. Its test is untouched. What final procedure handles preprocessing, the baseline, and evaluation correctly?
  1. Relearn pipeline statistics and baseline on development, then test both once.
  2. Freeze the old statistics, fit the model on test, then compare both scores.
  3. Relearn pipeline statistics on all rows, then fit the baseline on development.
  4. Relearn only the model on development, then select settings by test score.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A linear model receives an unordered "surface" feature coded as 1 for gravel, 2 for asphalt, and 3 for concrete. What assumption does this single coded column introduce?
  1. A new indicator column for every observed surface.
  2. No relationship between the codes and predictions.
  3. Separate fitted effects for all three surface names.
  4. Equal predicted changes for the 1-to-2 and 2-to-3 steps.
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

A lab has 90 labeled recordings and 9,000 unlabeled recordings. Its training method deliberately combines both collections to learn the labeled outcome. What setting is this?
  1. Fully supervised learning
  2. Reinforcement learning
  3. Semi-supervised learning
  4. Unsupervised clustering
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An estimator named LogisticRegression predicts whether a filter passes inspection. What is its learning task?
  1. Binary classification
  2. Multiclass classification
  3. Numeric regression
  4. Unsupervised anomaly detection
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A bike service wants a morning prediction of breakdown within seven days to prioritize inspections. Its table contains only bikes repaired by year-end; current status was overwritten after repairs. Which task and row construction matches the decision?
  1. Use every eligible bike-morning, a future breakdown label, and latest stored status.
  2. Use every eligible bike-morning, a future breakdown label, and cutoff-time status.
  3. Use repaired bike-mornings only, a future breakdown label, and cutoff-time status.
  4. Use every eligible bike-morning, a repair-duration label, and cutoff-time status.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A model’s training accuracy is 99%, while its validation accuracy is 73%. Its baseline validation accuracy is 70%. What concern should the team investigate?
  1. A baseline trained on validation labels.
  2. Underfitting caused by a too-simple model.
  3. An independent final test already completed.
  4. Overfitting to training-specific patterns.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A retailer forecasts each existing store’s next month. A source table includes duplicate store-month records, and a proposed feature is mean sales across all recorded years. What evaluation design matches the task?
  1. Keep copies together, split by store, and rebuild means from earlier data.
  2. Keep copies together, split by time, and retain full-history means.
  3. Split copies randomly, split periods randomly, and rebuild means from earlier data.
  4. Keep copies together, split by time, and rebuild means from earlier data.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A fitted scaler must prepare validation features without learning new statistics. What method should be called?
  1. transform(X_val)
  2. set_params(X_val)
  3. fit(X_val)
  4. fit_transform(X_val)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A model correctly classifies 361 of 400 validation cases; another correctly classifies 363. How large is their accuracy gap?
  1. 2 percentage points
  2. 0.5 percentage points
  3. 5 percentage points
  4. 0.05 percentage points
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A team imputes from all rows, selects an outlier cutoff after inspecting test distributions, then chooses a model using that test score. It never fits the model on test labels. What repair is needed for an independent estimate?
  1. Fit preparation on training, choose on validation, and reuse the inspected test cases.
  2. Fit preparation on all rows, choose on validation, and evaluate on fresh test cases.
  3. Fit preparation on training, choose on validation, and evaluate on fresh test cases.
  4. Fit preparation on training, choose on test scores, and evaluate on fresh test cases.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A pipeline has steps named "prep" and "classifier". How can you set the classifier’s C hyperparameter to 2 before refitting?
  1. pipe.set_params(classifier__C=2)
  2. pipe.set_params(prep__C=2)
  3. pipe.set_params(model__C=2)
  4. pipe.set_params(classifier_C=2)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A fixed pipeline and baseline were evaluated once on untouched test rows. What report best lets another analyst interpret and repeat the comparison?
  1. Only the best validation score and model name.
  2. Only the pipeline’s test score and feature count.
  3. Both test scores, units, split design, and seed.
  4. Both training scores and the original row count.
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

Two items have identical recorded features, but their numeric outcomes differ because of unrecorded behavior. What kind of error remains for a predictor using only those features?
  1. Reducible error from a poorly fitted slope.
  2. A hyperparameter that changes across rows.
  3. Target leakage from the numeric outcome.
  4. Irreducible error at those feature values.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An analyst changes a target from repair duration in minutes to "over 60 minutes" or "60 minutes or less." What happens to the task?
  1. It becomes clustering and discovers its own duration groups.
  2. It becomes binary classification and loses duration detail.
  3. It becomes multiclass classification and keeps the order.
  4. It stays regression and keeps the exact duration detail.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An independent-row classification table has 8,000 cases and 400 rare outcomes. A team wants a 25% stratified test that stays fixed as rows are added. What initial rare-outcome count and future membership rule fit the aim?
  1. 100 rare cases; stratify once and save the test IDs.
  2. 100 rare cases; stratify each enlarged table with the same seed.
  3. 400 rare cases; stratify once and save the test IDs.
  4. 200 rare cases; stratify each enlarged table with the same seed.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A grouped table has 60 devices. A GroupShuffleSplit reserves 20% of groups for testing. Devices have different numbers of readings. What test size is determined?
  1. 20 readings; the device count depends on the devices.
  2. 20 devices; the reading count is exactly one fifth.
  3. 12 devices; the reading count depends on the devices.
  4. 12% of readings; the device count depends on rows.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A fitted 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?
  1. Predict classes randomly; probabilities 0.75 and 0.25.
  2. Predict "ready"; probabilities 1.00 and 0.00.
  3. Predict "ready"; probabilities 0.75 and 0.25.
  4. Predict "blocked"; probabilities 0.25 and 0.75.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A candidate has training MAE 0.2 kg and validation MAE 1.8 kg on difficult batches. Its baseline has validation MAE 1.6 kg on separate easy batches after a different training split. How should the team evaluate the claimed difference?
  1. Align fitting and validation rows, compare MAE, and investigate the candidate’s fit gap.
  2. Align only the validation rows, compare MAE, and accept both original fits.
  3. Compare the printed MAEs, prefer the baseline, and treat the fit gap as underfitting.
  4. Align fitting rows, retain separate validation cases, and accept the candidate’s low training error.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A system predicts weekly cancellation. Its contact-reason field is filled after closure, current status is overwritten after closure, and prior-week completed usage is available. What feature repair matches the weekly task?
  1. Impute the later reason, reconstruct cutoff status, and keep prior usage.
  2. Remove the later reason, retain latest status, and keep prior usage.
  3. Remove the later reason, reconstruct cutoff status, and remove prior usage.
  4. Remove the later reason, reconstruct cutoff status, and keep prior usage.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Training values are 2, 6, and 10. A mean imputer is fitted correctly before transforming held-out values 20, 22, and a missing entry. What fills the missing entry?
  1. 21
  2. 6
  3. 12
  4. 14
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An analyst scales the full table, splits those values, fits a model-only pipeline, then chooses C using test accuracy. How should the pipeline workflow be rebuilt for an independent final evaluation?
  1. Keep scaled rows, fit the model within training, select on validation, and use a fresh test.
  2. Split raw rows, fit the scaler-model chain within training, select on validation, and reuse the original test.
  3. Split raw rows, fit the scaler-model chain within training, select on validation, and use a fresh test.
  4. Split raw rows, fit the scaler-model chain on all rows, select on validation, and use a fresh test.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A ColumnTransformer explicitly prepares "mass_kg" and "material". The input also contains "record_id" and "height_m". Its remainder setting is omitted. Which unlisted columns reach the model?
  1. Neither unlisted column.
  2. Only the record identifier column.
  3. Both unlisted columns.
  4. Only the numeric height column.
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

A fitted encoder has color categories blue, green, and red, with no dropped category. It uses handle_unknown="ignore". How does it represent a new "yellow" value for this feature?
  1. 1, 0, 0
  2. 0, 0, 0
  3. 0, 0, 1
  4. 0, 0, 0, 1
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A robot learns which movements earn higher rewards while interacting with its environment. What learning setting does this describe?
  1. Reinforcement learning
  2. Semi-supervised learning
  3. Unsupervised clustering
  4. Supervised classification
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An operator wants to warn trips at departure when they will exceed promised arrival time. Its archive includes canceled trips, a numeric final delay in minutes, and weather forecasts saved before departure. What task and rows support this warning?
  1. Use departed trips, derive a late/on-time label, and replace forecasts with observed later weather.
  2. Use only canceled trips, derive a late/on-time label, and retain saved departure-time forecasts.
  3. Use departed trips, derive a late/on-time label, and retain saved departure-time forecasts.
  4. Use departed trips, predict route codes as the target, and retain saved departure-time forecasts.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A team tries 80 designs on validation, picks one, tests it, and switches to the runner-up because that test score disappoints. It then refits the runner-up with fixed settings on training plus validation. What is the status of the old scores and the next independent estimate?
  1. Only validation guided selection; reuse the old test for the runner-up.
  2. Only the old test guided selection; report the runner-up’s validation score.
  3. Neither score guided the final fit; report the runner-up’s training score.
  4. Validation and old test both guided selection; use fresh untouched cases.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An independent-row data set has 2,400 cases, including 144 rare-class cases. A stratified split holds out 25% for testing. How many rare-class cases should that test contain?
  1. 144
  2. 36
  3. 108
  4. 25
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A regressor reports 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?
  1. Call fit on validation labels before requesting another score.
  2. Compute MAE from the regressor’s validation predictions.
  3. Compare 0.82 directly with 5 and choose the smaller value.
  4. Convert 0.82 to 82% and compare it with the baseline error.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A model trained on the same rows as its mean baseline predicts 11, 20, 16, and 27 minutes for validation outcomes 12, 18, 19, and 25. The baseline predicts 18 for all four. What is the model’s MAE reduction relative to this baseline?
  1. About 14%
  2. About 71%
  3. About 43%
  4. About 57%
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A maintenance model uses a cumulative fault count stored today to reconstruct predictions made six months ago. How should an analyst determine whether the feature is legitimate?
  1. Check the count recorded before each historical prediction.
  2. Keep today’s count because fault counts are numeric.
  3. Drop the count only when it matches the final label.
  4. Keep today’s count if the split is chronological.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A team forecasts next month for existing devices. It randomly splits device-days, fits category encoding on the full table, and includes each device’s mean reading across the whole period. What redesign repairs the evaluation?
  1. Split by device, fit encoding within training, and rebuild each mean from earlier history.
  2. Split by time, retain full-table encoding, and rebuild each mean from earlier history.
  3. Split by time, fit encoding within training, and retain each full-period mean.
  4. Split by time, fit encoding within training, and rebuild each mean from earlier history.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A selected pipeline is refitted on training plus validation. Its imputer median changes from 7 to 8. The baseline is still fitted only on original training rows; no test has been used. What final procedure is appropriate?
  1. Restore the old median, refit the baseline on development, and test both with fixed settings.
  2. Keep the new median, refit the baseline on test labels, and test both with fixed settings.
  3. Keep the new median, refit the baseline on development, and test both with fixed settings.
  4. Keep the new median, refit the baseline on development, and select settings by test results.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

79 Key Terms, each with its definition

A

Accuracy
Accuracy is the fraction of class predictions that match their observed labels on the examples being evaluated.
A classifier with 170 correct predictions among 200 cases has accuracy of 85%.
Anomaly detection
Anomaly detection identifies examples that differ from the usual data pattern so that their unusual behavior can be investigated.
Experts inspect flagged sensor readings to decide whether they represent a genuine fault.
As-of feature
An as-of feature is built from information available before a particular prediction cutoff instead of from later updated records.
The loan model uses earlier payment history known before each historical application date.

B

Baseline
A baseline is a simple reasonable prediction method used as a reference for judging whether a candidate improves the task.
A complex model is compared with the current rule before its extra complexity is accepted.
Binary classification
Binary classification predicts one of exactly two possible target classes, such as accepted or rejected inspection results.
A delivery model predicts either late or on time from information available before dispatch.

C

Class probability
A class probability is a model's estimated chance that an example belongs to a particular class, distinct from the selected label.
A model can return an estimated spam probability as well as a final spam-or-not-spam label.
Classification
Classification is supervised prediction of membership in a predefined set of categories, using examples with known class labels.
A model learns recorded packaging types even when their category names are stored as integers.
Clustering
Clustering groups examples by their similarity without learning from predefined class labels that identify the correct groups.
A cluster of frequent buyers needs inspection before an analyst gives it a useful name.
ColumnTransformer
A ColumnTransformer applies separate preparation to selected column groups, then combines the resulting feature outputs side by side.
Numeric measurements and heating categories take different branches before reaching one regressor.
Cross-validation
Cross-validation rotates development data through training and validation roles to compare models while a separate final test stays held out.
With scarce data, several parts take turns providing validation examples during model selection.

D

Data leakage
Data leakage occurs when information unavailable for legitimate prediction enters learning or selection and makes evaluation misleading.
A late repair record lets a historical model exploit information missing at its real prediction time.
Data snooping
Data snooping uses inspected test information to guide modeling decisions, making that test part of development.
An analyst chooses an outlier cutoff after examining test patterns, despite never fitting on test rows.
Development pool
The development pool combines the data available for learning and selection while excluding the reserved final test examples.
After settings are chosen, the full pool supplies the rows for the pipeline and baseline's final fit.
Dimensionality reduction
Dimensionality reduction replaces many features with fewer combined features while retaining useful information in the data.
A table with many related measurements can be represented by fewer combined inputs.
Duplicate record
A duplicate record is a repeated copy of the same observation that can make evaluation too easy if its copies cross the split.
Copies of a transaction are removed or kept together so the test does not repeat a training case.

E

Estimator
An estimator is a scikit-learn object that learns from data through fit and can expose other methods suited to its task.
A newly created linear regressor becomes a fitted estimator after learning from paired rows.
Example
An example is one observation represented by a row of data, with input features and, in a supervised task, a matching target label.
In a table of buildings, one row describes one building and its observed yearly energy use.
Experiment log
An experiment log records models, settings, preparation choices, and comparable training and validation results during development.
The log shows whether changing imputation helped before the team tries another estimator.

F

Feature
A feature is an input variable a model uses to make a prediction, such as a measurement or a suitably encoded category.
Floor area and heating type are features for predicting a building's energy use in kWh.
Feature selection
Feature selection chooses a subset of inputs to retain; when learned from data, the choice must stay inside the training boundary.
Selecting noise columns by their relationship to all labels exposes held-out answers.
Feature-table shape
A feature-table shape gives the number of example rows and input columns; standard estimator inputs are two-dimensional.
A single-feature DataFrame still has both a row count and a column count of one.
Final refit
A final refit learns the chosen fixed procedure again from training plus validation data before evaluating on an untouched test.
The imputation median can change when the selected pipeline learns from the full development pool.
Final test report
A final test report presents model and baseline results with their measure, units, and split design after all choices are fixed.
Both MAEs are shown in kWh alongside the held-out proportions and the recorded random seed.
Fitting
Fitting is the process of learning parameters or preprocessing values from the data supplied to an estimator's fit method.
Fitting a mean imputer computes fill values from the selected training feature columns.

G

Generalization
Generalization is a learned model's ability to make useful predictions for new examples beyond those used to fit its parameters.
Good results on comparable held-out buildings support generalization beyond the training buildings.
Group
A group is an entity linking several records, such as one patient or device, whose rows may need to stay together in a split.
Device IDs identify groups when many readings were taken from each physical sensor.
Group-based split
A group-based split keeps every row from an entity in one set when the task requires prediction for previously unseen entities.
Every image of a held-out patient remains outside training when testing new-patient prediction.

H

Historical snapshot
A historical snapshot records values as they stood at a particular time so past prediction inputs can be reconstructed correctly.
A monthly snapshot preserves account status before later cancellations update the database.
Hyperparameter
A hyperparameter is a setting chosen before a fit that controls the model or learning procedure, such as a neighbor count.
The analyst compares several neighbor counts on validation data before fixing the setting.

I

Imputation
Imputation fills missing values using a rule, often based on a statistic learned from the training examples for each column.
Numeric gaps are filled with training medians before the pipeline scales those columns.
Inference
Inference seeks to understand how an outcome depends on features, an aim distinct from accurate prediction of new cases.
An analyst studies how the outcome relates to area instead of only comparing forecast errors.
Intermediate step
An intermediate step is a nonfinal pipeline transformer that fits and transforms inputs before passing its output onward.
An imputer fills training gaps before the next step learns a scale from that filled table.
Irreducible error
Irreducible error is outcome variation that remains at fixed recorded feature values and cannot be removed using only those inputs.
Two buildings with the same recorded inputs may use different energy because of unrecorded habits.

L

Label
A label is the observed outcome a supervised model is trained to predict; it is also called the target or response.
The measured repair duration supplies a label for each completed historical repair job.
Learned attribute
A learned attribute stores a fitted value and usually has a trailing underscore in scikit-learn, such as coef_ or mean_.
After fitting, the analyst inspects the model's coef_ to see its learned coefficients.

M

Majority-class baseline
A majority-class baseline predicts the most frequent training class for every example and reveals easy accuracy from class imbalance.
Always predicting accepted can score highly while detecting none of the rejected cases.
Mean absolute error
Mean absolute error, or MAE, is the average absolute difference between numeric predictions and labels, in the label's units.
An MAE of 4 minutes describes average error size, without canceling early and late arrivals.
Mean baseline
A mean baseline predicts the arithmetic mean of the training labels for every example, without using feature values to vary it.
The fitted dummy regressor returns the same training-derived duration for every new job.
Median baseline
A median baseline predicts a training-label median, a constant that minimizes absolute error on those training labels.
A long repair pulls up the mean more than the median used by the constant reference.
Model
A model is a function learned from data that turns an example's input features into an output, such as a predicted value or class.
A fitted model maps a new building's feature values to its predicted annual energy use.
Multiclass classification
Multiclass classification predicts one class from a fixed set of more than two categories for each example.
A parcel model predicts which of four depots will handle a new shipment.

N

Named step
A named step is a pipeline component identified by a unique name used to inspect it and address its nested settings.
The analyst selects the step named model to inspect the final estimator's fitted coefficients.
Nested parameter
A nested parameter addresses a setting inside a named pipeline step with the step name, two underscores, and parameter name.
The name model__C reaches C in the estimator whose pipeline step is called model.

O

One-hot encoding
One-hot encoding represents a categorical feature with separate indicator columns for its learned categories, avoiding arbitrary spacing.
A gas-heated building has a 1 in the gas column and 0 in the other heating columns.
Outcome window
An outcome window is the specified period after a prediction cutoff during which the event defining the target label is observed.
A cancellation label records whether an active account closes in the next 30 days.
Overfitting
Overfitting occurs when a model learns training-specific noise or quirks, giving much better training than new-case performance.
A model nearly memorizes training rows but loses much of that apparent accuracy in validation.

P

Parameter
A parameter is a model value learned during fitting, such as the coefficient or intercept of a linear regression model.
The slope of a fitted energy model tells how its prediction changes with floor area.
Persistence forecast
A persistence forecast predicts that a recent observed value repeats, providing a simple reference for a time-series prediction.
Tomorrow's demand is first compared with a forecast that simply repeats today's demand.
Pipeline
A Pipeline chains fitted preparation and an estimator so training and prediction follow one ordered sequence of steps.
In a pipeline ending in a classifier, the raw validation table passes through a fitted scaler before the classifier predicts.
Positive class
The positive class is the outcome of interest in a binary task, regardless of whether that outcome is desirable or harmful.
In a fault-warning model, the positive class can be failure even though failure is unwanted.
Prediction
Prediction applies a learned model to estimate an unknown outcome for a new example, with accuracy judged on held-out cases.
An energy model estimates next year’s use from information available before that year.
Prediction time
The prediction time is the moment a prediction is needed; feature values must be available before that moment for the intended task.
A shift-start failure forecast can use completed earlier logs, but not repairs later that shift.
Predictor
A predictor is an estimator that returns predicted outcomes for supplied feature rows using a predict method after fitting.
The fitted building predictor returns energy estimates for a table of unfamiliar buildings.
Preprocessing statistic
A preprocessing statistic is a value learned during preparation, such as an imputation median or a scaling mean and standard deviation.
A held-out missing value is filled using the median learned from training, not its own batch.

R

Random seed
A random seed is a value controlling a random procedure so the same inputs and settings can produce the same row assignment.
An integer random_state lets two candidate models be compared on the same shuffled split.
Random split
A random split assigns shuffled examples to separate data sets, which is appropriate when independent rows match the intended use.
Independent water samples are shuffled into development and test parts with their labels attached.
Reducible error
Reducible error comes from an imperfect estimate of the feature-outcome relationship and can shrink with better modeling or inputs.
A better fitted relationship can reduce errors caused by a poor estimate of typical energy use.
Regression
Regression is supervised prediction of a quantity on a numeric scale, where differences between values have a meaningful size.
Predicting the number of minutes a repair will take is a regression task for scheduling.
Reinforcement learning
Reinforcement learning trains an agent to choose actions from rewards received during interaction with an environment.
A robot learns which movements earn rewards through the effects of its own actions.
Relative error reduction
A relative error reduction is the drop in an error measure divided by the reference error, often expressed as a percentage.
A fall in MAE from a baseline's 4 kg to a model's 3 kg removes one quarter of the baseline's average error.
Remainder setting
The remainder setting determines what a ColumnTransformer does with input columns not selected by its explicit branches.
The default drops an unlisted building ID and also drops any useful measurement left unlisted.

S

Scaling
Scaling changes numeric feature values using a learned reference, such as subtracting a training mean and dividing by its spread.
Validation measurements are placed on the same training-derived scale before prediction.
Semi-supervised learning
Semi-supervised learning combines labeled and unlabeled examples to learn a target when only part of the collection has labels.
A project uses a few annotated recordings together with many recordings lacking target answers.
Split proportion
A split proportion is the share of the input to a split assigned to one part; a second split uses the remaining input as its base.
A quarter of an 80% remainder is 20% of the original table, giving a three-way split.
Stable test membership
Stable test membership keeps the chosen evaluation examples assigned to the test even when more rows are added to the collection.
Saving test IDs prevents a later rerun from moving those familiar evaluation cases into training.
Stratification
Stratification preserves approximate proportions of selected classes or bands across split parts to support representative evaluation.
A stratified email split keeps the rare spam class near its overall share in the test.
Success criterion
A success criterion states how a prediction method must improve the intended decision, agreed before model results are inspected.
At a fixed number of offers, a new method should reach more accounts that later cancel than the current method does.
Supervised learning
Supervised learning learns a mapping from input features to a target using training examples whose target labels are known.
Historical repeat-purchase labels teach a model to predict whether new customers will return.

T

Target leakage
Target leakage is leakage through a feature that reveals the label or its aftermath using information unavailable at prediction time.
A cancellation reason populated after account closure reveals the outcome the model should predict.
Test set
The test set is held out from fitting and selection so it can estimate performance of the fixed final learning procedure.
Only after selecting the pipeline does the analyst compare its test predictions with labels.
Time-based split
A time-based split separates earlier training records from later validation and test periods to evaluate prediction forward in time.
A demand forecast learns from older months and is finally tested on the latest held-out period.
Train–test contamination
Train–test contamination occurs when held-out information shapes fitting or learned preparation before the final evaluation.
A full-table scaler includes test measurements when it learns a column mean and spread.
Training set
The training set supplies the examples used to learn model parameters and fitted preprocessing values during development.
A scaler learns column means from training rows before it transforms held-out measurements.
Transformer
A transformer is an estimator that learns a data-preparation rule and applies it through transform to produce changed inputs.
A scaler transforms validation measurements using means and spreads learned from training.

U

Underfitting
Underfitting occurs when a model is too simple to capture the useful pattern, leaving poor performance on training and new data.
A constant predictor can miss a strong area-energy relationship even on its training examples.
Unit of prediction
The unit of prediction defines what one example and one prediction represent, including the entity and the relevant occasion.
In a task that predicts cancellation, one subscriber on a particular monthly date forms one row.
Unseen category
An unseen category is a feature value absent during encoder fitting that can appear in validation, test, or new prediction rows.
If an encoder learned heating types without district heating, that value becomes all zeros in its heating columns when unknown categories are ignored.
Unsupervised learning
Unsupervised learning seeks useful structure in feature data without a recorded target label supplying answers for each example.
A shop groups customers by buying habits without recorded segment answers to learn from.

V

Validation set
The validation set supplies held-out development examples for comparing models and choosing settings or preprocessing designs.
The team chooses the neighbor count from validation results while leaving the test closed.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started