Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

From Text and Time Series to Tensors

Turn sentences into integer ids with a vocabulary built on training text only, pad a batch and build its mask, see why the last padded slot is not the end of a short sentence and how packing fixes it, then cut a time series into windows with a time-based split and measure what a scaler fitted on the whole series leaks.

Contentsand lesson path

What you will learn

  • Prepare sequence data for training: tokenize text into ids with padding and masks, or window a time series with a leakage-free temporal split.

Prerequisites: Deep Learning Fundamentals

01. Why it matters

A sequence is data where order carries meaning: the words of a review, the daily sales of a shop, the readings of a sensor. A network takes tensors with a fixed shape per batch, such as (batch, time) for word ids or (batch, time, features) for measurements. Getting from raw data to those tensors is where many sequence projects quietly go wrong.

Two kinds of mistake are common. The first is mechanical: sentences differ in length, so batches are padded with filler, and a model that treats filler as data learns from noise. The second is about time: if any number used to prepare the data, such as a vocabulary or a scaler, comes from the test period, the test score looks better than the model will be in use. This lesson builds both pipelines on tiny examples.

You need Python 3.12, PyTorch 2 (CPU build) and NumPy 2. Keep the scripts in one folder, as they import each other. Random values are seeded; the last digit can differ on other CPUs or library versions.

02. Tokens, ids and a vocabulary

Tokenising splits text into units called tokens. Here a token is a lower-case word, found with a regular expression that also drops punctuation. Large language models use subword tokenisers, which split rare words into pieces; the ideas are the same. A vocabulary maps each token to an integer id, and the model later looks up one learned vector per id.

Two ids are reserved. <pad> (id 0) is the filler used to make sequences the same length. <unk> (id 1) stands for any token that is not in the vocabulary. The vocabulary is built from the training texts only, and only from words seen at least min_freq times. Words below that count are mapped to <unk> during training too, so the <unk> vector gets trained on real examples of rare words instead of appearing for the first time at test time.

Python · vocab.py
import re
from collections import Counter

train_texts = [
    "The plot was good, the acting was good.",
    "The acting was dull and the plot was dull.",
    "Good film. Not a dull minute!",
    "A dull plot, but the music was good.",
]
test_texts = ["The music was superb, not dull at all."]
PAD, UNK = "<pad>", "<unk>"


def tokenize(text):
    return re.findall(r"[a-z]+", text.lower())  # lower-case words, no punctuation


def build_vocab(texts, min_freq=2):
    counts = Counter(tok for t in texts for tok in tokenize(t))
    words = sorted(w for w, c in counts.items() if c >= min_freq)
    return {PAD: 0, UNK: 1} | {w: i for i, w in enumerate(words, start=2)}


def encode(text, vocab):
    return [vocab.get(tok, vocab[UNK]) for tok in tokenize(text)]


if __name__ == "__main__":
    vocab = build_vocab(train_texts)              # training texts only
    print("vocabulary:", " ".join(f"{w}={i}" for w, i in vocab.items()))
    print("tokens:", tokenize(test_texts[0]))
    ids = encode(test_texts[0], vocab)
    print("ids:   ", ids)
    print(f"unknown share: {ids.count(1) / len(ids):.2f}")
Terminal
python vocab.py
Expected output
vocabulary: <pad>=0 <unk>=1 a=2 acting=3 dull=4 good=5 plot=6 the=7 was=8
tokens: ['the', 'music', 'was', 'superb', 'not', 'dull', 'at', 'all']
ids:    [7, 1, 8, 1, 1, 4, 1, 1]
unknown share: 0.62

The four training texts give a vocabulary of nine entries. The test sentence has eight tokens, and five of them become id 1: music, superb, at and all never reached two occurrences in training, and neither did not. Losing not changes the meaning of the review, which is why the share of unknown tokens on new data is worth printing in every text pipeline.

Why not build it on all the data? The test set stands for text the model has never seen. If test-only words get ids, the unknown rate you measure is too low and the pipeline uses information you will not have in use.

03. Padding, lengths and masks

A batch tensor must be rectangular. pad_sequence stacks sequences of different lengths and fills the short ones with the pad id. With batch_first=True the result has shape (batch, time); without it, (time, batch). Padding at the end is called right padding. Next to the batch you keep two things: the true lengths, and a mask, a boolean tensor that is True at real tokens and False at pads.

An embedding layer (nn.Embedding) is a lookup table with one trainable vector per id. With padding_idx=0, the row for <pad> starts at zero and is never updated. That does not make pads harmless, as the script shows by averaging the token vectors of each review, a simple way to get one vector per sentence.

Python · batch.py
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence

from vocab import build_vocab, encode, train_texts

vocab = build_vocab(train_texts)
seqs = [torch.tensor(encode(t, vocab)) for t in train_texts[:3]]
lengths = torch.tensor([len(s) for s in seqs])
batch = pad_sequence(seqs, batch_first=True, padding_value=vocab["<pad>"])
mask = batch != vocab["<pad>"]                  # True where there is a real token
print("lengths:", lengths.tolist())
print("batch:\n", batch)
print("mask:\n", mask.int())

torch.manual_seed(0)
emb = nn.Embedding(len(vocab), 4, padding_idx=0)  # row 0 is all zeros, never trained
vectors = emb(batch)                              # (batch, time, 4)
naive = vectors.mean(dim=1)                       # pads are counted as real steps
m = mask.unsqueeze(-1)                            # (batch, time, 1) broadcasts over 4
masked = (vectors * m).sum(dim=1) / m.sum(dim=1)  # average over real tokens only
print("vectors shape:", tuple(vectors.shape))
print("review 3, naive mean: ", naive[2].detach().numpy().round(3))
print("review 3, masked mean:", masked[2].detach().numpy().round(3))
Terminal
python batch.py
Expected output
lengths: [8, 9, 6]
batch:
 tensor([[7, 6, 8, 5, 7, 3, 8, 5, 0],
        [7, 3, 8, 4, 1, 7, 6, 8, 4],
        [5, 1, 1, 2, 4, 1, 0, 0, 0]])
mask:
 tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 0, 0, 0]], dtype=torch.int32)
vectors shape: (3, 9, 4)
review 3, naive mean:  [ 0.217 -0.086  0.068 -0.534]
review 3, masked mean: [ 0.326 -0.128  0.102 -0.8  ]

The third review has six real tokens and three pads. The plain mean(dim=1) divides its sum by 9, so every number is two thirds of the masked mean: 0.217 against 0.326 in the first dimension. Short reviews are shrunk towards zero for being short. The masked mean multiplies by the mask, sums, and divides by the number of real tokens.

Masks come in two conventions, and mixing them up is a classic bug. Hugging Face tokenisers return an attention_mask with 1 for real tokens. PyTorch's nn.MultiheadAttention takes a key_padding_mask where True means ignore this position. Check the documentation of every layer you pass a mask to.

04. Recurrent layers and the end of a short sequence

A recurrent layer such as a GRU reads a sequence one step at a time and carries a hidden state forward; the next lesson opens it up. For now, one fact matters: it runs over every position you give it, pads included. Its output tensor holds the hidden state at each step, so output[:, -1] is the state after the last slot of the batch. For a review that is shorter than the longest one, that slot is a pad.

There are two correct ways to get each review's state at its true last token. You can gather the output at position length − 1 for each row. Or you can pack the batch with pack_padded_sequence, which tells the layer the true lengths so that it stops each sequence there; the returned h_n then holds each sequence's real final state. enforce_sorted=False lets you pass the batch in any order.

Python · pack.py
import torch
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_sequence

from vocab import build_vocab, encode, train_texts

vocab = build_vocab(train_texts)
seqs = [torch.tensor(encode(t, vocab)) for t in train_texts[:3]]
lengths = torch.tensor([len(s) for s in seqs])     # [8, 9, 6]
batch = pad_sequence(seqs, batch_first=True)       # pads with 0 = <pad>

torch.manual_seed(0)
emb = nn.Embedding(len(vocab), 4, padding_idx=0)
gru = nn.GRU(input_size=4, hidden_size=3, batch_first=True)
x = emb(batch)

with torch.no_grad():
    output, h_n = gru(x)                           # runs over the pads too
    last_slot = output[:, -1]                      # position 8 for every review
    true_last = output[torch.arange(3), lengths - 1]  # gather each true last step
    packed = pack_padded_sequence(x, lengths, batch_first=True,
                                  enforce_sorted=False)
    _, h_packed = gru(packed)                      # stops at each true length

for name, t in [("output[:, -1]", last_slot), ("gathered", true_last),
                ("packed h_n[-1]", h_packed[-1])]:
    print(f"{name:15s} review 3: {t[2].numpy().round(4)}")
print("gathered == packed:", torch.allclose(true_last, h_packed[-1], atol=1e-6))
Terminal
python pack.py
Expected output
output[:, -1]   review 3: [ 0.043  -0.1896  0.0822]
gathered        review 3: [ 0.4292 -0.191   0.3451]
packed h_n[-1]  review 3: [ 0.4292 -0.191   0.3451]
gathered == packed: True

For review 3, the value at the last slot (0.043 in the first dimension) is far from its state at token 6 (0.429), because the GRU kept updating through three pad steps. Gathering and packing agree exactly. In a trained classifier, short reviews would be classified from states that drifted through pads. Gathering works for a one-direction layer. A bidirectional layer also reads each sequence backwards, starting from the last slot, so there packing is the safe choice.

05. Time series: windows, a time-based split and the scaler

A time series is one long sequence, so you cut it into training examples with a sliding window: each example takes window consecutive values as input and the next horizon values as targets, then the window moves on by one step. The script builds a seeded daily series of 400 days with a slow upward trend, a weekly cycle and noise, and uses 28 days of history to predict the next 7.

Neighbouring windows share 27 of their 28 inputs, so a random split of windows puts almost identical examples, and the very values being predicted, on both sides. The honest split is by time: pick a cut-off day, train on windows whose targets all lie before it, and test on windows whose forecasts start after it. A gap between the two can go further and keep the test windows from reusing any day the training windows touched.

Python · windows.py
import numpy as np


def make_series(n_days=400, seed=0):
    rng = np.random.default_rng(seed)
    t = np.arange(n_days)
    weekly = 10 * np.sin(2 * np.pi * t / 7)
    return 100 + 0.1 * t + weekly + rng.normal(0, 3, n_days)  # trend + week + noise


def make_windows(y, window=28, horizon=7):
    starts = np.arange(len(y) - window - horizon + 1)
    X = np.stack([y[s:s + window] for s in starts])
    Y = np.stack([y[s + window:s + window + horizon] for s in starts])
    return X, Y, starts


def time_split(starts, cutoff, window=28, horizon=7, gap=0):
    first_target = starts + window
    train = first_target + horizon <= cutoff       # every target before the cut-off
    test = first_target >= cutoff + gap            # forecasts start after the gap
    return train, test


if __name__ == "__main__":
    y = make_series()
    X, Y, starts = make_windows(y)
    print("series:", y.shape, " windows X:", X.shape, " targets Y:", Y.shape)
    for gap in (0, 28):
        train, test = time_split(starts, cutoff=300, gap=gap)
        tr_days = {int(d) for s in starts[train] for d in range(s, s + 35)}
        te_days = {int(d) for s in starts[test] for d in range(s, s + 35)}
        print(f"gap {gap:2d}: train {train.sum()} windows, test {test.sum()},"
              f" days used by both: {len(tr_days & te_days)}")
    rng = np.random.default_rng(0)
    test = rng.random(len(starts)) < 0.2           # a random split, for contrast
    tr_days = {int(d) for s in starts[~test] for d in range(s, s + 35)}
    seen = np.mean([all(d in tr_days for d in range(s + 28, s + 35))
                    for s in starts[test]])
    print(f"random split: {seen:.0%} of test windows have all 7 targets"
          " inside some training window")
Terminal
python windows.py
Expected output
series: (400,)  windows X: (366, 28)  targets Y: (366, 7)
gap  0: train 266 windows, test 94, days used by both: 28
gap 28: train 266 windows, test 66, days used by both: 0
random split: 97% of test windows have all 7 targets inside some training window

The 400 days give 366 windows. With the cut-off at day 300, 266 windows have all their targets before it; the six that straddle the cut-off belong to neither set. Without a gap, the first test windows use days 272 to 299 as inputs. Those days were training targets, which is legal (at forecast time you know the past), but the sets are not independent. A gap of one window length removes that overlap at the cost of 28 test windows. The random split shows the problem it avoids: 97% of its test windows have every target day inside some training window.

The same rule applies to every statistic you compute from the data, including the scaler that standardises values to mean 0 and standard deviation 1 before they reach a network.

Python · scaler.py
import numpy as np

from windows import make_series

y = make_series()
train, test = y[:300], y[300:]                     # split by time first
for name, ref in [("whole series", y), ("train only  ", train)]:
    mean, std = ref.mean(), ref.std()
    z_test = (test - mean) / std
    mae = np.abs(test - mean).mean()               # "forecast = scaler mean"
    print(f"fit on {name}: mean {mean:6.2f}  std {std:5.2f}  "
          f"test z-mean {z_test.mean():5.2f}  MAE of the mean {mae:5.2f}")
z_train = (train - train.mean()) / train.std()
print(f"train z-range with train stats: {z_train.min():.2f} to {z_train.max():.2f}")
Terminal
python scaler.py
Expected output
fit on whole series: mean 119.84  std 13.66  test z-mean  1.09  MAE of the mean 14.95
fit on train only  : mean 114.87  std 11.45  test z-mean  1.74  MAE of the mean 19.89
train z-range with train stats: -2.65 to 2.38

Fitted on the whole series, the mean is 119.84 instead of 114.87, because it includes the higher test period. The simplest forecast, "predict the scaler's mean", then scores an error of 14.95 on the test period instead of 19.89. Nothing got smarter; the future leaked in through one number, and a network trained on leaky scaled data benefits in the same hidden way. With train-only statistics the test period sits at a mean of 1.74 standard deviations, near the top of the training range (−2.65 to 2.38). That is the real situation the model will face, and the test score should show it.

06. Check your understanding

Practice check · 3 questions

Ids, masks and windows

Use the scripts and outputs of this lesson.

Q1. In `vocab.py`, `not` is encoded as `<unk>` in the test sentence, although the third training text contains it. Why?
Q2. In `batch.py`, every number of the naive mean of review 3 is exactly two thirds of its masked mean. Why?
Q3. Each window in `windows.py` predicts 7 days. You change `time_split` to put a window in training when its last *input* day is before the cut-off. What goes wrong?
Practice only: not graded, not saved, not evidence.

07. Apply it

The practice project asks you to train an LSTM or GRU on text classification or forecasting and compare it with a simple baseline. Whichever data you choose, write its preparation step first and test it on its own.

  1. For text: build the vocabulary on the training split, print its size and the unknown-token share on the validation split, and return padded ids, lengths and a mask from one collate function.
  2. For a series: write make_windows and a time-based split, with the cut-off dates printed, and fit the scaler on the training period only.
  3. Add one assertion that would fail if the pipeline leaked, for example that no test target date is before the last training target date.

08. Review prompt

Without looking back, explain what the <pad> and <unk> ids are for and why the vocabulary comes from training text only; describe the mask of a right-padded batch and how a masked mean differs from a plain one; give two ways to get the state of a recurrent layer at the true end of each sequence; say how a sliding window turns a series into examples; and explain how a split by time, and a scaler fitted on the training period, keep the future out of the test score.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check