Advanced architectures

Lecture 6 · Machine Learning for ICE · University of Klagenfurt, 2023

Nunzio Alexandro Letizia

This lecture

Lecture 6 of 8

Beyond the fully connected network, architectures built around the structure of the data:

  1. Convolutional networks, for spatial data
  2. Recurrent networks and the LSTM, for sequences
  3. Attention and transformers

From Machine Learning for ICE at the University of Klagenfurt, first taught in 2022: this is the 2023 edition. This lecture is the one that has aged the most: it stops at Stable Diffusion 1.5, a few months after ChatGPT came out. All lectures.

Convolutional networks

01

Convolutional neural networks

Convolutional neural networks (CNNs) are designed to capture spatial dependencies: image and document recognition, medical image analysis, natural language processing.

CNNs are feed-forward networks whose hidden layers are convolutional layers, made of filters (kernels) that detect patterns in the data. CNNs

  • are excellent at feature and representation learning
  • are regularized by design: not fully connected, with shared weights
  • need far fewer weights than a fully connected network of the same size

The convolutional layer

A CNN chains three operations: convolution (filtering), activation (a non-linearity), pooling (max or average).

Given an input tensor I with C channels and kernels K_{i,j}, where j indexes the feature maps, the feature map F_j is

F_j=\sigma\Big(\sum_{i=1}^CI_i*K_{i,j}+B_j\Big)

where

(I_i*K_{i,j})[x,y]=\sum_l\sum_mK_{i,j}[l,m]\cdot I_i[x-l,y-m]

If the (square) image has size W and the kernel size K, the feature map has size W-K+1.

Convolution, in a picture

A 5 by 5 input with its top-left 3 by 3 window highlighted, a 3 by 3 vertical-edge kernel, and the resulting 3 by 3 feature map with the first entry highlighted.

Slide the kernel over the input; at each position, multiply element by element and sum. A 5\times5 input and a 3\times3 kernel give a 3\times3 map, W-K+1=3. This kernel responds to vertical edges.

as deep-learning libraries compute it: without flipping the kernel (a cross-correlation)

Stride, padding, pooling

  • Stride S controls how far the filter moves at each step, so the overlap and the size of the feature map. S=1 moves pixel by pixel.
  • Padding P adds a border, so that edge pixels count as much as the others and the size can be preserved.

The size of the feature map becomes

\frac{W-K+2P}{S}+1

Feature maps shrink with depth, so layers near the input tend to have few filters and deeper layers more.

  • Pooling is a non-linear down-sampling: it progressively reduces the size of the feature maps, and helps against overfitting.
  • Activation: a ReLU usually follows each convolution, before the pooling.

Max pooling: a 4 by 4 grid split into four 2 by 2 blocks becomes a 2 by 2 grid holding the maximum of each block.

Deep CNNs

A deep CNN stacks these layers, then flattens the last feature maps into fully connected layers. Famous ones: AlexNet, VGG16, VGG19, InceptionV3, ResNet50, MobileNet.

VGG-16 (Simonyan and Zisserman, 2014): 13 convolutional layers with 3\times3 kernels, (K,P,S)=(3,1,1), in five blocks, each closed by a 2\times2 max pooling, (K,P,S)=(2,0,2), then 3 fully connected layers. The size halves at every block, from 224\times224 to 7\times7, while the channels grow from 64 to 512.

VGG-16 as a sequence of blocks: two, two, three, three and three convolutional layers, each block followed by max pooling, then three fully connected layers and a softmax.

Activity 7: VGG-16

Load the VGG-16 network, pre-trained, with Keras, and classify an image of your choice. What are the top 5 predicted labels?

model = VGG16()   # pre-trained on ImageNet
image = load_img('pyr_klu.jpg', target_size=(224, 224))
image = img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
image = preprocess_input(image)

yhat = model.predict(image)
label = decode_predictions(yhat, top=5)
for i in range(5):
    print('%s (%.2f%%)' % (label[0][i][1], label[0][i][2]*100))
lakeside (25.51%)
castle (8.75%)
cliff (7.71%)
beacon (5.39%)
promontory (4.61%)

ImageNet has no class for an observation tower: VGG-16 sees the lake first, then reaches for the nearest tall structures it knows, a castle, a beacon.

Aerial view of the Pyramidenkogel observation tower above the Wörthersee lake near Klagenfurt.

the Pyramidenkogel tower, above the Wörthersee

Recurrent networks

02

Recurrent neural networks

Recurrent neural networks (RNNs) deal with sequential data, as in natural language processing: dependencies in time, and inputs of variable length.

At each time step t, the activation a^{\langle t\rangle} and the output y^{\langle t\rangle} are

a^{\langle t\rangle}=g_1\big(W_{aa}a^{\langle t-1\rangle}+W_{ax}x^{\langle t\rangle}+b_a\big),\qquad y^{\langle t\rangle}=g_2\big(W_{ya}a^{\langle t\rangle}+b_y\big)

with the same weights at every step.

An RNN unrolled over three time steps: each cell takes an input and the previous activation, and produces an output and the next activation.

Pros, cons, shapes

  • Pros: inputs of any length, a model size that does not grow with it, weights shared across time.
  • Cons: slow computation, and training works poorly in practice, because gradients vanish over long-term dependencies.

Depending on the application:

  • one-to-one (a traditional network, image classification)
  • one-to-many (music generation, image captioning)
  • many-to-one (sentiment analysis)
  • many-to-many (machine translation, video classification)

Four small diagrams of recurrent networks: one-to-one, one-to-many, many-to-one and many-to-many.

Gates

To fight vanishing and exploding gradients, RNN cells get gates:

\Gamma=\sigma\big(Wx^{\langle t\rangle}+Ua^{\langle t-1\rangle}+b\big)

where W,U,b belong to the gate and \sigma is the sigmoid, with values in [0,1]. A gate decides how much of a piece of information goes through the cell.

Gate Role
forget \Gamma_f erase the cell or not
relevance \Gamma_r drop the previous state or not
update \Gamma_u how much new information to store
output \Gamma_o how much of the cell to reveal

The gated recurrent unit (GRU) and the long short-term memory (LSTM) work much better than plain RNNs. The cell state aggregates the data of all previous steps, the hidden state characterizes the previous step.

The LSTM cell, in a picture

An LSTM cell: the cell state runs along the top, modified by the forget gate and by the update gate times the candidate; the output gate times tanh of the cell state gives the new activation.

The cell state runs along the top almost untouched: the forget gate scales it, the update gate adds new content. That straight path is what lets gradients survive over long sequences.

The LSTM

The LSTM uses forget, update and output gates (the relevance gate belongs to the GRU):

\begin{aligned} \Gamma_f&=\sigma\big(W_fx^{\langle t\rangle}+U_fa^{\langle t-1\rangle}+b_f\big)&&\text{keep the cell state or not}\\ \Gamma_u&=\sigma\big(W_ux^{\langle t\rangle}+U_ua^{\langle t-1\rangle}+b_u\big)&&\text{how much to update}\\ \Gamma_o&=\sigma\big(W_ox^{\langle t\rangle}+U_oa^{\langle t-1\rangle}+b_o\big)&&\text{what to output}\\ \tilde c^{\langle t\rangle}&=\tanh\big(W_cx^{\langle t\rangle}+U_ca^{\langle t-1\rangle}+b_c\big)&&\text{candidate cell state}\\ c^{\langle t\rangle}&=\Gamma_f\odot c^{\langle t-1\rangle}+\Gamma_u\odot\tilde c^{\langle t\rangle}\\ a^{\langle t\rangle}&=\Gamma_o\odot\tanh\big(c^{\langle t\rangle}\big) \end{aligned}

A clear picture of the cell: C. Olah, Understanding LSTM networks, 2015.

Forecasting with an LSTM

A dataset of 2,075,259 measurements gathered in a house near Paris between December 2006 and November 2010 (47 months), one per minute:

  • date and time
  • global active and reactive power (kW), voltage (V), current intensity (A)
  • three sub-meterings (Wh): the kitchen (dishwasher, oven, microwave), the laundry room (washing machine, tumble-drier, fridge, a light), and an electric water heater with an air conditioner

Predict the global active power, hour by hour, with an LSTM recurrent network.

The dataset: Individual household electric power consumption, UCI Machine Learning Repository.

Activity 8: the outcome

The minutes are averaged to hours (34,589 of them), all 7 features are scaled to [0,1], and the task becomes: from the features at hour t-1, predict the active power at hour t. The first year (8,760 hours) trains, the rest tests.

model = Sequential()
model.add(LSTM(100, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')

history = model.fit(train_X, train_y, epochs=20, batch_size=70,
                    validation_data=(test_X, test_y), shuffle=False)
Test RMSE: 0.616

Actual and predicted hourly global active power over 200 hours: the prediction follows the daily peaks, smoothing the highest ones.

200 hours of the test set, in kW

The forecast follows the daily rhythm of the house and most of the peaks, but smooths the sharpest ones: with one hour of history, a sudden spike is hard to see coming.

The data preparation follows a public Kaggle notebook by Amir Rezaeian.

Attention and transformers

03

Image captioning

Language modelling needs to understand which part of a sentence matters for the task (a translation, for instance).

Captioning images has the same problem: the model should look at the relevant regions of the image, not the whole of it at once. Different words of a caption usually come from different regions.

Image CNN encoder h LSTM decoder “a dog on a beach”

a basic captioning model: the encoder extracts a hidden representation, the decoder produces the text word by word

Soft attention

Instead of the same representation h for every word, extract n representations \mathbf{y}_i, one per sub-region of the image, and let an attention unit decide which regions to use for each word.

The unit measures the similarity between each sub-region \mathbf{y}_i and the context \mathbf{C} (what has been generated so far):

\mathbf{m}_i=\tanh\big(W_{y}\mathbf{y}_i+W_C\mathbf{C}\big),\qquad s_i=\frac{e^{\mathbf{w}^T\mathbf{m}_i}}{\sum_je^{\mathbf{w}^T\mathbf{m}_j}},\qquad\mathbf{z}=\sum_is_i\,\mathbf{y}_i

The weights s_i sum to one: \mathbf{z} is an average of the regions, weighted by their relevance to the current word.

Transformers

LSTMs struggle with long sequences, and they process words one after the other, which makes them slow. Can the words go in parallel?

It turns out that “attention is all you need” (Vaswani et al., 2017): the transformer has no recurrent and no convolutional blocks. An encoder and a decoder, built from:

  • input embedding: the representation of a word, where similar words are close together
  • positional encoding: adds to each embedding the position of the word in the sentence
  • multi-head attention: computes several attention vectors for each word, in parallel
  • feed-forward layers: turn the attention vectors into inputs for the next block

Transformer: an encoder stack of attention and feed-forward layers feeding the cross attention of a decoder stack, which predicts the next word.

A. Vaswani et al., Attention is all you need, 2017.

Text to image

DALL-E (OpenAI, 2021) is a zero-shot text-to-image network: a discrete variational autoencoder compresses images into tokens, and a transformer models text and image tokens jointly.

Use the openly available Russian version, ruDALL-E, which uses a VQGAN instead of the VAE, to generate any image you like from a text prompt. Use CLIP to score the quality of the generations.

Activity 9: the outcome

# ruDALL-E reads Russian: translate the prompt first
text = 'Lake'
text = translators.google(text, from_language='en',
                          to_language='ru')   # 'Озеро'

seed_everything(42)
pil_images, scores = [], []
for top_k, top_p, images_num in [(2048, 0.995, 3)]:
    _pil_images, _scores = generate_images(
        text, tokenizer, dalle, vae,
        top_k=top_k, images_num=images_num, top_p=top_p)
    pil_images += _pil_images
    scores += _scores
# then: rank with ruCLIP, upscale 2x with Real-ESRGAN

Three images generated by ruDALL-E for the prompt lake: a mountain lake, a dark forest lake and a lake with trees and a jetty.

“Lake”, three samples, in May 2022

A 1.3-billion-parameter model on a Colab GPU: recognisable lakes, with the soft, smudged details of text-to-image in 2022.

Update 2023. Now do the same text-to-image task with Stable Diffusion 1.5.

In 2023 these were state of the art. Text-to-image models have moved a long way since, and lectures 7 and 8 cover some of the ideas underneath: autoencoders, VAEs and GANs.

Next: Lecture 7, deep learning for the physical layer