GNGiseldo Neo and Alana NeoBooks
Mathematical Foundations for Machine Learning8 / 8

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 xt∈Rdxx_t\in\mathbb R^{d_x} the input at tt and ht∈Rdhh_t\in\mathbb R^{d_h} the hidden state. A simple RNN of Elman calculates

ht=ϕ(Wxhxt+Whhht−1+bh),(7.1) h_t =\phi(W_{xh}x_t+W_{hh}h_{t-1}+b_h), \tag{7.1} ot=Whyht+by,y^t=ψ(ot).(7.2) o_t=W_{hy}h_t+b_y, \qquad \widehat y_t=\psi(o_t). \tag{7.2}

Parameters have formats

Wxh∈Rdh×dx,Whh∈Rdh×dh,Why∈Rdy×dh. W_{xh}\in\mathbb R^{d_h\times d_x}, \quad W_{hh}\in\mathbb R^{d_h\times d_h}, \quad W_{hy}\in\mathbb R^{d_y\times d_h}.

The ϕ\phi activation is usually tanh in a simple RNN. ψ\psi depends on the task: identity for regression, sigmoid for binary output or softmax for exclusive classes.

The initial state h0h_0 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:

ht=Fθ(xt,ht−1). h_t=F_\theta(x_t,h_{t-1}).

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.

A recurrent NNR and its unfolding: the same parameters are reused in all steps.

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 T=100T=100 steps does not have a hundred WhhW_{hh} 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 B×T×dxB\times T\times d_x: 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: hth_t depends on ht−1h_{t-1}. 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

E=∑t=1Tℓt(y^t,yt), E=\sum_{t=1}^{T}\ell_t(\widehat y_t,y_t),

the hth_t state can influence the loss in the step itself and all the future losses. Its derivative accumulates these paths. In a way simplified,

∂E∂ht=∂ℓt∂ht+∂E∂ht+1∂ht+1∂ht. \frac{\partial E}{\partial h_t} = \frac{\partial\ell_t}{\partial h_t} + \frac{\partial E}{\partial h_{t+1}} \frac{\partial h_{t+1}}{\partial h_t}.

For Elman’s recurrence,

∂ht+1∂ht=diag⁡ ⁣(ϕ′(zt+1))Whh. \frac{\partial h_{t+1}}{\partial h_t} = \operatorname{diag}\!\left( \phi'(z_{t+1}) \right)W_{hh}.

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 KK 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 KK 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:

  1. the effective depth depends on the length of the sequence;
  2. 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

  1. Check the formats in (7.1) and (7.2).
  2. How many parameters does a RNN have with dx=10d_x=10, dh=32d_h=32 e dy=5d_y=5?
  3. Explain why the number of parameters does not depend on TT.
  4. Differentiate fill, mask and truncated BPTT.
  5. Show how repeated products from a ∣λ∣<1|\lambda|<1 scale help understand the disappearance of the gradient.
  6. When a step-by-step output is required and when only hTh_T 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 x∈Rdx\in\mathbb R^d and MM drives. Each unit ii has:

  • a fixed position ri∈Rqr_i\in\mathbb R^q on the grid, normally q=2q=2;
  • a training prototype wi∈Rdw_i\in\mathbb R^d in the data space.

∥x−wi∥\lVert x-w_i\rVert distances compare an example to prototypes. ∥ri−rj∥\lVert r_i-r_j\rVert distances compare positions in the grid. Mix these two spaces make the algorithm incorrect.

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.

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 xtx_t, the winning drive, or BMU (best matching unit), is

ct=arg min⁡i=1,…,M∥xt−wi(t)∥2.(7.3) c_t =\operatorname*{arg\,min}_{i=1,\ldots,M} \lVert x_t-w_i(t)\rVert^2. \tag{7.3}

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 ii unit may be Gaussian:

Hcti(t)=exp⁡ ⁣(−∥ri−rct∥22σ(t)2).(7.4) H_{c_ti}(t) =\exp\!\left( -\frac{\lVert r_i-r_{c_t}\rVert^2}{2\sigma(t)^2} \right). \tag{7.4}

This function is not a metric: it is maximum in nearby units and decreases with distance. The parameter σ(t)>0\sigma(t)>0 is the radius of neighborhood. The square in σ(t)2\sigma(t)^2 is required in the form usual gaussian.

7.2.4 Update Rule

All prototypes are updated by

wi(t+1)=wi(t)+η(t)Hcti(t)(xt−wi(t)),(7.5) w_i(t+1) =w_i(t) +\eta(t)H_{c_ti}(t) \bigl(x_t-w_i(t)\bigr), \tag{7.5}

where 0<η(t)<10<\eta(t)<1 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 t=0,…,T−1t=0,\ldots,T-1 is

η(t)=η0(ηfη0)t/(T−1),σ(t)=σ0(σfσ0)t/(T−1). \eta(t)=\eta_0 \left(\frac{\eta_f}{\eta_0}\right)^{t/(T-1)}, \qquad \sigma(t)=\sigma_0 \left(\frac{\sigma_f}{\sigma_0}\right)^{t/(T-1)}.

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

  1. Standardize features when your scales are not comparable.
  2. Create rir_i positions from a grid and initialize prototypes wiw_i.
  3. For each iteration:
    1. choose an example, usually with shuffled order;
    2. find the BMU by (7.3);
    3. calculate the influence on the grid by (7.4);
    4. update the prototypes by (7.5);
    5. reduce η(t)\eta(t) and σ(t)\sigma(t).
  4. 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

w1=(0,5,0,6,0,8),w2=(0,4,0,2,0,5) w_1=(0{,}5,0{,}6,0{,}8), \qquad w_2=(0{,}4,0{,}2,0{,}5)

and the x=(0,8,0,7,0,4)x=(0{,}8,0{,}7,0{,}4) example. Quadratic distances are

∥x−w1∥2=0,32+0,12+(−0,4)2=0,26, \lVert x-w_1\rVert^2 =0{,}3^2+0{,}1^2+(-0{,}4)^2 =0{,}26, ∥x−w2∥2=0,42+0,52+(−0,1)2=0,42. \lVert x-w_2\rVert^2 =0{,}4^2+0{,}5^2+(-0{,}1)^2 =0{,}42.

Therefore, BMU is unit 1. With η=0,5\eta=0{,}5, influence H11=1H_{11}=1 and, to simplify, zero influence on the other unit,

w1′=w1+0,5(x−w1)=(0,5,0,6,0,8)+0,5(0,3,0,1,−0,4)=(0,65,0,65,0,60). \begin{aligned} w_1' &=w_1+0{,}5(x-w_1)\\ &=(0{,}5,0{,}6,0{,}8) +0{,}5(0{,}3,0{,}1,-0{,}4)\\ &=(0{,}65,0{,}65,0{,}60). \end{aligned}

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 H12=0,4H_{12}=0{,}4, then

w2′=w2+0,5⋅0,4(x−w2)=(0,48,0,30,0,48). w_2' =w_2+0{,}5\cdot0{,}4(x-w_2) =(0{,}48,0{,}30,0{,}48).

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

[:, None]\texttt{[:, None]} index transforms format influence MM in a M×1M\times1 column , allowing to multiply it by M×dM\times d 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

  1. Differentiate rir_i and wiw_i, including your spaces and roles.
  2. Calculate the example w2′w_2' and confirm each coordinate.
  3. What happens to (7.5) when σ(t)→0\sigma(t)\to0?
  4. Explain why standardization can completely change BMU.
  5. Compare quantization error and topographic error.
  6. Implement a 3×33\times3 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.

  1. In a recurring network of Elman, the hidden state hth_t typically depends on:

    1. xtx_t only.
    2. of xtx_t and of the previous state ht−1h_{t-1}.
    3. only the final label.
    4. of different and independent weights at each instant.
  2. “Unfold” a RNN in time means:

    1. represent the successive cell applications as a graph along the Just a minute.
    2. physically duplicate the dataset.
    3. remove all recurrent connections.
    4. order neurons by the value of bias.
  3. Sharing parameters over time allows RNN to:

    1. apply the same transition rule in different positions of the sequence.
    2. have a completely distinct model for each length.
    3. Dismiss any state.
    4. produce only sequences of size one.
  4. Gradients that disappear in long sequences are associated with:

    1. repeated products of derivatives and matrices with contractive factors.
    2. complete absence of the chain rule.
    3. Mandatory use of whole numbers.
    4. a very large Gram matrix.
  5. Truncated BPTT reduces computational cost to:

    1. limit the number of temporal steps by which the gradient is propagated.
    2. remove the forward propagation.
    3. train only the exit bias.
    4. make every sequence independent of the past.
  6. A self-organizable map (SOM) is a learning method:

    1. supervised requiring a label for example.
    2. competitive and unsupervised.
    3. exclusive to time series labelled.
    4. based on retropropagation of cross-entropy.
  7. The best matching unit (BMU) for an entry xx is generally the prototype which:

    1. is farther from xx.
    2. has less distance to xx.
    3. always occupies the upper left corner of the grid.
    4. received the largest class label.
  8. In the update of an SOM, in addition to BMU, they are also moved:

    1. neighboring prototypes in the grid, with intensity defined by the function of Neighborhood.
    2. only examples of the test set.
    3. all prototypes for the same amount, mandatory.
    4. only prototypes with correct label.
  9. During SOM training, it is common to gradually reduce:

    1. the learning rate and the neighborhood radius.
    2. the dimension of each input vector.
    3. the number of true classes.
    4. the amount of coordinates of the grid in each season.
  10. The quantisation error of an SOM measures primarily:

    1. the mean distance between each example and its BMU.
    2. the accuracy of labels used in supervised training.
    3. the number of explosive gradients.
    4. the PAC probability of failure.

Answer key with explanations

  1. b. The state combines the current input with a short memory of the past.
  2. a. The unfolding explains the time dependencies and allows applying the Jail rule.
  3. a. The same weights are reused, which expresses invariance of the rule of processing to temporal position.
  4. a. Successive multiplications by factors smaller than one reduce magnitude The gradient signal.
  5. a. The truncation establishes a finite backpropagation window, changing long temporal memory by efficiency.
  6. b. SOM learns prototypes by competition and neighborhood cooperation without use targets during adjustment.
  7. b. BMU minimizes the distance between input and prototype vectors.
  8. a. Local cooperation organizes close prototypes on the grid to represent regions close to the data.
  9. a. Starting with broad neighborhood favors global organization; reduce it allows local refinement.
  10. a. This distance summarizes the fidelity with which prototypes represent the data, but it doesn’t measure topological preservation alone.