Convolutional Neural Networks Basics
Add Conv2D and MaxPooling layers for image classification tasks.
Why CNNs for Images?
A dense network treats pixels independently, losing spatial relationships. A convolutional neural network (CNN) applies learnable filters that slide across the input, detecting local patterns like edges, textures, and shapes regardless of position. This translation invariance and parameter sharing make CNNs the gold standard for image data.
library(keras)
# Images are 3D tensors: (height, width, channels)
# MNIST: (28, 28, 1) — grayscale
# CIFAR-10: (32, 32, 3) — RGB
# Reshape flat vectors into image tensors
mnist <- dataset_mnist()
x_train <- array_reshape(mnist$train$x / 255, c(-1, 28, 28, 1))
y_train <- to_categorical(mnist$train$y, 10)
cat('Input shape:', dim(x_train))layer_conv_2d() — The Core Layer
layer_conv_2d(filters, kernel_size, activation) applies filters learnable 2D kernels of size kernel_size to the input. Each filter learns to detect one type of spatial pattern. The output has shape (height, width, filters).
library(keras)
# First conv layer: 32 filters of 3x3
model <- keras_model_sequential(input_shape = c(28, 28, 1)) |>
layer_conv_2d(
filters = 32,
kernel_size = c(3, 3),
activation = 'relu',
padding = 'same' # keep spatial dimensions
)
summary(model) # output: (None, 28, 28, 32)All lessons in this course
- Setting Up Keras and TensorFlow in R
- Building Sequential Models
- Convolutional Neural Networks Basics
- Training, Validation, and Preventing Overfitting