#415Prepare RNN data — scale, window, reshapeMedium

Prepare RNN data — scale, window, reshape

Background

The lab's prepare_data turns a raw 1-D series into RNN-ready tensors in three moves:

  1. Min-max scale to [0,1][0, 1]: x~=(xmin)/(maxmin)\tilde{x} = (x - \min)/(\max - \min).
  2. Sliding window: each input is seq_len consecutive scaled values; the target is the next value.
  3. Reshape inputs to (N, seq_len, 1) and targets to (N, 1) — the (B, T, F) / (B, O) shapes nn.RNN expects.

Problem statement

Implement prepare_rnn_data(series, seq_len) returning (X, y).

Input

  • series — array-like of length L (raw values).
  • seq_lenint, the window length.

Output

Returns (X, y): X is shape (L - seq_len, seq_len, 1), y is shape (L - seq_len, 1), both min-max scaled.

Examples

Example 1

Input:  series = [10, 20, 30, 40, 50], seq_len = 2
Output: X = [[[0.0],[0.25]], [[0.25],[0.5]], [[0.5],[0.75]]]   shape (3, 2, 1)
        y = [[0.5], [0.75], [1.0]]                              shape (3, 1)

Explanation: scaled series is [0, 0.25, 0.5, 0.75, 1.0]; windows of 2 predict the next value.

Constraints

  • Scale the whole series first with global min/max.
  • Window with stride 1: X[i] = scaled[i:i+seq_len], y[i] = scaled[i+seq_len].
  • Reshape X to (N, seq_len, 1) and y to (N, 1).

Notes

  • Scaling is essential: raw prices in the hundreds make the network's job far harder than values in [0,1][0, 1].
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 worked
  • reference arange window
  • sample step of two