A convolutional layer learns local patterns in an image instead of looking at every pixel at once. It takes small patches from a feature map and applies the same learned transformation at each location. A pattern learned in one part of an image can therefore be recognized elsewhere. Stacking these layers lets a network build from simple patterns, such as edges, toward more complex visual features. section 8.1.1
Listing 8.1 Instantiating a small convnet
library(keras3) inputs <- keras_input(shape = c(28, 28, 1)) outputs <- inputs |> layer_conv_2d(filters = 64, kernel_size = 3, activation = "relu") |> layer_max_pooling_2d(pool_size = 2) |> layer_conv_2d(filters = 128, kernel_size = 3, activation = "relu") |> layer_max_pooling_2d(pool_size = 2) |> layer_conv_2d(filters = 256, kernel_size = 3, activation = "relu") |> layer_global_average_pooling_2d() |> layer_dense(10, activation = "softmax") model <- keras_model(inputs = inputs, outputs = outputs)
This R/Keras model starts with 28 × 28 grayscale digit images. Three convolutional layers alternate with pooling layers; global average pooling and a softmax layer turn the resulting features into ten digit probabilities. section 8.1
Read each `layer_conv_2d()` call in terms of its input and output:
- The input is a feature map with height, width and channels. An MNIST image has one channel; an RGB image has three. section 8.1 section 8.1.1
- `kernel_size = 3` selects 3 × 3 patches. The `filters` argument sets the number of output channels, each representing a learned pattern’s response across the image. section 8.1 section 8.1.1
- Height and width can shrink as layers accumulate. Padding and strides affect which patches are used and how the spatial dimensions change; pooling is another way to downsample. section 8.1.1 section 8.1
Classify handwritten digits
Reshape MNIST images to `(28, 28, 1)`, divide pixel values by 255, then compile the model with `rmsprop`, `sparse_categorical_crossentropy` and accuracy. Fit for five epochs with batches of 64 and evaluate on the test images. The reported test accuracy is 0.9931, compared with 97.8% for the earlier densely connected model. section 8.1
Choose downsampling to suit the output. For classification, pooling can reduce feature-map size before a final classifier. For image segmentation, pixel locations matter: strided convolutions downsample while retaining more location information than max pooling, and transposed convolutions restore spatial dimensions for per-pixel predictions. section 8.1 section 11.3.2













