#446Temporal Train/Val SplitEasy

Temporal Train/Val Split

Background

"Just shuffle and split 80/20" is the wrong move for any model that will see time-ordered data in production. Random splits leak the future into the training set: the model sees Tuesday's session embeddings while training on Monday's, then fails when only Monday is actually available at serving time. The fix is a temporal split: cut at a timestamp so train is strictly before val.

Problem statement

Implement temporal_split(rows, train_frac=0.8, time_key="timestamp"). Given a list of dict rows containing a timestamp field (or another key the caller names), return (train, val) such that every train row's timestamp is strictly less than every val row's timestamp.

Input

  • rows - list[dict] of records. Each row must contain time_key.
  • train_frac - float in (0,1)(0, 1), the train fraction by row count (default 0.80.8).
  • time_key - str, the dict key for the timestamp (default "timestamp").

Output

  • (train, val) - two lists. train is the earliest train_fracn\lfloor \text{train\_frac}\cdot n\rfloor rows; val is the rest. Both preserve time order.

Examples

Example 1 - canonical 80/20

Input:  rows=[{ts:1}, {ts:2}, {ts:3}, {ts:4}, {ts:5}], train_frac=0.8, time_key="ts"
Output: train=[{ts:1},{ts:2},{ts:3},{ts:4}], val=[{ts:5}]

Example 2 - already unordered input is sorted first

Input:  rows=[{ts:3}, {ts:1}, {ts:2}], train_frac=2/3, time_key="ts"
Output: train=[{ts:1},{ts:2}], val=[{ts:3}]

Constraints

  • The boundary uses floor of train_frac * n so the val set is non-empty as long as n2n \ge 2 and train_frac < 1.
  • Raise ValueError if time_key is missing from any row.
  • Stable sort by timestamp (Python's sorted is already stable).

Notes

  • Why floor. Rounding up would put a row on the boundary into train; for a 5-row 80/20 you'd get train=5, val=0. Floor keeps the val set populated.
  • Group-aware temporal split. If the same user appears in multiple rows, a stricter split also cuts so each user is in one side. That's a sibling problem; this one isolates the temporal cut.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • example unordered 80/20
  • reference two-thirds split
  • sample half split