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 containtime_key.train_frac-floatin , the train fraction by row count (default ).time_key-str, the dict key for the timestamp (default"timestamp").
Output
(train, val)- two lists.trainis the earliest rows;valis 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 * nso the val set is non-empty as long as andtrain_frac < 1. - Raise
ValueErroriftime_keyis missing from any row. - Stable sort by timestamp (Python's
sortedis 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.
▶ 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