smartyfy.mrindigi.com

Python Master Course V2 — 147. Sequence Models and Recurrent State

Purpose and learning outcomes

An ordered sequence can contain information that disappears when you average its values. This lesson trains a tiny gated recurrent unit, or GRU, to compare the beginning and end of short numeric sequences. A simple aggregate-feature classifier provides a baseline. The exercise is classification of independent sequences, so it must not be confused with forecasting one continuous time series.

  • Represent ordered sequences with explicit length and batch axes
  • Build a simple recurrent model and understand state
  • Compare a sequence model with a non-neural baseline

Prerequisites: 143–145: PyTorch training; 139: time-aware evaluation.

Environment and run order

Use the isolated Python 3.11 or 3.12 environment from lesson 142. All tensors and models below run on the CPU. No pretrained weights or external datasets are downloaded. For first-time setup install the numerical packages, then use the official PyTorch installer selector for your operating system. The CPU wheel command below is for Linux or Windows; macOS uses python -m pip install torch. Run Python blocks sequentially in a single file.

Shell

python -m pip install numpy pandas scikit-learn matplotlib
# Linux/Windows CPU installation:
python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

Name every sequence axis

With batch_first=True, GRU inputs have shape (batch, length, features). Here each sequence contains eight scalar readings, so the feature dimension is one. The output contains one hidden vector per position, while the returned hidden state summarizes the final state of each recurrent layer. For one unidirectional layer, hidden has shape (1,batch,hidden_size). Choosing the wrong axis can silently turn time steps into unrelated examples.

Recurrent state is a learned memory

At each position a recurrent model combines the current input with its previous hidden state. A GRU uses learned gates to regulate how much existing state is retained and how much new information is incorporated. This can help represent dependencies across positions, but does not guarantee perfect memory for arbitrarily long sequences. Gradients flow through these repeated computations, making sequence length and update stability important.

Independent sequences start independently

Our rows are separately generated sequences. We let the GRU initialize hidden state to zeros for each batch and do not carry state between batches. Carrying state would connect unrelated examples and make predictions depend on batch order. A genuinely continuous streaming process can use carried state, but requires chronological handling and deliberate detachment boundaries when training across chunks.

A baseline should reveal what information matters

The aggregate baseline uses sequence mean, standard deviation, minimum, and maximum. These features ignore order. Our label compares the mean of the last two positions with the first two, so order is essential. A GRU can learn that relationship, but a hand-designed endpoint-feature model is an even stronger simple comparator. Be candid when a weak baseline proves only that order helps, not that recurrence is necessary.

Incremental worked example

1. Generate sequences and preserve the split boundary

Standardization uses only training sequence values. Random sequence-level splitting is appropriate because the generator creates independent sequences; it would be invalid for overlapping windows from one continuous timeline. A two-class target uses long integer labels.

Python

import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

torch.set_num_threads(1)
torch.manual_seed(47)
rng = np.random.default_rng(47)
raw = rng.normal(size=(600, 8, 1)).astype(np.float32)
y = (raw[:, -2:, 0].mean(1) > raw[:, :2, 0].mean(1)).astype(int)
ids = np.arange(len(y))
development, test = train_test_split(ids, test_size=0.2, stratify=y, random_state=47)
train, valid = train_test_split(development, test_size=0.25,
    stratify=y[development], random_state=48)
mean, std = raw[train].mean(), raw[train].std()
X = torch.tensor((raw - mean) / std)
target = torch.tensor(y, dtype=torch.long)
class SequenceClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.recurrent = nn.GRU(input_size=1, hidden_size=12, batch_first=True)
        self.head = nn.Linear(12, 2)
    def forward(self, inputs):
        outputs, hidden = self.recurrent(inputs)
        assert outputs.shape == (len(inputs), 8, 12)
        return self.head(hidden[-1])
model = SequenceClassifier()
loader = DataLoader(TensorDataset(X[train], target[train]), batch_size=48,
    shuffle=True, generator=torch.Generator().manual_seed(47), num_workers=0)

2. Compare recurrent and aggregate information

The training budget is fixed at 30 epochs. The baseline uses the same training labels and receives only aggregate features. We report validation during development, then evaluate both fixed procedures once on test for a declared comparison.

Python

optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(30):
    model.train()
    for inputs, labels in loader:
        optimizer.zero_grad(set_to_none=True)
        loss = loss_fn(model(inputs), labels)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0, error_if_nonfinite=True)
        optimizer.step()
    if epoch % 10 == 0:
        model.eval()
        with torch.no_grad():
            print(epoch, "validation accuracy",
                  (model(X[valid]).argmax(1) == target[valid]).float().mean().item())
values = raw[:, :, 0]
aggregates = np.column_stack([values.mean(1), values.std(1), values.min(1), values.max(1)])
baseline = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500))
baseline.fit(aggregates[train], y[train])
model.eval()
with torch.no_grad():
    recurrent_test = (model(X[test]).argmax(1) == target[test]).float().mean().item()
print("GRU test accuracy", recurrent_test)
print("aggregate baseline test accuracy", baseline.score(aggregates[test], y[test]))

Expected output / interpretation

GRU inputs are (batch,8,1), per-position states are (batch,8,12), and class logits are (batch,2).
Validation and test accuracies are runtime observations.
An aggregate baseline may perform near chance because its inputs erase the order defining the target.

Guided lab and acceptance criteria

  1. Reverse the order of every validation sequence and examine how the true label should change. The endpoint comparison reverses except for exact ties, which are negligible for this continuous generator. Test predictions without modifying the trained model.
  2. Add a baseline using the first-two mean and last-two mean. Fit a linear classifier on training rows and evaluate using the same protocol. Explain why its success would show that the engineered representation is sufficient without recurrence.
  3. Create a shape audit for batch sizes one and five. Confirm that the model returns one pair of logits per sequence and that hidden state is not reused across independent batches.
  4. Deliver the sequence definition, split rationale, recurrent model, both simple baselines if extended, and a discussion of information loss. Passing work distinguishes independent-sequence classification from temporal forecasting and does not let overlapping windows cross partitions.

Common mistakes and repairs

  • Using batch_first=True for inputs but interpreting hidden as batch-first: the returned hidden-state layout remains layers-times-directions, batch, hidden size.
  • Carrying hidden state across unrelated shuffled sequences: reset it so examples do not influence one another through batch order.
  • Claiming recurrence is necessary after beating only order-free aggregates: compare a simple model with meaningful order-aware features too.

Questions that test understanding

What does hidden[-1] select?

For this single-layer, unidirectional GRU, it selects the final hidden state of the only recurrent layer, leaving shape (batch,12). With multiple layers or bidirectionality, interpretation changes and may require concatenating directions. Do not reuse this indexing pattern blindly for a different architecture.

Why not use only the sequence mean?

The target depends on whether the end exceeds the beginning. Reversing a sequence preserves its overall mean but changes that relationship. An order-free statistic cannot distinguish both cases reliably, so poor baseline performance reveals lost information rather than an inherent weakness of linear models.

When should hidden state be carried between batches?

Only when batches intentionally represent consecutive chunks of the same underlying stream and the deployment contract uses that continuity. Then manage sequence boundaries and detach state when truncating gradient history. Independent examples should start independently, even if they have the same length.

Why is random splitting acceptable here but not in forecasting?

The generator creates each complete sequence independently. The prediction concerns a property of a new independent sequence, not the future of a shared timeline. Overlapping windows or repeated subjects would break that assumption and require grouped or chronological splitting.

How should variable-length sequences be handled?

You need explicit lengths and a strategy such as padding with packed sequences or carefully selecting the last valid state. Reading the final padded position as though it were real data can distort predictions. This lesson fixes length eight to isolate recurrent-state mechanics before adding that complexity.

Does gradient clipping prove stable learning?

No. It bounds an update-related quantity when gradients become large, but cannot fix wrong labels, poor initialization, or an invalid objective. Log pre-clipping norms and investigate repeated extreme values. It is a safeguard within a diagnostic process, not a certification.

Exercises with worked solutions

Exercise 1: Build the order-aware baseline

Reveal the worked solution and reasoning

The target-generating relationship is a linear comparison between these two means, so a simple linear classifier should be highly competitive. Fit on training only. Treat this as a development extension and obtain a new final evaluation if you changed the comparison after studying prior test results.

Python

endpoint_features = np.column_stack([values[:, :2].mean(1), values[:, -2:].mean(1)])
endpoint_model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500))
endpoint_model.fit(endpoint_features[train], y[train])
print("endpoint validation accuracy", endpoint_model.score(endpoint_features[valid], y[valid]))

Exercise 2: Check independent batch behavior

Reveal the worked solution and reasoning

In eval mode without carried state, a sequence’s prediction should be the same whether processed alone or inside a batch, up to numerical tolerance. This tests the intended interface rather than task accuracy.

Python

model.eval()
with torch.no_grad():
    alone = model(X[valid[:1]])
    together = model(X[valid[:5]])[:1]
assert torch.allclose(alone, together, atol=1e-6)
print("independent sequence prediction checked")

Recap and next step

A sequence model learns from order through recurrent state. Correct axes, deliberate state boundaries, and meaningful simple baselines keep the result interpretable. Attention next provides another way to combine information across positions, with masks making the allowed information flow explicit and testable.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.