Chapter 4 — Defining the Machine Learning Problem
From a real-world need to a precise, testable, and feasible prediction task
| CORE MESSAGE Most machine learning failures begin before model training. A precise problem definition aligns the target, prediction time, data, metric, and decision so that a technically good model is also useful and valid. |
Chapter 4 problem-definition path
REAL-WORLD NEED | PREDICTION TASK | MEASURABLE TARGET | SUCCESS CRITERIA | FEASIBILITY |
Chapter overview
Before choosing an algorithm, a machine learning team must decide exactly what problem it is solving. This chapter turns an imprecise real-world need into a supervised learning specification that can be implemented, evaluated, and defended. The emphasis is on questions that must be answered before training begins: What decision will the prediction support? What is one row? What is the target? When is the prediction produced? Which features are available at that moment? How costly are different errors? What result would count as success?
A well-defined problem creates a stable contract between domain experts, data engineers, data scientists, software teams, and end users. It also prevents common failures such as target leakage, label ambiguity, mismatched evaluation metrics, unrealistic data assumptions, and models that arrive too late to influence a decision.
| KEY IDEA Problem formulation is not a preliminary administrative step. It is part of the technical design of the machine learning system. |
Learning objectives
- Translate a real-world need into a supervised classification or regression task.
- Identify the decision, prediction target, prediction time, users, and error costs.
- Define a measurable target and distinguish target availability from feature availability.
- Recognize target ambiguity, proxy targets, delayed labels, and target leakage.
- Define the correct unit of observation and verify the grain of a dataset.
- Specify technical, business, scientific, and operational success criteria.
- Relate false-positive and false-negative costs to metric and threshold selection.
- Assess whether sufficient data, reliable labels, useful features, and an appropriate use case exist.
- Decide whether machine learning is warranted or a simpler rule-based solution is preferable.
- Write a complete structured machine learning problem statement.
Running example
Throughout the chapter, a telecommunications churn scenario is used as a running example. The organization wants to identify customers who are likely to cancel their subscription soon enough for a retention team to intervene. This apparently simple goal contains several design choices: what “cancel” means, the prediction horizon, the observation date, eligible customers, available features, campaign capacity, the cost of unnecessary contact, and the cost of failing to identify a customer who leaves.
| Element | Running example |
|---|---|
| Domain need | Reduce avoidable customer churn. |
| Decision | Which customers should receive a retention intervention? |
| Unit of observation | One eligible customer at a monthly scoring date. |
| Target | 1 if the customer cancels within the next 30 days; otherwise 0. |
| Prediction time | End of each month, before the retention campaign starts. |
| Typical users | Retention analysts and campaign managers. |
| Primary concern | Capture customers at genuine risk while respecting campaign capacity. |
Chapter map
| Section | Purpose |
|---|---|
| 4.1 From a real-world need to an ML task | Convert a domain problem into a precise prediction-and-decision specification. |
| 4.2 Defining the target variable | Design a measurable, available, unambiguous, leakage-resistant target. |
| 4.3 Defining the unit of observation | Decide what one row represents and align all features and labels to that grain. |
| 4.4 Defining success criteria | Specify how technical and operational success will be measured. |
| 4.5 Feasibility analysis | Determine whether the problem is learnable, useful, and worth solving with ML. |
| Workshop | Formulate a complete supervised learning problem using a structured template. |
4.1 From a Real-World Need to an ML Task
Organizations usually begin with a broad need rather than a machine learning specification: reduce churn, prevent failures, improve student support, detect fraud, estimate demand, prioritize inspections, or automate document routing. The first design task is to transform that need into a prediction that is available at a useful time and supports a concrete action.
Figure 4.1 — Translating a real-world need into an actionable ML task
DOMAIN NEED | DECISION | PREDICTION | TIMING | ACTION |
4.1.1 Understanding the domain problem
A domain problem describes an undesirable condition, an opportunity, or a decision that an organization wants to improve. The machine learning problem is narrower: it defines what information will be estimated from data. These two statements must be related, but they are not interchangeable.
| Domain statement | Weak ML statement | Better ML formulation |
|---|---|---|
| Reduce customer churn. | Predict churn. | At each monthly scoring date, estimate the probability that each active customer will cancel within 30 days so the retention team can prioritize a limited number of offers. |
| Prevent machine downtime. | Predict failures. | Every hour, estimate whether each operating machine will experience a critical failure within the next 24 hours so maintenance can schedule inspection. |
| Improve loan decisions. | Predict risky applicants. | At application time, estimate the probability of a defined repayment failure within 12 months using only information available before the credit decision. |
| Improve sales planning. | Forecast sales. | Predict next-week unit demand per product-store pair early enough to support replenishment. |
| GOOD PRACTICE Start with the decision and workflow, not with the available columns. A dataset can tempt a team into predicting something that is easy to label but operationally irrelevant. |
4.1.2 Identifying the decision to be supported
A prediction has value only when it changes or improves a decision. The team should identify the decision owner, the set of available actions, the constraints on those actions, and how the prediction enters the workflow. For example, a churn probability may be used to rank customers because the campaign team can contact only 2,000 customers per month. In that case, ranking quality at the top of the list may matter more than overall accuracy.
- What decision will be made differently because the model exists?
- What actions are available after a high-risk or high-value prediction?
- Who owns the decision and who is accountable for the outcome?
- Is the action automatic, advisory, or subject to human review?
- Is there a capacity limit, budget, service-level target, or legal constraint?
- What happens when the model is uncertain or input data are incomplete?
| DECISION-FIRST TEST If the team cannot describe the action that follows a prediction, the use case may be analytics rather than a deployable supervised learning problem. |
4.1.3 Defining what should be predicted
The predicted quantity should be stated in operational terms. A classification target requires a precise event or state; a regression target requires a precise numerical measurement. Vague targets such as “high risk,” “good customer,” or “machine health” must be converted into measurable definitions.
| Question | Classification example | Regression example |
|---|---|---|
| What outcome? | Customer cancellation event. | Number of units sold. |
| Prediction horizon | Within the next 30 days. | During the next 7 days. |
| Target definition | 1 if cancellation date falls inside horizon; else 0. | Total units sold in the forecast window. |
| Population | Active customers eligible for intervention. | Active product-store combinations. |
| Output | Probability of churn and/or class. | Expected number of units. |
A simple Python dictionary can make the initial formulation explicit and easy to review with stakeholders.
| PYTHON | Example 4.1 — Representing a problem specification |
| problem = { "objective": "prioritize retention interventions", "unit": "one active customer at month-end", "target": "cancels within next 30 days", "output": "probability of churn", "prediction_time": "month-end before campaign", "user": "retention team" } for key, value in problem.items(): print(f"{key:16s}: {value}") |
4.1.4 Determining when the prediction must be available
Prediction time is the cut-off that separates permissible information from future information. Every feature must be computable at or before this moment. The label usually describes what happens after the prediction time. This temporal separation is central to preventing leakage.
Figure 4.2 — Features come from the past; the target is observed in the future
FEATURE WINDOW | PREDICTION TIME | TARGET HORIZON |
For a churn model scored on 31 January, features might summarize behavior through 31 January and the target might indicate whether cancellation occurs from 1 February through 2 March. A feature such as “cancellation_reason” would be unavailable at scoring time and therefore invalid, even if it is highly predictive in historical data.
| Timing concept | Question | Example |
|---|---|---|
| Observation date | At what point is one example created? | 31 January. |
| Feature window | Which past period may be summarized? | Previous 90 days. |
| Prediction time | When must the model output exist? | Before campaign selection on 1 February. |
| Prediction horizon | How far into the future is the target defined? | Next 30 days. |
| Label maturity | When can the final label be known? | After the 30-day horizon closes. |
4.1.5 Identifying who will use the result
The user of the model influences output format, explanation requirements, latency, thresholding, and interface design. A data scientist reviewing a batch table can tolerate different outputs from a call-center agent who must act within seconds or an automated control system that requires millisecond latency.
| User context | Design implication |
|---|---|
| Human analyst ranking cases | Provide scores, ranking, filters, and explanations. |
| Operational agent handling one case | Return a fast, concise recommendation with key reasons. |
| Automated system | Define strict latency, reliability, fallback, and monitoring requirements. |
| Researcher | Emphasize reproducibility, uncertainty, statistical validity, and transparent methodology. |
| Manager | Connect technical metrics to capacity, cost, and expected operational impact. |
4.1.6 Determining the cost of incorrect predictions
Errors are rarely symmetric. In binary classification, a false positive and a false negative often lead to different actions and consequences. The team should define these consequences before choosing a metric or decision threshold.
| Outcome | Churn example | Potential consequence |
|---|---|---|
| True positive | High risk; customer actually churns. | Intervention reaches a customer who genuinely needs attention. |
| False positive | High risk; customer would have stayed. | Offer cost, unnecessary contact, possible customer annoyance. |
| False negative | Low risk; customer churns. | Missed opportunity to retain the customer and lost future value. |
| True negative | Low risk; customer stays. | No retention cost is incurred. |
| IMPORTANT The preferred metric should reflect the real error structure. For example, recall emphasizes missed positive cases, precision emphasizes unnecessary positive actions, and cost-sensitive evaluation can encode both explicitly. |
| PYTHON | Example 4.2 — Quantifying asymmetric error costs |
| # Simple expected-cost calculation for a binary classifier false_positives = 180 false_negatives = 45 cost_fp = 4.0 # unnecessary retention offer/contact cost_fn = 120.0 # estimated value lost when churn is missed expected_cost = false_positives * cost_fp + false_negatives * cost_fn print(f"Estimated decision cost: {expected_cost:,.2f}") |
| 4.1 CHECKPOINT A candidate ML task is much clearer when you can state the decision, prediction, unit, population, prediction time, horizon, user, available actions, and relative error costs in one paragraph. |
4.2 Defining the Target Variable
The target variable is the value the model learns to predict. It must be measurable, correctly aligned with each observation, and available as historical ground truth. Poor labels place a hard ceiling on model quality because the algorithm is trained to reproduce the target definition, including its noise and biases.
4.2.1 Choosing a measurable target
A useful target definition specifies the event or quantity, the measurement rule, the time horizon, the eligible population, and any exclusions. The definition should be executable: two people implementing it independently should obtain the same labels from the same source data.
| Vague target | Measurable target |
|---|---|
| Customer is likely to leave. | 1 if a voluntary service cancellation is recorded within 30 days after scoring; 0 otherwise. |
| Machine will fail soon. | 1 if a critical fault code requiring shutdown occurs within 24 hours after the hourly observation. |
| Student performs poorly. | Final course score on a 0–100 scale, or a clearly defined pass/fail label. |
| High-value transaction. | Net transaction value in the accounting system after returns are finalized. |
4.2.2 Target availability
Historical training requires labels for past examples. The team should identify the authoritative source of truth, the delay before labels become complete, and whether some outcomes remain unobserved. For instance, a 90-day default label cannot be finalized until at least 90 days after the decision date. Training on more recent observations may therefore create artificially negative labels that have not yet had enough time to mature.
- Where is the ground truth stored?
- How long after prediction time does the label become final?
- Can the event occur without being recorded?
- Are some observations censored because follow-up is incomplete?
- Has the label definition changed over time?
- Are labels available for all groups and all operating conditions?
4.2.3 Target quality
Target quality includes correctness, consistency, completeness, timeliness, and agreement with the intended concept. A model cannot reliably exceed the quality of its labels. Manual labels may suffer from reviewer disagreement; administrative labels may reflect policy rather than the underlying concept; sensor-derived labels may contain calibration errors.
| Quality dimension | Diagnostic question | Possible check |
|---|---|---|
| Correctness | Does the label represent the real outcome? | Audit a random sample against primary records. |
| Consistency | Is the same rule applied across time and sites? | Compare label rates and definitions by period/source. |
| Completeness | Are positive and negative outcomes both observed? | Measure missing or unresolved label rate. |
| Timeliness | Is the label mature when training data are extracted? | Enforce a maturity cutoff. |
| Reliability | Would two reviewers agree? | Estimate inter-rater agreement for manual labels. |
4.2.4 Target ambiguity
Ambiguity occurs when the target has multiple legitimate interpretations. Churn can mean contract cancellation, inactivity for a fixed period, non-renewal, or migration to another product. “Fraud” may mean suspected fraud, confirmed fraud, or a chargeback. These definitions produce different datasets and different models.
| RESOLUTION RULE Document inclusion and exclusion rules, edge cases, horizon boundaries, time zone, status codes, and treatment of unknown outcomes. Ambiguity should be resolved before model comparison. |
4.2.5 Target leakage
Target leakage occurs when the training inputs contain information that would not legitimately be available at prediction time or that directly encodes the future target. Leakage can produce spectacular validation scores and unusable deployed models.
| Leakage example | Why it is invalid | Safer alternative |
|---|---|---|
| Cancellation reason used to predict churn | Reason is recorded after cancellation. | Use behavior available before scoring. |
| Final diagnosis used to predict initial triage outcome | Diagnosis may be established after the prediction moment. | Use measurements and notes available at triage time. |
| Refund status used to predict transaction fraud | Refund can be a consequence of fraud investigation. | Use transaction-time information only. |
| Dataset-wide target mean encoded into a feature | Information from validation/test labels leaks into training representation. | Fit target-dependent transformations inside training folds only. |
| LEAKAGE WARNING A suspiciously strong feature should trigger a semantic and temporal review. High predictive power is not evidence that the feature is valid. |
| PYTHON | Example 4.3 — Screening features by availability time |
| # A simple metadata-based availability check features = { "tenure_months": "before_prediction", "support_tickets_90d": "before_prediction", "cancellation_reason": "after_prediction", "final_account_status": "after_prediction" } invalid = [name for name, timing in features.items() if timing == "after_prediction"] print("Potential leakage features:", invalid) |
4.2.6 Proxy variables
A proxy target is an observable variable used in place of the concept the organization actually cares about. Proxies may be necessary when the desired outcome is difficult or expensive to measure, but they change the meaning of the model. For example, “support ticket escalation” might be used as a proxy for customer dissatisfaction, yet many dissatisfied customers never submit a ticket.
| Desired concept | Possible proxy | Risk |
|---|---|---|
| Customer satisfaction | Complaint or escalation | Misses silent dissatisfaction and reflects reporting behavior. |
| Equipment degradation | Alarm code | Alarm policy and sensor thresholds may change. |
| Knowledge mastery | Exam score | Measures test performance imperfectly and may reflect other factors. |
| True demand | Observed sales | Sales are censored when stockouts prevent purchases. |
When a proxy is used, the project should explicitly say “predict the proxy” rather than claiming to predict the latent concept. Stakeholders should validate whether improving the proxy is expected to improve the real objective.
4.2.7 Delayed labels
Some targets are known only after a delay. Delayed labels affect dataset cutoffs, model monitoring, retraining frequency, and online evaluation. The newest records may be usable for prediction but not yet usable as labeled training examples.
| PYTHON | Example 4.4 — Excluding observations whose labels are not mature |
| import pandas as pd as_of = pd.Timestamp("2026-08-31") label_horizon_days = 30 data = pd.DataFrame({ "prediction_date": pd.to_datetime([ "2026-06-30", "2026-07-31", "2026-08-20" ]) }) data["label_mature"] = ( data["prediction_date"] + pd.to_timedelta(label_horizon_days, unit="D") <= as_of ) print(data) |
| Target specification field | Example |
|---|---|
| Target name | churn_30d |
| Type | Binary classification label |
| Positive event | Voluntary cancellation of the main subscription |
| Horizon | (prediction time, prediction time + 30 days] |
| Negative label | Eligible customer with no positive event during the full horizon |
| Unknown label | Insufficient follow-up, unresolved account status, or data-quality failure |
| Authoritative source | Subscription lifecycle table |
| Maturity delay | 30 days plus source-system reporting delay |
4.3 Defining the Unit of Observation
The unit of observation—also called the data grain—is what one row represents at prediction time. Every feature and target must be aligned to this unit. A model trained on a mixture of grains can double-count entities, leak future information, and produce misleading evaluation results.
4.3.1 Typical units of observation
| Unit | Example prediction | Typical identifier |
|---|---|---|
| One customer | Will this customer churn in the next 30 days? | customer_id + scoring_date |
| One transaction | Is this transaction fraudulent? | transaction_id |
| One patient visit | Will this visit lead to a defined outcome? | visit_id |
| One machine cycle | Will the cycle fail quality inspection? | machine_id + cycle_id |
| One image | Which class is shown in this image? | image_id |
| One day | What will tomorrow’s demand be for this location? | location_id + date |
| One sensor window | Does this 10-second window contain an anomaly? | sensor_id + window_start |
4.3.2 Entity, event, and time-window grains
The same source system can support different units. A transaction table naturally has one row per event, but a churn model may need one row per customer per month. The event records must then be aggregated using only events before the scoring date. Conversely, a fraud model may preserve one row per transaction and add customer-history features calculated from prior transactions.
| Grain | Strength | Risk if misused |
|---|---|---|
| Entity-level | Simple for one prediction per entity. | Can hide temporal changes and repeated decisions. |
| Event-level | Fits real-time decisions for individual events. | Repeated events from the same entity can leak across train/test splits. |
| Entity-time snapshot | Supports recurring predictions over time. | Requires careful feature windows and label horizons. |
| Fixed sensor window | Transforms streaming signals into comparable samples. | Overlapping windows can create near-duplicate train/test examples. |
4.3.3 Checking row uniqueness
The candidate primary key should uniquely identify one observation. Duplicate keys may indicate accidental joins, repeated exports, multiple events at the same grain, or a missing dimension such as time. The proper response depends on semantics; duplicates should not be removed automatically without understanding why they exist.
| PYTHON | Example 4.5 — Verifying the proposed observation key |
| import pandas as pd snapshots = pd.DataFrame({ "customer_id": [101, 101, 102, 103], "scoring_date": ["2026-07-31", "2026-07-31", "2026-07-31", "2026-07-31"] }) key = ["customer_id", "scoring_date"] duplicate_rows = snapshots.duplicated(key, keep=False) print(snapshots.loc[duplicate_rows]) |
4.3.4 Constructing an entity-time observation
When raw data contain many events per entity, features can summarize a historical window relative to the prediction date. The aggregation must stop at the prediction cutoff. A correct feature such as “number of support tickets in the previous 90 days” uses only past events; a count that accidentally includes the target horizon would leak future behavior.
In a real temporal problem, first filter events to the permitted historical feature window.
| PYTHON | Example 4.6 — Aggregating event data to one row per entity |
| import pandas as pd transactions = pd.DataFrame({ "customer_id": [1, 1, 1, 2, 2], "amount": [20, 35, 15, 50, 40] }) customer_features = ( transactions.groupby("customer_id") .agg(transaction_count=("amount", "size"), total_amount=("amount", "sum"), mean_amount=("amount", "mean")) .reset_index() ) print(customer_features) |
| UNIT-OF-OBSERVATION TEST Complete this sentence without ambiguity: “At prediction time, one row represents ____.” Then verify that every feature and target can be defined for exactly that row. |
4.4 Defining Success Criteria
Success criteria determine how the project will be evaluated and whether it should proceed to deployment. They should be defined before extensive model experimentation so that the team does not choose whichever metric happens to make a model look best. A complete definition combines technical quality, domain value, operational feasibility, and risk constraints.
4.4.1 Technical metrics
Technical metrics quantify predictive performance on data that were not used to fit the model. Metric choice depends on the target and the decision. No single metric is best for every problem.
| Task | Metric | What it emphasizes |
|---|---|---|
| Binary classification | Precision | How often predicted positives are truly positive. |
| Binary classification | Recall / sensitivity | How many actual positives are detected. |
| Classification | F1-score | Balance between precision and recall. |
| Classification | ROC AUC | Ranking quality across thresholds. |
| Imbalanced classification | Average precision / PR AUC | Positive-class ranking when positives are rare. |
| Probability prediction | Log loss / Brier score | Quality of predicted probabilities. |
| Regression | MAE | Typical absolute error in target units. |
| Regression | RMSE | Penalizes larger errors more strongly. |
| Regression | R² | Performance relative to a mean-prediction baseline. |
4.4.2 Business metrics
A technically accurate model may still have little operational value. Business criteria connect predictions to outcomes such as savings, revenue, workload, conversion, retention, inventory cost, or resource utilization. These outcomes are affected by both model quality and the intervention process.
| Model metric | Business/operational counterpart |
|---|---|
| Recall among high-risk customers | Fraction of preventable churn cases reached by the campaign. |
| Precision in top 2,000 scores | Share of limited campaign capacity spent on genuinely at-risk customers. |
| MAE in demand forecast | Expected unit-level planning error and associated over/under-stock cost. |
| False-positive rate | Volume of unnecessary manual reviews or interventions. |
| Latency | Whether a prediction arrives early enough to affect the decision. |
4.4.3 Scientific objectives
In research, success may include statistical validity, reproducibility, robustness, uncertainty quantification, performance across datasets, or evidence that a proposed method improves a defined baseline. The scientific claim should determine the experiment design. A tiny score increase on one split may be insufficient if the research question concerns robustness or generalization.
- Predefine primary and secondary metrics.
- Use repeated or cross-validated evaluation when appropriate.
- Report variability and uncertainty rather than only a single score.
- Compare against meaningful baselines under matched conditions.
- Evaluate failure modes relevant to the claimed contribution.
- Keep the final test protocol fixed once defined.
4.4.4 Operational constraints
A model operates inside a system. The acceptable solution is constrained by prediction latency, throughput, memory, hardware, uptime, data refresh frequency, explainability, review capacity, and maintenance cost. These requirements can rule out otherwise strong algorithms.
| Constraint | Example requirement | Why it matters |
|---|---|---|
| Prediction latency | < 200 ms per transaction | The decision must occur before authorization completes. |
| Batch deadline | Score all customers by 06:00 | Campaign preparation starts at 07:00. |
| Interpretability | Provide top reasons for each flagged case | Human reviewers need an actionable explanation. |
| Review capacity | Maximum 500 cases/day | Threshold must respect available investigators. |
| Infrastructure | CPU-only environment | Large GPU-dependent models may be impractical. |
| Data freshness | Features no older than 15 minutes | Stale signals reduce decision quality. |
4.4.5 Minimum acceptable performance
The team should define a performance floor relative to a baseline and to operational needs. “Better than random” is rarely sufficient. A useful acceptance rule might be: the model must improve recall at fixed review capacity by at least 15% over the current rule while maintaining a maximum false-positive rate and a specified latency.
| BASELINE PRINCIPLE A success threshold should be expressed relative to something meaningful: the current process, a simple rule, a dummy predictor, a previous model, or a minimum operational requirement. |
4.4.6 Prediction latency and availability
Latency is the time from receiving an eligible case to delivering the prediction. End-to-end latency includes feature retrieval and preprocessing, not only the estimator’s execution time. For batch systems, the equivalent requirement is often a completion deadline and maximum acceptable data age.
4.4.7 Interpretability requirements
Interpretability can be a mandatory requirement when predictions support expert review, regulated decisions, safety-sensitive processes, or scientific conclusions. Requirements should be concrete: global feature behavior, per-prediction reason codes, monotonic relationships, sparse models, or documentation of influential features. “The model must be interpretable” is too vague to guide model selection.
4.4.8 Cost of false positives and false negatives
When decisions have measurable costs, a threshold can be selected by minimizing expected cost on validation data. The chosen cost values should come from domain analysis rather than from model performance. Costs may include money, labor, opportunity loss, delays, customer burden, or safety impact.
| PYTHON | Example 4.7 — Comparing decision thresholds using error costs |
| import numpy as np from sklearn.metrics import confusion_matrix # y_true and p are validation labels and predicted probabilities # Example values for demonstration only y_true = np.array([0, 0, 1, 1, 0, 1, 0, 1]) p = np.array([.10, .35, .80, .55, .60, .45, .20, .90]) cost_fp, cost_fn = 4, 120 for threshold in [0.3, 0.5, 0.7]: pred = (p >= threshold).astype(int) tn, fp, fn, tp = confusion_matrix(y_true, pred).ravel() cost = fp * cost_fp + fn * cost_fn print(threshold, "FP=", fp, "FN=", fn, "cost=", cost) |
| Success criterion type | Example statement |
|---|---|
| Technical | Average precision ≥ 0.45 on the locked evaluation protocol. |
| Operational | Score the monthly population in less than 20 minutes. |
| Capacity | Return at most 2,000 intervention candidates per month. |
| Business | Improve retained value per contacted customer over the current rule. |
| Interpretability | Provide stable per-customer reason codes to campaign analysts. |
| Reliability | If required features are missing, route the case to a documented fallback. |
4.5 Feasibility Analysis
A well-defined prediction can still be infeasible. Feasibility analysis asks whether the organization has enough relevant data, labels are trustworthy, the target contains a learnable signal, necessary features are available at prediction time, and machine learning adds value over simpler alternatives. It is better to discover a fundamental limitation before months of modeling work.
4.5.1 Is sufficient data available?
Dataset size should be judged in relation to problem difficulty, number of features, model complexity, class frequency, temporal diversity, and the number of independent entities. Ten million duplicated or highly correlated rows may contain less information than a smaller diverse dataset.
- How many independent observations are available?
- How many positive examples exist for each important class?
- Does the history cover different seasons, sites, devices, or operating conditions?
- Are rare but important situations represented?
- Can a valid train/validation/test split be created without starving any subset?
- Will the deployed population resemble the historical population?
4.5.2 Are the labels reliable?
Reliable labels are a prerequisite for supervised learning. If the label process is inconsistent, biased, incomplete, or heavily delayed, improving the label pipeline may yield more value than trying increasingly complex algorithms. A pilot label audit should examine examples from different time periods and subgroups.
| FEASIBILITY WARNING If labels are generated by an old decision rule, a model trained on them may learn the old process rather than the underlying outcome. This is especially important when historical actions influence which outcomes are observed. |
4.5.3 Is the target predictable?
Some outcomes are dominated by random events or by factors that are not observable before prediction time. A model can only learn signal contained in the available features. Early feasibility experiments can compare simple baselines, inspect feature-target relationships, and estimate an achievable range without extensive tuning.
Predictability is not the same as causality. A feature can help prediction without being a cause, and a causal factor may be unavailable or too noisy to improve prediction. The project should be explicit about whether the goal is predictive, explanatory, or causal.
4.5.4 Are the features available at prediction time?
Historical databases often contain columns that are convenient for retrospective analysis but unavailable online, delayed by hours or days, expensive to compute, or produced after the decision. A feature inventory should record source system, refresh rate, computation time, historical coverage, and prediction-time availability.
| Feature | Historical availability | Prediction-time availability | Decision |
|---|---|---|---|
| tenure_months | Yes | Yes | Use |
| support_tickets_90d | Yes | Yes after nightly aggregation | Use for batch scoring |
| cancellation_reason | Yes | No; created after target event | Exclude |
| credit_bureau_score | Partial | Available but costly | Evaluate cost-benefit |
| real_time_sensor_fft | Not stored historically | Available online only | Cannot train directly until history is collected |
4.5.5 Is machine learning necessary?
Machine learning is useful when decisions depend on patterns that are difficult to encode manually, data are sufficiently rich, performance can improve with learning, and the decision occurs often enough to justify development and maintenance. It is not automatically the best solution.
| Prefer a rule-based approach when… | Consider machine learning when… |
|---|---|
| The policy is deterministic and stable. | Relationships are complex, interacting, or difficult to express as rules. |
| A few transparent conditions solve the problem adequately. | Historical examples show useful predictive signal beyond simple rules. |
| Very little labeled data exist. | Enough representative labeled data are available. |
| Errors from an opaque model are unacceptable. | Validation, monitoring, and human oversight can manage model risk. |
| The process changes so quickly that training data become obsolete. | Patterns are sufficiently stable to generalize between retraining cycles. |
4.5.6 Would a simple baseline be sufficient?
A baseline is not merely an evaluation formality. It can answer whether the proposed ML system is worth its complexity. A business rule, historical average, majority-class predictor, or simple linear model may already satisfy the objective. If a complex model offers only a negligible improvement, the simpler solution may be more reliable, explainable, and maintainable.
| PYTHON | Example 4.8 — A lightweight dataset-feasibility report |
| def feasibility_report(df, target, required_features): report = {} report["rows"] = len(df) report["target_missing_rate"] = df[target].isna().mean() report["target_unique_values"] = df[target].nunique(dropna=True) report["missing_required_features"] = [ col for col in required_features if col not in df.columns ] if set(df[target].dropna().unique()).issubset({0, 1}): report["positive_rate"] = df[target].mean() return report # Use this as a starting point; domain-specific checks are still required. |
Feasibility decision matrix
| Dimension | Green — proceed | Amber — resolve risk | Red — reformulate or stop |
|---|---|---|---|
| Data volume | Representative history and enough independent examples. | Some sparse groups or short history. | Too few examples for valid training/evaluation. |
| Labels | Clear, reliable, mature labels. | Noise or delay can be audited and improved. | No trustworthy ground truth. |
| Feature availability | Key signals exist at prediction time. | Engineering work required. | Useful signals are available only after outcome. |
| Operational action | Prediction changes a real decision. | Action exists but process is not finalized. | No action follows the prediction. |
| Baseline value | Current method leaves meaningful room for improvement. | Benefit may be modest. | Simple rule already satisfies the need. |
| Monitoring | Outcomes and inputs can be tracked. | Some monitoring gaps. | No way to observe post-deployment behavior. |
| GO/NO-GO PRINCIPLE A “no-go” result can be a successful technical outcome if it prevents building a model that cannot be trained, evaluated, or used responsibly. The next step may be better data collection, label redesign, process redesign, or a simpler rule. |
Workshop — Formulate a Supervised Learning Problem
In this workshop, students transform a short real-world scenario into a structured machine learning problem statement. The goal is not to train a model. The goal is to define a task that another team could implement without guessing the meaning of the target, the timing, or the success criteria.
Workshop scenario
| SCENARIO A subscription-based digital service has noticed that some customers cancel unexpectedly. A retention team can make personalized offers to at most 1,000 customers each week. Management wants a data-driven method to prioritize whom to contact. Historical data include subscription dates, plan type, weekly usage, billing history, support contacts, campaign history, and cancellation dates. |
Student task
Prepare a one-page problem specification using the eight required fields below. Every statement should be measurable and tied to a specific point in time.
| Field | Questions students must answer |
|---|---|
| Objective | What real-world outcome should improve? What is the intended benefit? |
| Inputs | Which information categories may be used, and which are definitely excluded? |
| Target | What exact event or numerical value is predicted? What is the horizon? |
| Prediction time | When is the score produced? Which data are available by then? |
| Users | Who receives the output and what action do they take? |
| Constraints | Capacity, latency, interpretability, data freshness, legal or operational limits. |
| Evaluation metric | Which primary technical metric matches the decision and error costs? |
| Baseline | What simple or current method must the model improve upon? |
Step 1 — Define the objective and decision
- Rewrite “reduce churn” as an operational objective.
- State the decision: which customers should receive one of the limited weekly retention contacts?
- Identify the decision owner and the maximum action capacity.
Step 2 — Define the unit and prediction time
- Choose whether one row represents a customer, customer-week, customer-month, or another unit.
- Choose a weekly scoring date that occurs before campaign assignment.
- State the feature window and ensure all candidate features are available before the cutoff.
Step 3 — Define the target
- Choose a prediction horizon such as 30 days.
- Define exactly which cancellation statuses count as a positive event.
- Specify how insufficient follow-up or unresolved account states are handled.
- Identify the authoritative source of cancellation dates.
Step 4 — Define success criteria
- Select a metric that reflects limited campaign capacity and the importance of finding likely churners.
- Define a minimum improvement over the current process.
- Specify the maximum number of customers returned each week.
- Define required prediction completion time and explanation needs.
Step 5 — Perform a feasibility review
- Check whether enough positive churn cases exist historically.
- Check whether labels are mature and consistently recorded.
- List features that are available only after cancellation and must be excluded.
- Determine whether a simple rule might already meet the business need.
Workshop worksheet
| Problem statement field | Student formulation |
|---|---|
| Objective | |
| Inputs | |
| Target | |
| Prediction time | |
| Users | |
| Constraints | |
| Evaluation metric | |
| Baseline |
Illustrative solution
| ONE VALID FORMULATION Each Monday at 05:00, score every active customer who is eligible for a retention offer and estimate the probability of voluntary cancellation during the next 30 days. Use only subscription, usage, billing, support, and prior-campaign information finalized before the weekly cutoff. Rank eligible customers and provide the top 1,000 to the retention team with concise reason codes. Evaluate primarily using precision and recall within the top 1,000, compare against the current prioritization rule, and require the batch to complete before 07:00. |
| Field | Illustrative answer |
|---|---|
| Objective | Increase effective retention by focusing limited contacts on customers at elevated near-term churn risk. |
| Inputs | Pre-cutoff subscription, usage, billing, support, and prior campaign history; exclude cancellation-derived fields. |
| Target | Binary: voluntary cancellation within 30 days after weekly scoring. |
| Prediction time | Every Monday before the campaign list is built. |
| Users | Retention campaign analysts and agents. |
| Constraints | Top 1,000 customers/week; batch before 07:00; explanations required; fallback for missing critical features. |
| Evaluation metric | Top-k precision/recall or recall at fixed capacity; probability quality as secondary metric. |
| Baseline | Current business prioritization rule or a simple risk-score baseline. |
Workshop evaluation rubric
| Criterion | Excellent evidence | Points |
|---|---|---|
| Objective and decision | Links prediction to a concrete action and domain outcome. | 15 |
| Target definition | Event, horizon, inclusions/exclusions, and source are unambiguous. | 20 |
| Timing and unit | Observation grain, scoring time, feature window, and horizon align. | 20 |
| Users and constraints | Identifies user, capacity, latency, interpretability, and fallback needs. | 15 |
| Evaluation metric | Metric matches error costs and operational decision. | 15 |
| Baseline and feasibility | Defines a meaningful comparator and checks data/label/feature viability. | 15 |
Knowledge check
| # | Question |
|---|---|
| 1 | Why is “predict churn” an incomplete machine learning problem statement? |
| 2 | What is the difference between prediction time and target horizon? |
| 3 | Give one example of target leakage and explain why it creates optimistic evaluation results. |
| 4 | Why might observed sales be a problematic proxy for customer demand? |
| 5 | What does the unit of observation determine? |
| 6 | Why should success criteria be chosen before extensive model experimentation? |
| 7 | When can a false positive be more costly than a false negative? Give an example. |
| 8 | Why can the newest data be unusable for supervised training even though they are available in the database? |
| 9 | Name two situations in which a rule-based solution may be preferable to machine learning. |
| 10 | What does a feasibility “red flag” tell the team to do next? |
Suggested answers
- 1. It does not define the population, target event, time horizon, prediction time, user, action, or success criterion.
- 2. Prediction time is when the model output must be available; the target horizon is the future period over which the outcome is defined.
- 3. Example: using cancellation_reason to predict churn. It is recorded after churn, so historical evaluation sees information unavailable at deployment.
- 4. Sales can be censored by stockouts: low observed sales may reflect unavailable inventory rather than low demand.
- 5. It defines what one row represents and therefore how features, labels, keys, splits, and aggregations must be constructed.
- 6. Predefining criteria prevents metric shopping and keeps model selection aligned with the real objective.
- 7. When acting on a false alert is expensive or harmful—for example, sending costly manual inspections for many non-failing machines.
- 8. The label may be delayed; the required follow-up horizon has not yet elapsed, so recent negative labels are not mature.
- 9. When a few stable transparent rules already solve the task, or when labeled data are insufficient for valid training and evaluation.
- 10. Reformulate the task, improve data or label collection, redesign the process, choose a simpler method, or stop the project rather than forcing modeling.
Chapter summary
Defining the machine learning problem creates the foundation for every later step in the supervised learning workflow. A valid formulation begins with a real decision, defines a precise prediction available at the right time, establishes one clear unit of observation, and aligns features with a measurable target. The target must be trustworthy, mature, and free from future information. Success criteria should combine predictive performance with business or scientific value, operational constraints, error costs, latency, and interpretability. Finally, feasibility analysis determines whether sufficient representative data, reliable labels, useful prediction-time features, and a genuine need for machine learning exist.
| BEFORE MOVING TO DATA LOADING Write the problem specification first. If the objective, unit, target, prediction time, users, constraints, evaluation metric, and baseline cannot be stated clearly, the dataset is not yet ready to drive model development. |
| Before training, confirm… | Evidence |
|---|---|
| Objective and decision | A prediction is tied to a defined action or scientific question. |
| Unit of observation | One row has an unambiguous meaning and key. |
| Target | The target is measurable, reliable, mature, and temporally valid. |
| Features | Required inputs exist at prediction time. |
| Timing | Feature window, prediction time, and target horizon are explicit. |
| Success | Primary metric, acceptance threshold, and operational constraints are predefined. |
| Baseline | A meaningful current or simple alternative is identified. |
| Feasibility | Data, labels, signal, infrastructure, and monitoring are adequate. |