Problem Framing & the ML Project Lifecycle

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This page was checked on 2026-10-30. It covers the work that happens before and around model training, which is where most machine learning projects succeed or fail. It builds on the process models in The Data Science Workflow (CRISP-DM and the R for Data Science loop) and adds what is specific to projects whose product is a model: framing the problem as a prediction, protecting the evaluation, and keeping the model healthy after launch. The examples target Python 3.13 and scikit-learn 1.9. Examples were run on Python 3.13 with scikit-learn 1.9.1 on 2026-11-01. The previous pages, What Is Machine Learning? and Types of Learning, define the vocabulary.

Why framing comes first

A model answers the question it was trained on, not the question the business has. If those differ, a technically excellent model produces no value. Typical mismatches: predicting which customers will churn when the decision is whom to offer a discount (the customers most likely to leave are not necessarily those whose behaviour a discount changes); predicting clicks when the goal is satisfaction; optimising accuracy when a missed case costs ten times a false alarm. Time spent on framing is cheap compared to a retraining cycle or a launch that is later rolled back.

The lifecycle at a glance

flowchart LR F[1 Frame the problem] --> D[2 Collect and label data] D --> E[3 Explore and prepare] E --> M[4 Model and tune] M --> V[5 Evaluate against the goal] V -- not good enough --> D V -- good enough --> L[6 Launch] L --> O[7 Monitor and maintain] O -- drift or new needs --> F

The arrows back are the point. The data science workflow page lists six CRISP-DM phases; a model-centred project expands the last two, because a deployed model is a system that needs monitoring, retraining and a way to be switched off. The reproducibility and MLOps basics page shows how to make each step repeatable, and experiment tracking and MLOps covers the tooling for training runs.

Step 1: frame the problem

Answer these questions in writing, with the people who will use the model, before collecting a single row.

Question What a good answer looks like

What decision or action will the prediction change?

A concrete action with an owner: "the retention team calls the 500 highest-risk customers each week".

What does success mean, in business terms?

A number and a target: "reduce monthly churn from 3.0 to 2.5 percent", not "build a good model".

How is the problem solved today?

The current process is the baseline to beat and a source of labels and domain knowledge. If nothing exists, a simple heuristic is the baseline.

Is ML needed?

A rule or lookup table that works is better. Google’s guidance is blunt: do not be afraid to launch a product without machine learning, and collect the data a later model would need.

What is the prediction target, exactly?

A precise definition with a time window: "cancels within 30 days after the prediction date", not "churn".

What does an error cost?

Costs of false positives and false negatives, ideally in money or time. They decide the metric and the threshold.

What is available at prediction time?

Only features that exist when the prediction is made. A feature computed after the outcome is leakage.

Who is affected, and could they be harmed?

Fairness, privacy and regulatory review belong here, not at the end. See ethics and privacy and fairness and responsible ML.

Translate the need into a learning task

The same business need can be framed as different learning tasks, with different data and trade-offs.

Business need Possible framings Consequence

Reduce customer churn

Binary classification (will cancel in 30 days); survival analysis (time until cancellation); uplift modelling (who responds to an offer)

Classification is simplest; uplift answers the real decision question but needs data from randomised offers

Show relevant products

Ranking; multiclass over a catalogue; embedding similarity

The metric is a ranking metric, not accuracy; see embeddings and representation learning

Forecast demand

Regression on a time series; quantile regression for stock decisions

Needs time-aware splits and a metric that weights under- and over-stocking

Find defective parts

Supervised classification when defects are labelled; anomaly detection when they are rare and unlabelled

Labels decide the family; see types of learning

Route support tickets

Multiclass text classification; zero-shot classification with a language model

A pretrained model may need no training data at all; see transfer learning and foundation models

Prefer the simplest framing that supports the decision, and write down the target definition with the same care as a function signature. Ambiguity about the target (when the window starts, how ties and missing outcomes are handled) is the root of many leakage bugs.

Choose the metric before the model

Distinguish three kinds of numbers and decide each in advance.

  • Business metric: what the organisation cares about (revenue, cost, retention). Often measured only in production, with an experiment.

  • Evaluation metric: an offline number that tracks the business metric well enough to compare models (precision at k, expected cost, mean absolute error). It must be computable on held-out data.

  • Loss function: the differentiable quantity the training algorithm minimises, which may differ from the evaluation metric.

If the offline metric improves while the business metric does not, the metric is wrong, not the experiment. Google’s Rules of ML advise tracking several metrics and keeping the objective simple and directly attributable to a measurable user behaviour. Metrics for each task type are in model evaluation and metrics and scoring.

Step 2: data and labels

Data work usually dominates the schedule. Check these items early, since they set the ceiling for the model.

  • Coverage and representativeness: does the data look like what the model will see in production, across seasons, regions and user groups? Training on easy-to-collect data is a classic source of failure.

  • Label definition and quality: who produced the labels, how consistent are they (agreement between annotators), and are they delayed or biased by earlier decisions? A model trained on past approvals learns the approver’s habits, not the truth, and it never sees the outcome of rejected cases (selection bias).

  • Volume: how much is needed depends on the model family. Linear models and gradient boosting work with thousands of rows, deep networks usually need far more unless a pretrained model is fine-tuned. Learning curves estimate whether more data would help; see validation and learning curves.

  • Leakage: features that encode the answer, duplicates that appear on both sides of a split, or preprocessing fitted on all the data. Document, for each feature, when its value becomes known.

  • Privacy and rights: personal data, consent and retention limits apply to training data as well as to the service.

  • Logging for the future: log the features and the model output at serving time. These logs are the training data of the next version and the only defence against training-serving skew, described below.

Step 3 and 4: explore, build a baseline, then iterate

Explore the data as described in exploratory data analysis, and build features following feature engineering. Then, before any tuning, build the simplest end-to-end system that produces a prediction and an evaluation number. Two reasons: it exposes plumbing problems while they are cheap, and it sets the baseline every later change has to beat.

A good order of baselines, from least to most effort:

  1. A constant (the majority class or the mean).

  2. A hand-written heuristic that a domain expert would accept.

  3. A simple model such as regularised linear regression or a shallow tree on a few features.

  4. A strong generic model, usually gradient boosting for tabular data and a pretrained network for images, text or audio.

Move down the list only while the improvement justifies the cost. Google’s rules of ML put it as: keep the first model simple and get the infrastructure right. A system with a pipeline that can be tested, deployed and monitored is worth more than a marginally better model that cannot be reproduced. Take notes on every experiment (reproducibility), so that results can be compared fairly.

Step 5: evaluate honestly

Three habits protect the evaluation.

  1. Split the way production will use the model. If the model predicts the future, split chronologically: train on older rows, validate on newer, test on the newest. If rows from the same user or machine are correlated, keep each group on one side of the split (grouped splitting). A random split of correlated or time-ordered rows leaks the future and overstates quality. See train and test splits and cross-validation.

  2. Touch the test set once. Tune on validation data; use the test set for the final number only. Repeated peeking turns the test set into a second validation set.

  3. Evaluate in the units of the decision. Convert errors to cost when costs are known, and choose the decision threshold on validation data, not on the test set.

The example creates time-ordered synthetic data, splits it chronologically, defines the evaluation metric as an expected cost per case (a false negative is ten times worse than a false positive), compares a do-nothing baseline, a heuristic and a gradient boosting model, and picks the decision threshold on the validation part only.

import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score, confusion_matrix

rng = np.random.default_rng(0)
n = 5000
X = rng.normal(size=(n, 5))
logit = 1.2 * X[:, 0] - 0.8 * X[:, 1] + 0.5 * X[:, 2] * X[:, 3] - 2.0
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)

# Rows are ordered by time, so split chronologically: train < validation < test.
tr, va, te = slice(0, 3000), slice(3000, 4000), slice(4000, n)

C_FP, C_FN = 1.0, 10.0   # cost of a false alarm and of a missed case

def expected_cost(y_true, y_pred):
    tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
    return (C_FP * fp + C_FN * fn) / len(y_true)

# Baseline 1: never flag anyone.
never = DummyClassifier(strategy="constant", constant=0).fit(X[tr], y[tr])
# Baseline 2: a heuristic a domain expert might propose (feature 0 above average).
heuristic = lambda A: (A[:, 0] > 0).astype(int)
# Candidate: gradient boosting.
model = HistGradientBoostingClassifier(random_state=0).fit(X[tr], y[tr])

# Choose the decision threshold on validation data only.
p_va = model.predict_proba(X[va])[:, 1]
thresholds = np.linspace(0.05, 0.95, 19)
best_t = min(thresholds, key=lambda t: expected_cost(y[va], (p_va >= t).astype(int)))

p_te = model.predict_proba(X[te])[:, 1]
print("never flag :", expected_cost(y[te], never.predict(X[te])))
print("heuristic  :", expected_cost(y[te], heuristic(X[te])))
print("model      :", expected_cost(y[te], (p_te >= best_t).astype(int)), "at threshold", best_t)
print("average precision on test:", average_precision_score(y[te], p_te))

Output:

never flag : 1.93
heuristic  : 0.705
model      : 0.658 at threshold 0.05
average precision on test: 0.4591723368618831

Source: scikit-learn: Metrics and scoring and HistGradientBoostingClassifier. The cost ratio of ten to one is an assumption of the example; in a real project it comes from the business. The cost-minimising threshold is below 0.5 because misses are expensive, which is the same idea as the decision threshold page describes with TunedThresholdClassifierCV. The exact numbers depend on the random draw; the point is that the model’s cost is below both baselines.

Step 6: launch

Offline quality is necessary and not sufficient. Before a model is switched on for real traffic, verify the following.

  • Training-serving skew is excluded. The same code must compute the features in training and in serving, or the model will be fed inputs that differ from those it learned on. The most robust fix is to ship the preprocessing and the model as one object (a scikit-learn Pipeline) and to log serving-time features for later comparison. Google’s Rules of ML single out skew as a leading cause of silent failure.

  • The model is packaged reproducibly. Record the library versions, the training data snapshot, the code revision and the evaluation numbers next to the artifact. Persisted scikit-learn models are tied to the scikit-learn version that produced them, and loading a pickle or joblib file from an untrusted source can execute arbitrary code; see model persistence and the serving advice in deploying and serving models.

  • There is a fallback. If the model fails, times out or is rolled back, the product should degrade to the heuristic baseline, not to an error.

  • The release is gradual and measured. Use a shadow deployment (the model predicts but its output is not used), then a canary or A/B test against the current system on the business metric. See deployment and release patterns.

  • Latency, memory and cost fit the budget, measured on production hardware.

  • Risks are reviewed: fairness across groups, explanations where needed, privacy, and an owner for incidents. See responsible AI practices.

import json
import platform
import joblib
import numpy as np
import sklearn
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
X = rng.normal(size=(500, 4))
y = (X[:, 0] + rng.normal(scale=0.5, size=500) > 0).astype(int)

# One object holds preprocessing and model, so serving cannot drift from training.
pipe = make_pipeline(
    SimpleImputer(), StandardScaler(), HistGradientBoostingClassifier(random_state=0)
).fit(X, y)

joblib.dump(pipe, "model.joblib")
metadata = {
    "scikit_learn": sklearn.__version__,
    "python": platform.python_version(),
    "features": ["f0", "f1", "f2", "f3"],
    "train_rows": len(X),
    "metric": {"name": "expected_cost", "validation": None},  # fill in from your evaluation
}
with open("model.metadata.json", "w") as f:
    json.dump(metadata, f, indent=2)

# In the serving process (load only files you produced yourself):
served = joblib.load("model.joblib")
print(served.predict_proba(X[:3]))

Source: scikit-learn: Model persistence. The metadata file travels with the artifact so that a mismatch between the training and serving environments is detected at load time. For cross-version or cross-language serving, an interchange format such as ONNX is an alternative; see ONNX and interoperability.

Step 7: monitor and maintain

A model is not finished at launch, because the world keeps changing. Monitor four things.

  1. Inputs: the distribution of each feature against the training distribution (data drift), and the rate of missing or invalid values.

  2. Outputs: the distribution of predicted scores and decisions. A sudden shift often signals an upstream data bug before any label arrives.

  3. Outcomes: the real metric, once labels arrive, which may take days or months. Plan proxies for the delay.

  4. System health: latency, errors and cost.

Retrain on a schedule, on a trigger (a drift alarm), or continuously, whichever the cost of staleness justifies, and verify each new model with the same evaluation and gradual release as the first. Keep the ability to roll back to the previous model and to the heuristic. The patterns are described in drift and regression monitoring and, for training runs, in experiment tracking and MLOps.

A model can also change the world it measures. A recommender decides what users see, so its own outputs shape the next training data (a feedback loop); a fraud model changes attacker behaviour. Keep a portion of traffic with random or baseline decisions, so that unbiased data remains available.

Google’s rules of ML in brief

Google’s "Rules of Machine Learning" collects forty-three practical rules from production experience. Those that bear most directly on project structure are summarised here in the page’s own words.

Theme Practice

Start simple

Launch a heuristic if it is good enough, and make the first model simple. Get the pipeline, logging and evaluation right before adding features.

Infrastructure first

Test the pipeline independently of the model, and make it easy to train, validate and roll back.

Measure

Track metrics from the start, including ones you are not yet optimising, and watch for changes that raise one metric and lower another.

Features

Add features from the data you already have before inventing new sources. Use human-readable names and document the owner and meaning of each.

Skew

Log the features used at serving time, reuse code between training and serving, and test on data from after the training period.

Re-evaluate

Revisit the objective and the heuristic when the model plateaus; the remaining gains may be in the problem definition.

A project checklist

The questions below are a compact form of the checklist that Aurélien Géron proposes in his machine learning textbook, adapted to this page’s structure. Use them at the start and again before launch.

Phase Check

Frame

The decision, the owner and the business metric are written down. The target is precisely defined. The current solution and a baseline exist. ML is justified over rules.

Data

Data sources, access and rights are listed. Labels are defined and sampled for quality. A test set is set aside, split the way production works, and not touched.

Explore

Distributions, missing values, duplicates and leakage candidates are examined. Notes are kept.

Prepare

Cleaning and feature construction are in a pipeline fitted on training data only, so they can run unchanged in serving.

Model

A quick pass across several model families compares them against the baseline with cross-validation. Hyperparameters are tuned on validation data.

Evaluate

Errors are analysed by segment. The result is measured in the units of the decision, with an uncertainty estimate. Fairness checks are run.

Launch

The model is packaged with metadata. Monitoring, a fallback and a retraining plan exist. The release is gradual.

Maintain

Drift and outcomes are tracked, with named owners and alert thresholds.

Common mistakes

  • Starting with the algorithm and discovering at the end that the prediction cannot be used for a decision.

  • Optimising an offline metric nobody has connected to a business outcome.

  • Randomly splitting time-ordered or grouped data, which leaks the future or the entity.

  • Tuning on the test set repeatedly, or reporting the best of many runs as the expected performance.

  • Fitting scalers, imputers or encoders on the full dataset before splitting.

  • Computing features differently in training and in serving.

  • Treating the model as finished at launch, with no monitoring or retraining plan.

  • Skipping the baseline, so that nobody can say how much the model contributed.

  • Ignoring who might be harmed by the model’s errors until a complaint arrives.