RNN/LSTM
How recurrent neural networks and LSTMs process sequences step by step with a memory state, for forecasting, speech and sensor data, and why gates were added to keep long-range information.
What it is
A recurrent neural network (RNN) is a neural network for sequential data, in which the output at each step depends not only on the current input but also on a hidden state carrying information from earlier steps. This gives the network a kind of memory and lets it handle sequences of variable length: text, speech, sensor streams, financial series, hydrological and weather records, and biological sequences. Plain RNNs struggle to remember over long spans, and the Long Short-Term Memory (LSTM) network, proposed by Hochreiter and Schmidhuber in 1997, solved much of this using gates that control what to store, forget and output. The simpler Gated Recurrent Unit (GRU) (Cho et al., 2014) has similar abilities. LSTMs powered speech recognition, machine translation and forecasting for many years, before transformers took over many language tasks (see transformers).
It answers questions such as: What is the next value of this time series? What class does this sequence belong to (activity, fault, sentiment)? How can an input sequence be translated into an output sequence? Is this sensor trace anomalous? LSTMs remain popular for modest-size time-series problems, streaming and low-latency settings, and hydrology and process monitoring.
Fundamentals
The recurrent cell and unrolling
A basic RNN updates its hidden state with ht = tanh(Wh ht−1 + Wx xt + b) and produces output yt = Wy ht + c, with the same weights at every time step. Unrolled over time it looks like a very deep network with shared weights. Training uses backpropagation through time (BPTT): gradients flow backward through all steps. Each step multiplies the gradient by the recurrent weight matrix and the tanh derivative, so over many steps the gradient shrinks exponentially (the vanishing gradient problem) or grows without bound (exploding gradients). Vanishing gradients prevent learning dependencies more than about 10–20 steps apart, and exploding gradients are controlled by gradient clipping (rescaling when the norm exceeds a threshold). Training often uses truncated BPTT, with windows of fixed length.
LSTM gates and the cell state
The LSTM adds a cell state ct, a conveyor belt that carries information with only small, controlled changes. Three gates, each a sigmoid layer σ with output between 0 and 1, regulate it. The forget gate, ft = σ(Wf[ht−1, xt] + bf), decides what to erase; the input gate, it = σ(Wi[ht−1, xt] + bi), with candidate values c̃t = tanh(Wc[ht−1, xt] + bc), decides what to write. The state update is ct = ft ⊙ ct−1 + it ⊙ c̃t, where ⊙ is element-wise multiplication. The output gate, ot = σ(Wo[ht−1, xt] + bo), gives ht = ot ⊙ tanh(ct). Since the cell state is updated additively, gradients can flow across many steps when the forget gate stays near 1, which is why LSTMs learn long dependencies. A layer with nin inputs and nh hidden units has 4[(nin + nh)nh + nh] parameters. The GRU merges the cell and hidden states and uses two gates (update and reset), with fewer parameters and similar accuracy in many tasks.
Architectures and task types
RNNs support several input–output patterns: many-to-one (classify a whole sequence from the final state), one-to-many (image captioning), many-to-many aligned (label each time step, such as tagging) and sequence-to-sequence (encoder–decoder: an encoder compresses the input into a vector, and a decoder generates the output sequence, as in translation, with attention added to avoid the single-vector bottleneck). Bidirectional RNNs read sequences forward and backward, which helps when the whole sequence is available, but not for real-time forecasting. Layers can be stacked (2–4 layers) with dropout between them. During training of generative models, teacher forcing feeds the true previous output, which can cause exposure bias at inference. Variants: convolutional LSTMs for spatiotemporal data such as radar nowcasting, and echo state networks.
Practical use for time series
Data are cut into overlapping windows (for example, the past 48 hours to predict the next 6). Inputs should be scaled using training statistics, missing values handled, and the data split chronologically (train on the past, test on the future) or by blocks, never randomly, to prevent leakage; use rolling-origin evaluation (see ARIMA time series analysis for the classical baseline). Forecasts should be compared with simple baselines, such as persistence (tomorrow equals today), seasonal naive and ARIMA, which are hard to beat on many series. Hyperparameters include hidden size (32–256 units), number of layers, window length, learning rate, dropout and batch size, and early stopping on validation loss prevents overfitting. Multi-step forecasts can be direct (output all steps) or recursive (feed predictions back, accumulating error). Probabilistic forecasts use quantile or distribution outputs (DeepAR style). Global LSTMs trained on many related series, as in the hydrology work that trained one LSTM across hundreds of catchments (see hydrological modeling), often outperform per-series models.
Typical applications and limits
Applications: demand and load forecasting, streamflow and weather, predictive maintenance on sensor streams, speech and handwriting recognition, physiological signals (ECG, EEG) and protein or DNA sequences. Limits: sequential computation prevents parallelism across time, so training is slow on long sequences; very long-range dependencies remain hard; performance depends heavily on data volume and scaling; and on many language and long-sequence tasks transformers outperform them. Frameworks: PyTorch (nn.LSTM, nn.GRU) and TensorFlow/Keras.
Basic operation
- Prepare the series. Clean, scale and create input windows and targets.
- Split chronologically. Keep validation and test periods after the training period.
- Set a baseline. Compute persistence or ARIMA forecasts for comparison.
- Define the network. Choose LSTM or GRU layers, hidden size and dropout.
- Train. Use Adam, gradient clipping and early stopping on validation loss.
- Tune. Adjust window length, hidden units and learning rate.
- Evaluate. Test on future data with metrics such as RMSE, MAE and skill versus baseline.
- Collect the output. You obtain forecasts or sequence labels; windowing and multi-step strategies are covered in the video.
Good practice
- Never shuffle across time. Random splits leak future information.
- Beat the baseline. Compare with simple forecasts.
- Clip gradients. This prevents exploding updates.
- Scale using training data only. Avoid leakage through normalization.
- Report uncertainty. Give intervals or ensembles, not only point forecasts.
- Be careful in operational use. Forecasts for floods, grids or patients should be monitored, retrained as conditions change, and combined with expert oversight.
Key terms
- Hidden state — the vector carrying information from earlier steps of a sequence.
- Backpropagation through time — gradient computation by unrolling the network across time steps.
- Vanishing gradient — gradients shrinking toward zero over many steps, blocking learning.
- LSTM gate — a learned 0-to-1 switch controlling what is forgotten, stored or output.
- Cell state — the LSTM’s long-term memory pathway.
- GRU — a simpler gated recurrent unit with two gates.
- Sequence-to-sequence — a model mapping an input sequence to an output sequence.
Video coming soon
About five minutes on RNN/LSTM: how it works in detail, how the data is acquired, and how it is analyzed.
More in 4.3 AI and Machine Learning
- Regularized linear models
- Decision trees and random forests
- Gradient boosting (XGBoost)
- Support vector machines
- k-NN
- k-means
- Gaussian processes
- Neural networks
- CNNs
- RNN/LSTM
- Transformers
- Autoencoders
- GANs
- Diffusion models
- Graph neural networks
- Reinforcement learning
- Transfer learning
- Federated learning
- Explainable AI (SHAP, LIME)
- Physics-informed neural networks
- Bayesian optimization
- Active learning
- Symbolic regression
- Genetic algorithms and particle swarm optimization
- Dimensionality reduction (t-SNE, UMAP)
- NLP and large language models
- Retrieval-augmented generation
- Computer vision (detection, segmentation)
- Anomaly detection
- Machine-learned interatomic potentials
- AutoML
