Skip to content
AI.info

ML data engineering

Prediction Time, Unit of Analysis, and Outcome Horizon

Define subjects, events, episodes, cutoffs, and horizons so examples represent the intended decision.

By the end you can

Example

Grain mistakes that look harmless in SQL

Each of these joins executes successfully, and each one changes the statistical population the model is actually fitted to. How much it changes has been measured.

Take three-dimensional brain MRI. Cut it into two-dimensional slices, then split the slices instead of splitting the subjects. Different slices of the same brain now land in training and in test. Yagis and colleagues did exactly that and reported the result in Scientific Reports in 2021: “slice-level CV erroneously boosted the average slice level accuracy on the test set by 30% on Open Access Series of Imaging Studies (OASIS), 29% on Alzheimer's Disease Neuroimaging Initiative (ADNI), 48% on Parkinson's Progression Markers Initiative (PPMI) and 55% on a local de-novo PD Versilia dataset.” Each of the three public cohorts used 200 subjects, 100 cases and 100 controls. The local de-novo Parkinson's dataset from Versilia had 34.

Nothing was wrong with the model, the features, or the code. The row was the wrong thing, and thirty to fifty-five points of accuracy came out of that alone.

Nor is this an isolated slip. Wen and colleagues surveyed convolutional-network papers on classification of Alzheimer's disease for Medical Image Analysis in 2020. They concluded that “more than half of the surveyed papers may have suffered from data leakage” from splits that put the same subject in train and test. A grain error is the most reproducible mistake in applied machine learning because it never announces itself. The query returns rows. The metrics improve. The improvement is the error.

  • Order prediction: joining five order lines to one order label creates five copies and overweights large baskets.
  • Medical imaging: splitting at the 2D slice level rather than the subject level inflated average slice-level test accuracy by 29 points on ADNI and 48 on PPMI across cohorts of 200 subjects, and by 55 on the 34-subject Versilia data.
  • Subscription churn: mixing account-level labels with user-level features creates ambiguous ownership for shared plans.
  • Machine failure: aggregating sensors after the maintenance ticket opened leaks part of the diagnosis into the features.
  • Ad response: collapsing all impressions into user-day rows loses the item and placement context needed at serving time.

A row is a claim about the world

Every training row makes an assertion: this subject existed in this state at this time. If the assertion is vague, the model learns from an unstable target.

The unit of analysis is the thing one row represents. It may be a transaction, customer-day, machine-hour, hospital encounter, product-week, image, document, or user-item impression.

The correct unit follows the decision. A model that approves one transaction needs transaction-level examples. A model that schedules store inventory may require product-store-week examples.

Many data problems begin when sources use different grains. Joining order lines to orders, device pings to sessions, or repeated laboratory measurements to encounters can silently multiply records.

Leakage has now been counted across the sciences. Sayash Kapoor and Arvind Narayanan surveyed reviews of machine-learning-based science in 2023 and found “17 fields where leakage has been found, collectively affecting 294 papers”. They set out “a detailed taxonomy of eight types of leakage, ranging from textbook errors to open research problems”. Much of what that taxonomy catches is a grain or a time mistake rather than a modelling one. In civil war prediction, once the errors were corrected, they report that “complex ML models do not perform substantively better than decades-old LR models”. Two hundred and ninety-four papers is not a warning about carelessness. It is a description of what happens when the row is defined after the join rather than before it.

Choose the row grain from the prediction decision, then force every source to respect it.

Comparison

Event rows, entity snapshots, and episodes solve different problems

Selecting a grain is not a question of how the table is laid out. It changes labels, how far one row leans on the next, and operational use.

An event-level row turns one observed action or measurement into one example. It is the natural choice for transaction scoring and click prediction: score each card payment at authorization. It can also create many correlated rows for a single entity, and every feature it uses has to have existed before the event it describes.

An entity snapshot represents one entity at a scheduled prediction time — predict customer churn every Monday. It is natural for churn, risk, and account prioritization, and it requires a clear history window and cutoff. Repeated snapshots of the same entity are not independent of one another, so they need grouped or temporal evaluation rather than a random split.

An episode-level row makes a bounded sequence the unit: a visit, a session, a trip, a claim, a support conversation classified after closure. Episode boundaries are frequently inferred rather than observed. A late event can reopen or alter an episode the dataset has already labelled.

These three are not interchangeable descriptions of the same data. Each defines a different population, with different dependence between rows and a different meaning for the same metric. The choice is the first modelling decision a team makes, and usually the only one nobody records.

FigureComparison · 3 columns

Event-level row

One observed action or measurement becomes one example.

  • Natural for transaction scoring and click prediction
  • Can create many correlated rows per entity
  • Needs event-time features available before the event
  • Example: score each card payment at authorization

Entity snapshot

One entity is represented at a scheduled prediction time.

  • Natural for churn, risk, and account prioritization
  • Requires a clear history window and cutoff
  • Repeated snapshots need grouped or temporal evaluation
  • Example: predict customer churn every Monday

Episode-level row

A bounded sequence becomes the unit.

  • Natural for visits, sessions, trips, and claims
  • Episode boundaries may be inferred rather than observed
  • Late events can reopen or alter an episode
  • Example: classify a support conversation after closure

Visual

Entities can contain events, episodes, and windows

The same person or asset can appear at several useful levels, and those levels should not be mixed accidentally. An entity is a persistent subject: a customer, device, merchant, patient, or machine. An episode is a bounded period inside that subject's life — a session, visit, claim, loan, or maintenance cycle. An event is an occurrence with a timestamp, such as a click, payment, reading, or diagnosis. A windowed example is a modelling snapshot that aggregates permitted history before a prediction time.

Collapsing one level into another is not a tidiness concern about joins. It is a named error with a counted prevalence. Kahan and colleagues reviewed 100 cluster randomised trials in 2016. Of the 99 that reported the number of clusters, 64 — 65% — were at risk of an inflated type I error rate. In 14 of them, no clustering-aware analysis was reported at all. In 50, an individual-level analysis had been run on fewer than 40 clusters with no correction. That is roughly two trials in three, in a literature with editors, statisticians and reviewers, making the same mistake a one-to-many join makes silently.

The standards text is explicit about the mechanism. The Cochrane Handbook for Systematic Reviews of Interventions puts it this way: “If the clustering is ignored and cluster-randomized trials are analysed as if individuals had been randomized, resulting confidence intervals will be artificially narrow and P values will be artificially small.” Artificially narrow intervals and artificially small p-values are precisely what a duplicated-label join produces in a model report. Apparent precision, manufactured by counting one subject many times.

The reporting is no better than the analysis. Richardson and colleagues examined 50 reviews covering 201 cluster-randomised trials and found that only 8 of 33 — 24% — reported the method of cluster adjustment. When the nesting is not written down, a reader cannot tell whether it was handled.

FigureLayers · 4 layers
  1. 01

    Entity

    A persistent subject such as a customer, device, merchant, patient, or machine.

  2. 02

    Episode

    A bounded period such as a session, visit, claim, loan, or maintenance cycle.

  3. 03

    Event

    An occurrence with a timestamp, such as a click, payment, reading, or diagnosis.

  4. 04

    Windowed example

    A modeling snapshot that aggregates permitted history before a prediction time.

A persistent entity may generate many episodes, events, and prediction-time snapshots.

Key idea

Outcome horizons create censored examples

Suppose churn is defined as no renewal within 30 days. A customer observed only 10 days ago does not yet have a reliable negative label. The outcome window is incomplete, and marking that customer as non-churn introduces false negatives concentrated near the dataset boundary. The same issue affects defaults, failures, readmissions, fraud confirmations, and any delayed outcome.

Where the horizon starts matters as much as how long it runs. Samy Suissa named the failure in 2008: “Immortal time is a span of cohort follow-up during which, because of exposure definition, the outcome under study could not occur.” The consequence is not extra noise. In the statin and diabetes-progression example, the naive time-fixed analysis reported an adjusted hazard ratio of 0.74 (95% CI 0.58–0.95), an apparent benefit. The correctly time-aligned analysis of the same data gave 1.97 (1.53–2.52), an apparent harm. The treatment did not change. The patients did not change. The outcome did not change. Only the placement of time zero changed, and the sign of the answer went with it. Hernán and colleagues state the rule: time zero must be “the time when the eligibility criteria are met and a treatment strategy is assigned”.

The horizon is sometimes not a modelling choice at all. For Medicare's Hospital Readmissions Reduction Program it is written into federal regulation, in 42 CFR § 412.152: “Readmission is the case of an individual who is discharged from an applicable hospital, the admission of the individual to the same or another applicable hospital within a time period of 30 days from the date of such discharge.” One row is one index discharge from an applicable hospital. The horizon is exactly 30 days. The program was authorised by section 1886(q) of the Social Security Act and applied to payments from 1 October 2012. A dataset built on patients rather than discharges, or on a longer window because it produced a cleaner label, is answering a question no hospital is paid or penalised on.

A correct dataset either waits for the horizon, marks the row as censored, or uses a method designed for incomplete follow-up. Dropping recent rows is nearly always safer than inventing labels for them.

No observed outcome is not the same as a negative outcome when the observation horizon is incomplete.

Steps

Write an example specification before writing the join

One short page agreed up front prevents months of teams disagreeing inside transformation code. Name the subject: the persistent entity and any secondary entity involved in the decision. Fix the decision moment: when the prediction is requested, and which clock establishes that time. Bound the history: the earliest and latest observations allowed in the feature window. Define the outcome: the event, the horizon, and the censoring rule used to assign the target. Declare uniqueness: the key that must identify exactly one example, tested continuously.

The second step is the one that gets skipped, and a widely deployed model shows what skipping it costs. The Epic Sepsis Model runs at hundreds of US hospitals. Wong and colleagues validated it externally on 27,697 patients and 38,455 hospitalizations at Michigan Medicine. Reporting in JAMA Internal Medicine in 2021, they found an area under the curve of 0.63 (95% CI 0.62–0.64), against the developer's reported 0.73–0.83.

The timing result is more damaging than the discrimination result. Ostermayer and colleagues examined 145,885 emergency-department encounters and reported in 2024 that “Providers were alerted with a median lead time of 0 minutes (80% CI, −6 hours and 42 minutes to 12 hours and 0 minutes).” Half the alerts carried no lead time at all. The reported 80% interval around that median runs from a lag of six hours and 42 minutes to a warning of twelve hours.

A prediction that arrives at the moment of the decision it was meant to precede is not an early warning. It is a description of something already happening. That is what an unfixed prediction time produces in the field. If the specification does not say which clock defines the decision moment, and which observations are permitted strictly before it, the cutoff drifts onto the decision itself. The model then reports what a clinician can already see.

FigureProcess · 5 steps
  1. 1. Name the subject

    State the persistent entity and any secondary entity involved in the decision.

  2. 2. Fix the decision moment

    Define when the prediction is requested and which clock establishes that time.

  3. 3. Bound the history

    Specify the earliest and latest observations allowed in the feature window.

  4. 4. Define the outcome

    State the event, horizon, and censoring rule used to assign the target.

  5. 5. Declare uniqueness

    Write the key that must identify exactly one example and test it continuously.

The example key, cutoff time, and outcome horizon should fit in one unambiguous sentence.

Analogy

Frames, clips, possessions, or whole matches

Many cameras record one long sports match. You could train on individual frames, five-second clips, player possessions, or complete matches, and each choice answers a different question. The entity is the player or team. Events are passes and shots. Episodes are possessions, while a snapshot captures the state before a tactical decision.

The analogy holds most tightly at its worst point. Frames from one match are not independent observations of football. They are one match, counted many times. That is exactly what slice-level splitting did to 200 brains. Rows duplicated by a join carry no visual warning, unlike a repeated frame in the video, and they can silently change the training distribution while every dashboard improves.

The unit of analysis determines which question the dataset can answer.

Case

The KDD Cup 2008 patient ID that carried the diagnosis

The winners of KDD Cup 2008 met a nested unit of analysis in a medical dataset and documented it themselves. Claudia Perlich and her co-authors published the winners' report later that year. Siemens had handed competitors 102,294 candidate locations drawn from 1,712 patients, of whom 118 had cancer — a base rate of 6.9%, and roughly 59.8 candidate locations for every patient. Ranking candidate locations and ranking patients are two different tasks over exactly the same rows.

The patient identifier then turned out to carry most of the predictive signal. Identifiers “between 0 and 20,000 (254 patients; 36% malignant)” behaved nothing like those “above 4,000,000 (1044 patients, of them 1.7% malignant)”. A key that means nothing separated a 36% malignancy rate from a 1.7% one — a ratio of 21.2 — and those two bands together held 75.8% of the patients. Against the 6.9% base rate, the low band runs 5.2 times above it and the high band 4.1 times below it.

The identifier is not a feature anyone intended the model to read. And the usual remedy does not reach it. Splitting on patients rather than on locations fixes the duplication of candidate rows, but the identifier leak lives in the patient, so it travels with the patient into whichever fold the patient goes. Choosing the right unit and closing the leak are two separate pieces of work. Doing the first does not do the second.

Figure

The malignancy rate on either side of an identifier range, beside the counts the competition handed out — a leak that is 21.2× in size and covers three quarters of the patients.

Questions that expose an unstable grain

Ask whether two engineers would produce the same row count from the written specification. If not, the grain or boundaries remain ambiguous.

Check whether each serving request maps to exactly one training-example definition. A mismatch means the learner is solving a related but different problem. That question is not house style. It is Guiding Principle 4 of the ten in Good Machine Learning Practice for Medical Device Development, issued jointly on 27 October 2021 by the US Food and Drug Administration, Health Canada and the UK Medicines and Healthcare products Regulatory Agency. The principle is titled “Training Data Sets Are Independent of Test Sets”, and it reads: “Training and test datasets are selected and maintained to be appropriately independent of one another. All potential sources of dependence, including patient, data acquisition and site factors are considered and addressed to assure independence.” Three named sources of dependence — patient, acquisition, site — and the verb is addressed, not assumed absent. The document is non-binding guidance rather than a requirement. But three regulators wrote the same sentence down together, which is a stronger endorsement than most engineering conventions have.

Measure examples per entity and per episode. A few entities dominating the count can reveal duplicate joins, heavy users, repeated snapshots, or operational processes that determine who gets measured.

Finally, inspect a small sample as timelines rather than rows. Timelines make cutoff violations, incomplete horizons, and episode-boundary mistakes easier to see, because the thing that goes wrong in all of them is an ordering, and an ordering is invisible in a row preview.

A stable unit can be explained, keyed, counted, and reconstructed as a timeline.

Key takeaways