LSTM time sequence generation using PyTorch
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
LSTM models are a practical choice when you want a network to learn patterns from ordered values such as sensor readings, traffic counts, or sampled waveforms. In PyTorch, sequence generation usually means training on short windows of past values and then asking the model to predict the next value repeatedly.
Preparing Sequential Training Data
An LSTM does not read a whole time series as one flat vector. It expects steps over time, so the first job is to convert raw data into fixed-length windows. Each training example contains a short input sequence and the target value that follows it.
The example below builds a simple sine wave dataset. The helper returns tensors shaped for batch_first=True, so each input has the form batch, time, features.
Two details matter here. First, the model predicts one step ahead, not an entire future sequence at once. Second, scaling is often useful for real data. A sine wave is already small and smooth, but measured business or industrial data often needs normalization before training.
Building the LSTM Model
In PyTorch, nn.LSTM handles the recurrent state updates for you. A small forecasting model usually consists of an LSTM layer followed by a linear layer that maps the last hidden state to the next numeric value.
This model is intentionally small. For many sequence problems, a larger hidden state, more layers, or dropout may help, but simple models are easier to debug. If a tiny model cannot learn a clean synthetic series, the issue is usually in the data pipeline or tensor shapes rather than model capacity.
Training and Generating New Values
Training is standard supervised learning. Feed a window in, compare the predicted next value against the true next value, and minimize mean squared error. After training, generation becomes autoregressive: take the latest window, predict one value, append it, and repeat.
The generation loop is where many beginners get lost. The model only predicts one next point at a time, so you must feed its output back into the input window. That feedback is what turns a one-step forecaster into a sequence generator.
For real projects, split the data into train and validation sets. If validation error rises while training error falls, the model is starting to memorize the training windows instead of learning a pattern that generalizes.
Common Pitfalls
One frequent mistake is passing tensors with the wrong shape. With batch_first=True, the LSTM expects batch, time, features. If you pass time, batch, features, training may fail or silently learn the wrong mapping.
Another common issue is forgetting that long generated sequences accumulate error. Even if one-step predictions look good, repeated feedback can drift. Reducing that drift may require better scaling, more representative training windows, or training on noisier data.
It is also easy to confuse sequence generation with sequence classification. A classifier uses the final hidden state to predict a label. A generator uses that state to predict the next numeric step and then rolls forward.
Summary
- Use sliding windows to convert a raw time series into supervised training samples.
- In PyTorch,
nn.LSTMplus a linear output layer is enough for basic one-step forecasting. - Sequence generation is autoregressive: predict one value, append it to the window, and repeat.
- Check tensor shapes early, because many LSTM bugs come from incorrect
batch, time, featuresordering. - Evaluate both one-step accuracy and multi-step drift before trusting generated sequences.

