import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten
from tensorflow import set_random_seed
from sklearn.model_selection import train_test_split
from keras.datasets import mnist
The MNIST dataset consists of 70,000, 28x28 black-and-white images of handwritten digits.
(X_train, y_train), (X_holdout, y_holdout) = mnist.load_data()
X_val, X_test, y_val, y_test = train_test_split(X_holdout, y_holdout, test_size = 0.5, random_state=1)
print(X_train.shape)
print(y_train.shape)
print(X_val.shape)
print(y_val.shape)
print(X_test.shape)
print(y_test.shape)
mydigit = X_train[0]
plt.imshow(mydigit, cmap=cm.binary)
plt.axis('off')
plt.show()
Xs_train = X_train / 255
Xs_val = X_val / 255
Xs_test = X_test / 255
%%time
np.random.seed(1)
set_random_seed(1)
model = Sequential()
model.add(Flatten(input_shape=(28,28)))
model.add(Dense(512, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
opt = keras.optimizers.Adam(lr = 0.001)
model.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
h = model.fit(Xs_train, y_train, batch_size=1024, epochs=20, validation_data=(Xs_val, y_val), verbose=2)
plt.rcParams["figure.figsize"] = [8,4]
plt.subplot(1,2,1)
plt.plot(h.history['loss'], label='Training')
plt.plot(h.history['val_loss'], label='Validation')
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend()
plt.subplot(1,2,2)
plt.plot(h.history['acc'], label='Training')
plt.plot(h.history['val_acc'], label='Validation')
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend()
plt.show()
score = model.evaluate(X_test, y_test, verbose=0)
print('Testing loss: ', score[0])
print('Testing accuracy:', score[1])
import tensorflow as tf
from keras.layers import Conv2D, MaxPooling2D
import keras
np.random.seed(1)
tf.set_random_seed(1)
model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', input_shape=(28,28,1), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax'))
opt = keras.optimizers.Adam(lr=0.001)
model.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
model.summary()
h = model.fit(Xs_train.reshape(-1,28,28,1), y_train,
batch_size=256, epochs=20, verbose=2,
validation_data = (Xs_val.reshape(-1,28,28,1), y_val))
np.random.seed(1)
Z_train = np.zeros((60000, 56, 56))
Z_val = np.zeros((5000, 56, 56))
Z_test = np.zeros((5000, 56, 56))
for i in range(60000):
ho, vo = np.random.choice(range(28)), np.random.choice(range(28))
Z_train[i, vo:(vo+28), ho:(ho+28)] = X_train[i]
for i in range(5000):
ho, vo = np.random.choice(range(28)), np.random.choice(range(28))
Z_val[i, vo:(vo+28), ho:(ho+28)] = X_val[i]
for i in range(5000):
ho, vo = np.random.choice(range(28)), np.random.choice(range(28))
Z_test[i, vo:(vo+28), ho:(ho+28)] = X_test[i]
n = np.random.choice(range(6000))
plt.imshow(Z_train[n,:,:], cmap=cm.binary)
plt.axis('off')
plt.show()
Zs_train = Z_train / 255
Zs_val = Z_val / 255
Zs_test = Z_test / 255
%%time
np.random.seed(1)
set_random_seed(1)
model = Sequential()
model.add(Flatten(input_shape=(56,56)))
model.add(Dense(512, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.summary()
opt = keras.optimizers.Adam(lr = 0.001)
model.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
h = model.fit(Zs_train, y_train, batch_size=1024, epochs=20, validation_data=(Zs_val, y_val), verbose=2)
plt.rcParams["figure.figsize"] = [8,4]
plt.subplot(1,2,1)
plt.plot(h.history['loss'], label='Training')
plt.plot(h.history['val_loss'], label='Validation')
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend()
plt.subplot(1,2,2)
plt.plot(h.history['acc'], label='Training')
plt.plot(h.history['val_acc'], label='Validation')
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend()
plt.show()
np.random.seed(1)
tf.set_random_seed(1)
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(56,56,1), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(100, activation='softmax'))
opt = keras.optimizers.Adam(lr=0.001)
model.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
model.summary()
h = model.fit(Zs_train.reshape(-1,56,56,1), y_train,
batch_size=256, epochs=20, verbose=2,
validation_data = (Zs_val.reshape(-1,56,56,1), y_val))
plt.rcParams["figure.figsize"] = [8,4]
plt.subplot(1,2,1)
plt.plot(h.history['loss'], label='Training')
plt.plot(h.history['val_loss'], label='Validation')
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend()
plt.subplot(1,2,2)
plt.plot(h.history['acc'], label='Training')
plt.plot(h.history['val_acc'], label='Validation')
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend()
plt.show()