How to split each window into features and a target (Forecast, version 4)?
This is version 4 of the forecasting series, and the last version before training begins. Version 4 cuts every window into two parts: the features, which are the days the model is allowed to look at, and the target, which is the day it must guess.
Features and target
Take one window of 30 days. The first 29 days are what the model will see; the 30th day is what it must predict. This turns each window into one training example. The two parts have names that are worth remembering, because every later version uses them:
- Features — the 29 known days. The input.
- Target — the 30th day. The answer the model is graded against.
Because the last sales values in every window is used as the target, a window of 30 yields 29 features, not 30. That is why 29 appears throughout this program.
How the program works
1. Import torch, its data tools, and pandas
import torch
from torch.utils.data import TensorDataset, DataLoader
import pandas as pd
TensorDataset pairs up features with targets.
DataLoader serves those pairs to the model in batches. pandas reads
the CSV file.
2. Cut and split in one function
def create_sliding_windows_with_target(data, window_size, shift=1):
windows = data.unfold(0, window_size, shift)
row_n = windows.shape[0]
col_n = windows.shape[1]
features = windows[0:row_n, 0:col_n-1] # All columns except the last
targets = windows[0:row_n, col_n-1:col_n] # Just the last column
return features, targets
The first line is version 3's cutting, unchanged. windows.shape then reports the
size of the result: row_n is how many windows there are, col_n is
how long each one is.
The next two lines do the split. windows[0:row_n, 0:col_n-1] means
every row, columns 0 up to but not including the last, which is the 29 known days.
windows[0:row_n, col_n-1:col_n] means every row, the last column only,
which is the answer. The comment on each line says the same thing in fewer words, and the
last line returns features and targets.
3. Load the real sales file
df = pd.read_csv('time_series.csv')
series = df['series'].values
series_tensor = torch.tensor(series, dtype=torch.float32)
window_size = 30
The first two lines bring in the 1,460 daily sales figures. The third line converts them from
a plain array into a PyTorch tensor, which is simply the format PyTorch uses
to do its calculations, and dtype=torch.float32 makes each number a decimal rather
than an integer — required, because sales figures have cents.
4. Build the dataset of examples
features, targets = create_sliding_windows_with_target(series_tensor, window_size=window_size, shift=1)
dataset = TensorDataset(features, targets)
batch_size = 32
train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
The first line calls the function, create_sliding_windows_with_target, to give us
two lists, features and targets. The first list holds the 29-day
inputs, and the second holds the matching answers. TensorDataset keeps each input
together with its own answer. DataLoader then gives the examples to the model in
groups of 32 instead of all 1,431 at once. Setting shuffle=True changes the order
of the examples each time the model sees them, so it learns from the sales values rather than
memorising their date order.
5. Print what was built
print(f"Series length: {len(series)}")
print(f"Number of windows: {len(features)}")
print(f"Feature shape: {features.shape}")
print(f"Target shape: {targets.shape}")
These four lines are a habit worth copying: before training anything, print the shapes. If the numbers are wrong here, every result further down is wrong too, and finding that out now costs one run instead of an afternoon.
6. Peek at three examples
for i in range(3):
print(f"\nWindow {i+1}:")
print(f"Features (previous {window_size-1} days): {[f'{x:.2f}' for x in features[i].numpy()]}")
print(f"Target (next day): {targets[i].item():.2f}")
The loop runs three times, once for each of the first three examples. Inside it, the first
print labels the example, the second prints the 29 features rounded to two
decimals, and the third prints the one target. The :.2f inside the braces means
show two decimal places.
What you should see
Series length: 1460
Number of windows: 1431
Feature shape: torch.Size([1431, 29])
Target shape: torch.Size([1431, 1])
First few windows:
Window 1:
Features (previous 29 days): ['29.40', '33.41', '37.86', ... '27.24', '28.71']
Target (next day): 27.08
The series has 1,460 days, and each window covers
30 of them. The first window contains days [1, 2, 3, ..., 30], the second
contains days [2, 3, 4, ..., 31], and so on, with each window starting one day
later than the previous one.
You can calculate a window's starting day from its ending day:
starting day = ending day − 30 + 1. The second window ends on day 31, so
it starts on day 31 − 30 + 1 = 2. The last window ends on day 1,460, so
it starts on day 1,460 − 30 + 1 = 1,431. The windows therefore start on
days 1, 2, and so on up to 1,431, giving 1,431 windows in total.
Each window becomes one training example. Its first 29 values are the inputs, and its last
value is the target. That is why the feature shape is [1431, 29] and the target
shape is [1431, 1]: there are 1,431 examples, each with 29 inputs and 1 answer.
The whole program
The pieces above, put back together. This is the complete file, 27 lines in all:
import torch
from torch.utils.data import TensorDataset, DataLoader
import pandas as pd
def create_sliding_windows_with_target(data, window_size, shift=1):
windows = data.unfold(0, window_size, shift)
row_n = windows.shape[0]
col_n = windows.shape[1]
features = windows[0:row_n, 0:col_n-1] # All columns except the last
targets = windows[0:row_n, col_n-1:col_n] # Just the last column
return features, targets
df = pd.read_csv('time_series.csv')
series = df['series'].values
series_tensor = torch.tensor(series, dtype=torch.float32)
window_size = 30
features, targets = create_sliding_windows_with_target(series_tensor, window_size=window_size, shift=1)
dataset = TensorDataset(features, targets)
batch_size = 32
train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
print(f"Series length: {len(series)}")
print(f"Number of windows: {len(features)}")
print(f"Feature shape: {features.shape}") # Should be (num_windows, window_size-1)
print(f"Target shape: {targets.shape}") # Should be (num_windows, 1)
print("\nFirst few windows:")
for i in range(3):
print(f"\nWindow {i+1}:")
print(f"Features (previous {window_size-1} days): {[f'{x:.2f}' for x in features[i].numpy()]}")
print(f"Target (next day): {targets[i].item():.2f}")
Running it on your own computer
Download the zip file and unzip it
to a folder. The zip holds the programs in this series so far, the
time_series.csv data file, and pyproject.toml. This note uses
time_04.py. Open the folder in Visual Studio Code, then type these three lines
in the terminal:
uv python pin 3.12.10
uv sync
uv run time_04.py
The first line records which Python version this folder uses, and the second installs every
package that pyproject.toml lists. The third line prints the four counts and the
three example windows in the terminal.
Those three lines are needed only once. The next time you want to run the program again,
type just uv run time_04.py.
If you have not set up uv yet, start with How to install Visual Studio Code? and then the uv note for Windows or Mac.
What comes next
The dataset exists, but nothing has learned from it yet. Version 5 tidies the two slicing lines into a shorter form, and version 6 splits the examples into a training part and a validation part so that progress can be measured on days the model has not seen.