Lecture 6 · Machine Learning for ICE · University of Klagenfurt, 2023
Lecture 6 of 8
Beyond the fully connected network, architectures built around the structure of the data:
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.
01
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
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.
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)
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.
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.
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.

the Pyramidenkogel tower, above the Wörthersee
02
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.
Depending on the application:
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 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 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.
A dataset of 2,075,259 measurements gathered in a house near Paris between December 2006 and November 2010 (47 months), one per minute:
Predict the global active power, hour by hour, with an LSTM recurrent network.
The dataset: Individual household electric power consumption, UCI Machine Learning Repository.
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

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.
03
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
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.
K. Xu et al., Show, attend and tell: neural image caption generation with visual attention, 2015.
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:
A. Vaswani et al., Attention is all you need, 2017.
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.
# 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
“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.
letizia.tech · Machine Learning for ICE · University of Klagenfurt