<jupyter_start><jupyter_text>Convolutional Neural Network - MNIST Classification  Import Libs<jupyter_code>import tensorflow as tf
import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import normalize
from sklearn.metrics import confusion_matrix

import keras
from keras.datasets import mnist
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.callbacks import ModelCheckpoint
from keras import backend as K

tf.logging.set_verbosity(tf.logging.ERROR)

%matplotlib inline
%config InlineBackend.figure_format = 'retina'<jupyter_output>Using TensorFlow backend.<jupyter_text>Define one hot encode function<jupyter_code>def one_hot_encode(x, num_classes):
    one_hot = np.zeros([len(x), num_classes])
    for i in enumerate(x):
        one_hot[(i[0], i[1])] = 1
    return one_hot<jupyter_output><empty_output><jupyter_text>Read Data<jupyter_code>(train_X, train_y), (test_X, test_y) = mnist.load_data()
plt.imshow(train_X[5], cmap=plt.get_cmap('gray'))
plt.title(train_y[5])<jupyter_output><empty_output><jupyter_text>Normalize data<jupyter_code>train_X = train_X.astype(np.float32)
train_X /= 255.0

test_X = test_X.astype(np.float32)
test_X /= 255.0<jupyter_output><empty_output><jupyter_text>Encode outputs<jupyter_code>train_y = one_hot_encode(train_y, 10)
test_y = one_hot_encode(test_y, 10)<jupyter_output><empty_output><jupyter_text>Parameters<jupyter_code>batch_size = 128
num_classes = 10
epochs = 10

# input image dimensions
img_rows, img_cols = 28, 28
train_X = train_X.reshape(train_X.shape[0], img_rows, img_cols, 1)
test_X = test_X.reshape(test_X.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)<jupyter_output><empty_output><jupyter_text>Build Model<jupyter_code>model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.20))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.20))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.summary()<jupyter_output>_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 26, 26, 32)        320       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 24, 24, 64)        18496     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 12, 12, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 9216)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 128)               1179776   
_________________________________________________________________
dropout_2 [...]<jupyter_text>Train<jupyter_code>checkpoint = ModelCheckpoint('model/cnn-mnist-model-{epoch:03d}.h5',
                             monitor='val_loss',
                             verbose=0,
                             save_best_only=True,
                             mode='auto')

history = model.fit(train_X, train_y,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(test_X, test_y),
          callbacks = [checkpoint])<jupyter_output>Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 48s 797us/step - loss: 0.2100 - acc: 0.9354 - val_loss: 0.0502 - val_acc: 0.9831
Epoch 2/10
60000/60000 [==============================] - 47s 789us/step - loss: 0.0588 - acc: 0.9825 - val_loss: 0.0417 - val_acc: 0.9859
Epoch 3/10
60000/60000 [==============================] - 47s 788us/step - loss: 0.0396 - acc: 0.9879 - val_loss: 0.0359 - val_acc: 0.9885
Epoch 4/10
60000/60000 [==============================] - 47s 788us/step - loss: 0.0313 - acc: 0.9904 - val_loss: 0.0262 - val_acc: 0.9909
Epoch 5/10
60000/60000 [==============================] - 48s 792us/step - loss: 0.0252 - acc: 0.9922 - val_loss: 0.0299 - val_acc: 0.9898
Epoch 6/10
60000/60000 [==============================] - 46s 759us/step - loss: 0.0209 - acc: 0.9934 - val_loss: 0.0358 - val_acc: 0.9881
Epoch 7/10
60000/60000 [==============================] - 47s 786us/step - loss: 0.0171 - acc: 0.9941 - val_loss: 0.[...]<jupyter_text>Results<jupyter_code>plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()<jupyter_output><empty_output><jupyter_text>Load best model before overfitting<jupyter_code>score = model.evaluate(test_X, test_y, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])<jupyter_output>Test loss: 0.02635958956483164
Test accuracy: 0.9922
{'fraction_non_alphanumeric': 0.16071101337731356, 'fraction_numerical': 0.07714861645592816, 'mean_word_length': 4.558044806517311, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 37, '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': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '28947', 'license': 'MIT', 'n_tokens_mistral': 2108, 'n_tokens_neox': 1802, 'n_words': 348, 'path': 'CNN MNIST.ipynb', 'repo_name': 'vmf91/MachineLearning', 'size': '5457'}