AI Fundamentals
Chapter 11 · How Machines See: Convolutional Networks

See a CNN work

Six steps that follow Chapter 11: why a regular network is too big for photos, how one filter slides over a digit, a filter you work out by hand, pooling, a CIFAR-10 CNN layer by layer, and then that CNN trained live in your browser. Everything runs here in your browser; nothing is uploaded.

See it live on your camera →

1 · Why not a basic NN for images? §2.1

A regular (fully connected) network connects every pixel to every neuron in the first hidden layer. Make the image bigger and watch the weights explode. A convolutional layer only learns its small filters, so its size doesn't depend on the image at all.

Regular network: first layer

Channels
Inputs
Weights + biases

Convolutional layer

Channels in
Weights + biases

Same filters for any image size: the filter slides over the whole image and shares its weights (§2.1).

Recall the digit network from Chapter 10: 784 inputs → 100 → 10
784×100 + 100 + 100×10 + 10 = 79,510

2 · A filter slides over a digit §2

A filter is a small grid of weights. At each spot it multiplies the 3×3 patch under it by its weights, adds them up, and writes one number into the feature map. A filter for horizontal lines lights up where the 7's top bar is. Draw on the digit to try your own.

Padding
Stride
Input: 28 × 28 (gray = zero padding)
Feature map
Click or drag on the input to draw.

The filter (its weights)

This step

Each box: pixel value × weight. Bright in the feature map = a big sum = "this pattern is here". The network learns its filter weights in training; you don't set them (§2).

3 · Your turn: a filter by hand §2

Slide the vertical-line filter over the 5×5 image with no padding (valid) and stride 1. At each of the 9 spots, multiply and add. Fill in the feature map, then check.

Image (5 × 5)
Filter (3 × 3)
Feature map (3 × 3)

Now: with padding='same', what size is the feature map?

4 · Pooling shrinks the feature map §3

A 2×2 pooling layer looks at each 2×2 block and keeps one number: the biggest (max) or the average. Each side halves, so there are 4× fewer numbers. Pooling has no weights; nothing is learned. This pools the feature map from step 2.

Pooling

Up close: a 4 × 4 piece of the map, where the most is happening

Each shaded 2×2 block becomes one number on the right.

5 · A CNN for CIFAR-10, layer by layer §4

This is a CNN for CIFAR-10 (32×32 color images, 10 classes). For each layer, predict its output shape and how many parameters it learns, then reveal. Hint: a Conv2D layer has filters × (3·3·channels in + 1) parameters.

#Layer (Keras)Output shapeParametersHow

Where the 3.43 million parameters are

Most of them sit in the first Dense layer right after Flatten. The convolution layers, which do the "seeing", are small, because their filters are shared across the image.

Compare: a regular network

Input 32×32×3 = 3,072 → Dense 2000 → Dense 2000 → Dense 10
3,072×2,000 + 2,000 = 6,146,000
2,000×2,000 + 2,000 = 4,002,000
2,000×10 + 10 = 20,010
Total = 10,168,010 parameters, about 3× the CNN's. More weights, yet it usually does worse on CIFAR-10, because flattening throws away which pixels are next to each other.

6 · CNN for CIFAR-10, live in your browser §6

Load CIFAR-10, train a regular feedforward network, train the CNN, compare their loss and accuracy, then predict. It runs here in your browser on part of CIFAR-10 so it runs in a few minutes. In Colab, the full version trains on all 50,000 images for 30 epochs, so its accuracy is higher than what you'll see here.

Test images: 1,000 · Backend: –
Loading CIFAR-10…

a · The data §6

CIFAR-10: 60,000 color photos, 32×32 pixels, 10 classes. Keras would download all of it. Here we load a subset and print the shapes the way the code does.

X_train: –   y_train: –
X_test:  –   y_test:  –
Code for this part
from keras.datasets import cifar10
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
print(X_train.shape)   # (50000, 32, 32, 3)
print(y_train.shape)   # (50000, 1)
print(X_test.shape)    # (10000, 32, 32, 3)
print(y_test.shape)    # (10000, 1)

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=[10, 10])
for i in range(25):
    plt.subplot(5, 5, i+1)
    plt.xticks([]); plt.yticks([])
    plt.imshow(X_train[i])
    plt.xlabel(class_names[y_train[i, 0]])
plt.show()

X_train = X_train / 255   # SCALE TO 0-1
X_test = X_test / 255

b · First, a regular feedforward network §6

Flatten 32×32×3 = 3,072 → Dense(2000, relu) → Dense(2000, relu) → Dense(10, softmax)
Parameters: 10,168,010 · optimizer sgd
Press Train. The log appears here, epoch by epoch, like model.fit in Keras.
Code for this part
model = keras.Sequential()
model.add(keras.layers.Flatten(input_shape=(32, 32, 3)))   # 3,072 INPUTS
model.add(keras.layers.Dense(2000, activation='relu'))
model.add(keras.layers.Dense(2000, activation='relu'))
model.add(keras.layers.Dense(10, activation='softmax'))
model.summary()   # 10,168,010 PARAMETERS

model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
h = model.fit(X_train, y_train, epochs=50, verbose=True)   # THE SLIDE RUNS 50 EPOCHS
model.evaluate(X_test, y_test)

c · Then the CNN §4

Model
Press Train. The CNN does far more arithmetic per image than the regular network, so each epoch takes longer.
Code for this part

d · Loss and accuracy §6

Dashed = training set, solid = validation (here, as in the Colab version, the test images). The test accuracy is measured on the 1,000 test images after training.

Regular network · test accuracy–
CNN · test accuracy–
regular lossregular val_lossCNN lossCNN val_loss
regular accuracyregular val_accuracyCNN accuracyCNN val_accuracy

Train both models to compare them.

Code for this part
plt.plot(history.history['loss'], 'black', linewidth=2.0)
plt.plot(history.history['val_loss'], 'green', linewidth=2.0)
plt.legend(['Training Loss', 'Validation Loss'])
plt.title('Loss Curves'); plt.show()

plt.plot(history.history['accuracy'], 'black', linewidth=2.0)
plt.plot(history.history['val_accuracy'], 'blue', linewidth=2.0)
plt.legend(['Training Accuracy', 'Validation Accuracy'])
plt.title('Accuracy Curves'); plt.show()

e · Predict §6

Predictions from

Train a model to see its predictions. Wrong ones are outlined in red.

Code for this part
pred = model.predict(X_test)               # 10 PROBABILITIES PER IMAGE
pred_classes = np.argmax(pred, axis=1)     # THE CLASS WITH THE HIGHEST

plt.figure(figsize=[10, 10])
for i in range(25):
    ax = plt.subplot(5, 5, i+1)
    ax.imshow(X_test[i])
    ax.set_title("True: %s \nPredict: %s" % (class_names[y_test[i, 0]], class_names[pred_classes[i]]))
    ax.axis('off')
plt.subplots_adjust(hspace=1)
plt.show()