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.
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.
Same filters for any image size: the filter slides over the whole image and shares its weights (§2.1).
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.
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).
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.
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.
Each shaded 2×2 block becomes one number on the right.
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 shape | Parameters | How |
|---|
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.
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.
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: –
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 / 255Press Train. The log appears here, epoch by epoch, like model.fit in Keras.
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)
Press Train. The CNN does far more arithmetic per image than the regular network, so each epoch takes longer.
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.
Train both models to compare them.
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()Train a model to see its predictions. Wrong ones are outlined in red.
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()