Recurrent Networks
Sequential data has order and dependencies between positions. phrase, the meaning of a word depends on the previous ones; in a series a recent measure helps to interpret the following. common feedforward receives a fixed size vector and does not maintain, by itself Just a state between steps.
A recurrent neural network (RNN) introduces a hidden state which is updated along the sequence. The same transformation is reused in every moment, allowing to process sequences of different lengths.
7.1 Elman recurrent network
Be the input at and the hidden state. A simple RNN of Elman calculates
Parameters have formats
The activation is usually tanh in a simple RNN. depends on the task: identity for regression, sigmoid for binary output or softmax for exclusive classes.
The initial state can be zero, a learned parameter or a vector provided by another model. This choice is part of the specification of architecture.
7.1.1 Memory as a state
The (7.1) equation combines the current observation with a summary of the past. The state does not literally store all previous items; it is a fixed dimension representation, recursively updated:
Two sequences with the same last element can produce states different because they have traveled different history. small state may lose relevant details of long sequences.
7.1.2 Unrolling through time
Although the recurrent diagram contains a cycle, for a finite sequence can unfold it into a string. Each visual copy represents the the same cell in a different instant; the parameters are shared.

Figure 7.1. A recurrent NNR and its unfolding: the same parameters are reused in all steps.
Sharing has two consequences:
- the number of parameters does not grow with the length of the sequence;
- gradients of every moment contribute to the same matrices.
A RNN with steps does not have a hundred matrices; it has a matrix used a hundred times.
7.1.3 Input and output formats
Recurrent networks can be organised according to the task:
- sequence for sequence: one label per step, such as labeling words;
- sequence for vector: one output after reading the entire sequence as text classification;
- vector for sequence: an initial condition generates several steps;
- sequence for sequence with different lengths: one encoder produces a representation used by a decoder.
In batch, an entry usually has a format : examples, time and features. different lengths can be filled up to a common size, but a mask must prevent artificial positions from contributing to the loss or for metrics.
Filling does not create information. Also, process a sequence far beyond its actual length can alter states if the implementation do not respect the mask.
7.1.4 Forward propagation
import number as np
def rnn_elman(X, W_xh, W_hh, b_h, Why, b_y, h0=None):
"X has format (lot, time, features)."
B, T, X.shape
d_h = W_hh.shape[0]
h = np.zeros((B, d_h)) if h0 is None else h0.copy()
States, exits = [], []
for t in range(T):
h = np.tanh(X[:, t, :] @W_xh.T + h @W_hh.T + b_h)
o = h @W_hy.T + b_y
states.append(h.copy())
exits.append(s)
H = np.stack(states, Axis=1)
O = np.stack(outcomes, Axis=1)
return O, H
The time loop is sequential: depends on . Inside each step, all examples and all units are vectorized.
7.1.5 Backpropagation through time
back-propagation through time (BPTT) applies back-propagation to graph unfolded. If the total loss is
the state can influence the loss in the step itself and all the future losses. Its derivative accumulates these paths. In a way simplified,
For Elman’s recurrence,
Repeated products of these Jacobians explain two problems:
- gradients that disappear: standards smaller than one are multiplied repeatedly, weakening long dependencies;
- gradients that explode: standards larger than one can grow quickly and destabilize training.
Gradient standard clipping helps in the second case. LSTM and GRU cells create state paths controlled by doors and were designed for facilitate the learning of longer dependencies; they reduce, but They don’t eliminate all the difficulties.
7.1.6 Truncated BPTT
Save the graph of a very long sequence consumes memory and increases the derivatives path. In truncated BPTT, we process blocks Steps, we transport the state value to the next block, but We interrupt the derivation graph at the border.
This reduces cost and memory, but prevents the gradient from assigning credit directly to events prior to the window. The length is, therefore, a computational and statistical hyperparameter.
7.1.7 Relationship with feedforward networks
An unfolded NNR looks like a deep network, but has two essential differences:
- the effective depth depends on the length of the sequence;
- the parameters of the temporal copies are shared.
Feedforward networks can also receive a fixed observation window, but the window needs to be chosen beforehand and each position usually have different parameters. NNRs offer a recurring rule applicable to varied lengths.
Today, attention mechanisms and Transformers are important alternatives for many sequential problems because they allow shorter paths between positions and greater parallelism. continuous flows, compact models and scenarios with step-to-step processing Pass.
Temporal order is not batch order
To shuffle the order of independent examples between times is usually suitable. Shuffle the steps within each sequence destroys the temporal structure that recurrence must learn.
Exercises
- Check the formats in (7.1) and (7.2).
- How many parameters does a RNN have with , e ?
- Explain why the number of parameters does not depend on .
- Differentiate fill, mask and truncated BPTT.
- Show how repeated products from a scale help understand the disappearance of the gradient.
- When a step-by-step output is required and when only can Is that enough?
7.2 Self-organizing maps
A self-organizing map (* Self-Organizing Map*, SOM) is a method of Unsupervised learning that represents high-dimensional data by a grid, usually two-dimensional, of prototypes. data space tends to activate nearby units in the grid.
The SOM does not discover true labels or approximate a “divine function”. It produces an exploratory representation whose interpretation depends on the data, the scale of features and hyperparameters.
7.2.1 Three distinct objects
Consider data and drives. Each unit has:
- a fixed position on the grid, normally ;
- a training prototype in the data space.
distances compare an example to prototypes. distances compare positions in the grid. Mix these two spaces make the algorithm incorrect.

Figure 7.2. Each unit occupies a fixed position in the grid and has a prototype in the data space; the winner and her neighbors move towards the example.
7.2.2 Best matching unit
For an example , the winning drive, or BMU (best matching unit), is
Using the distance or your square produces the same winner and avoids the root square in the calculation.
7.2.3 Neighborhood function
The winner’s influence on the unit may be Gaussian:
This function is not a metric: it is maximum in nearby units and decreases with distance. The parameter is the radius of neighborhood. The square in is required in the form usual gaussian.
7.2.4 Update Rule
All prototypes are updated by
where is the learning rate. BMU moves more; its neighbors also approach the example, preserving local order in the grid.
At the beginning, higher radius and rate promote global organization. Both decrease to allow local adjustments. possible for is
The final values should be positive. Reduce the radius to zero too soon transforms training into independent competition and harms the Topological organization.
7.2.5 Algorithm
- Standardize features when your scales are not comparable.
- Create positions from a grid and initialize prototypes .
- For each iteration:
- Associate each example to your BMU position to view the map.
Random boot is simple; sample examples or initialize in direction of the first main components can accelerate the organization. Different seeds can produce different orientations from grid without one of them necessarily being wrong.
7.2.6 Example of an update
Consider two prototypes
and the example. Quadratic distances are
Therefore, BMU is unit 1. With , influence and, to simplify, zero influence on the other unit,
The prototype moved to the midpoint between its previous value and the example. As only the winner has been updated, this is the limit case of competitive learning, similar to k-means online. Distinguished SOM behavior appears when neighboring units also They’re positively influenced.
For example, if , then
Unit 2 also moves, but by a smaller fraction.
7.2.7 NumPy Implementation
import number as np
def passo_som(x, prototypes, positions, rate, sigma):
x = np.asarray(x, dtype=float)
W = np.asarray(prototypes, dtype=float)
R = np.asarray(positions, dtype=float)
dist_data = np.sum(((W - x) ** 2, Axis=1)
bmu = np.argmin(dist_data)
dist_grade = np.sum(((R - R[bmu]) ** 2, Axis=1)
influence = np.exp(-dist_grade / (2 * sigma**2))
W + = rate * influences[:, None] * (x - W)
return bmu, W
index transforms format influence in a column , allowing to multiply it by differences by broadcasting.
7.2.8 Evaluation and visualization
Since there is no mandatory label, we use internal criteria and inspection:
- quantization error: average distance from each example to prototype of its BMU;
- topographic error: frequency with which the first and second BMUs They’re not neighbors on the grid;
- matrix U: viewing the distances between neighbouring prototypes;
- distribution of examples per unit, to detect empty units or excessive concentration.
Low quantization error does not guarantee good topological preservation. Increase the number of units tends to improve quantization, but can also create a sparse map and harder to interpret.
7.2.9 Limitations and responsible use
SOMs are sensitive to the scale of features, startup, order of examples, grid size and schedules. The proximity in the grid is a approximation of data structure, does not prove that two groups are natural categories.
When external labels exist, they can be designed on the map after the training for interpretation, but should not be presented as labels discovered without uncertainty. PCA, t-SNE, UMAP, k-means and self-encoders respond to different objectives and constitute comparisons useful according to the application.
Exercises
- Differentiate and , including your spaces and roles.
- Calculate the example and confirm each coordinate.
- What happens to (7.5) when ?
- Explain why standardization can completely change BMU.
- Compare quantization error and topographic error.
- Implement a grid , manage your positions and run a Algorithm time.
7.2.10 Summary of the chapter
RNNs process sequences while maintaining a state and sharing parameters over time, its training unfolds the recurrence and applies the PTB. SOMS belong to another family: competitive learning not supervised with prototypes arranged in a grid. In both cases, the structure of the model — time in the NNR, neighborhood in the SOM — incorporates a hypothesis about important relationships in the data.
7.3 Multiple choice exercises
The first five questions deal with recurrent networks; the others deal with self-organizing maps. Each item has a single correct answer.
-
In a recurring network of Elman, the hidden state typically depends on:
- only.
- of and of the previous state .
- only the final label.
- of different and independent weights at each instant.
-
“Unfold” a RNN in time means:
- represent the successive cell applications as a graph along the Just a minute.
- physically duplicate the dataset.
- remove all recurrent connections.
- order neurons by the value of bias.
-
Sharing parameters over time allows RNN to:
- apply the same transition rule in different positions of the sequence.
- have a completely distinct model for each length.
- Dismiss any state.
- produce only sequences of size one.
-
Gradients that disappear in long sequences are associated with:
- repeated products of derivatives and matrices with contractive factors.
- complete absence of the chain rule.
- Mandatory use of whole numbers.
- a very large Gram matrix.
-
Truncated BPTT reduces computational cost to:
- limit the number of temporal steps by which the gradient is propagated.
- remove the forward propagation.
- train only the exit bias.
- make every sequence independent of the past.
-
A self-organizable map (SOM) is a learning method:
- supervised requiring a label for example.
- competitive and unsupervised.
- exclusive to time series labelled.
- based on retropropagation of cross-entropy.
-
The best matching unit (BMU) for an entry is generally the prototype which:
- is farther from .
- has less distance to .
- always occupies the upper left corner of the grid.
- received the largest class label.
-
In the update of an SOM, in addition to BMU, they are also moved:
- neighboring prototypes in the grid, with intensity defined by the function of Neighborhood.
- only examples of the test set.
- all prototypes for the same amount, mandatory.
- only prototypes with correct label.
-
During SOM training, it is common to gradually reduce:
- the learning rate and the neighborhood radius.
- the dimension of each input vector.
- the number of true classes.
- the amount of coordinates of the grid in each season.
-
The quantisation error of an SOM measures primarily:
- the mean distance between each example and its BMU.
- the accuracy of labels used in supervised training.
- the number of explosive gradients.
- the PAC probability of failure.
Answer key with explanations
- b. The state combines the current input with a short memory of the past.
- a. The unfolding explains the time dependencies and allows applying the Jail rule.
- a. The same weights are reused, which expresses invariance of the rule of processing to temporal position.
- a. Successive multiplications by factors smaller than one reduce magnitude The gradient signal.
- a. The truncation establishes a finite backpropagation window, changing long temporal memory by efficiency.
- b. SOM learns prototypes by competition and neighborhood cooperation without use targets during adjustment.
- b. BMU minimizes the distance between input and prototype vectors.
- a. Local cooperation organizes close prototypes on the grid to represent regions close to the data.
- a. Starting with broad neighborhood favors global organization; reduce it allows local refinement.
- a. This distance summarizes the fidelity with which prototypes represent the data, but it doesn’t measure topological preservation alone.