#417Build sliding-window training pairsMedium

Build sliding-window training pairs

Background

To train a model to predict the next value from the previous window values, you slice a time series into overlapping (input window, next value) pairs:

series = [1, 2, 3, 4, 5], window = 2
X = [[1,2], [2,3], [3,4]]   y = [3, 4, 5]

Each row of X is window consecutive values; the matching y is the value right after that window.

Problem statement

Implement sliding_windows(series, window) returning (X, y).

Input

  • series — array-like of length N.
  • windowint, 1window<N1 \le \text{window} < N.

Output

Returns (X, y): X is an np.ndarray of shape (N - window, window); y is an np.ndarray of shape (N - window,).

Examples

Example 1

Input:  series = [1, 2, 3, 4, 5], window = 2
Output: X = [[1,2],[2,3],[3,4]],  y = [3, 4, 5]

Example 2 — bigger window

Input:  series = [1, 2, 3, 4, 5], window = 3
Output: X = [[1,2,3],[2,3,4]],  y = [4, 5]

Constraints

  • X[i] = series[i : i+window], y[i] = series[i+window].
  • There are N - window pairs.
  • Return both as np.ndarray.

Notes

  • This turns a single sequence into a supervised dataset — the standard setup for the many-to-one "predict the next step" task.
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.

  • Reference example
  • Sample bigger window
  • Example float series