<jupyter_start><jupyter_text>Train a convolutional neural network on the MNIST dataset Gets to 85.83% test accuracy after 20 epochs (there is a lot of margin for parameter tuning).<jupyter_code>from __future__ import print_function

from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.losses import categorical_crossentropy
from tensorflow.keras.optimizers import RMSprop, Adadelta
import tensorflow.keras as keras
from tensorflow.keras import backend as K
batch_size = 128
num_classes = 10
epochs = 20

# input image dimensions
img_rows, img_cols = 28, 28

# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
# print('x_train shape:', x_train.shape)
print(x_train.shape, 'train samples')
print(x_test.shape, 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print(y_train.shape, 'train labels')
print(y_test.shape, 'test labels')
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())         
# model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=categorical_crossentropy,
              optimizer=Adadelta(),
              metrics=['accuracy'])
model.summary()
import time

start = time.time()

history = model.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

print("Training completed in %s seconds" % (time.time()-start))<jupyter_output>Epoch 1/20
469/469 [==============================] - 51s 108ms/step - loss: 2.2896 - accuracy: 0.1298 - val_loss: 2.2580 - val_accuracy: 0.2735
Epoch 2/20
469/469 [==============================] - 54s 115ms/step - loss: 2.2370 - accuracy: 0.2261 - val_loss: 2.1923 - val_accuracy: 0.4970
Epoch 3/20
469/469 [==============================] - 52s 111ms/step - loss: 2.1693 - accuracy: 0.3189 - val_loss: 2.1045 - val_accuracy: 0.5948
Epoch 4/20
469/469 [==============================] - 56s 120ms/step - loss: 2.0745 - accuracy: 0.3988 - val_loss: 1.9837 - val_accuracy: 0.6525
Epoch 5/20
469/469 [==============================] - 57s 122ms/step - loss: 1.9595 - accuracy: 0.4541 - val_loss: 1.8362 - val_accuracy: 0.6824
Epoch 6/20
469/469 [==============================] - 56s 119ms/step - loss: 1.8237 - accuracy: 0.4984 - val_loss: 1.6686 - val_accuracy: 0.7073
Epoch 7/20
469/469 [==============================] - 57s 122ms/step - loss: 1.6833 - accuracy: 0.5279 - val_loss: 1.4959 - val_ac[...]
{'fraction_non_alphanumeric': 0.18171926006528835, 'fraction_numerical': 0.08133841131664853, 'mean_word_length': 4.537650602409639, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '245990', 'license': 'MIT', 'n_tokens_mistral': 1527, 'n_tokens_neox': 1302, 'n_words': 303, 'path': '03_Applied_AI_DeepLearning/notebooks/week_3_3_cnn_mnist_classification.ipynb', 'repo_name': 'hsotoparada/Advanced-Data-Science-Specialization', 'size': '3676'}