Created
November 4, 2018 09:12
-
-
Save breadplop/3f9fc19b168c34ddf162f6319e864a71 to your computer and use it in GitHub Desktop.
BT4221 Assignment 4 Question 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from keras.datasets import mnist | |
from keras.utils import np_utils | |
from keras.layers import Input, Dense, Dropout, Activation, Flatten, Convolution2D, ZeroPadding2D, MaxPooling2D | |
from keras.models import Model | |
batch_size = 128 | |
nb_classes = 10 | |
epochs = 10 | |
# input image dimensions | |
img_rows, img_cols = 28, 28 | |
# number of convolutional filters to use | |
nb_filters = 32 | |
# size of pooling area for max pooling | |
pool_size = (2, 2) | |
# convolution kernel size | |
kernel_size = (1, 1) | |
# the data, shuffled and split between train and test sets | |
(X_train, y_train), (X_test, y_test) = mnist.load_data() | |
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) | |
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[0], 'train samples') | |
print(X_test.shape[0], 'test samples') | |
# convert class vectors to binary class matrices | |
Y_train = np_utils.to_categorical(y_train, nb_classes) | |
Y_test = np_utils.to_categorical(y_test, nb_classes) | |
# input functions for CNN | |
input_layer = Input(shape=(input_shape)) | |
layers = ZeroPadding2D((1,1))(input_layer) | |
layers = Convolution2D(nb_filters, (3, 3), activation='relu')(layers) | |
layers = ZeroPadding2D((1,1))(input_layer) | |
layers = Convolution2D(nb_filters, (3, 3), activation='relu')(layers) | |
layers = ZeroPadding2D((1,1))(input_layer) | |
layers = Convolution2D(nb_filters, (3, 3), activation='relu')(layers) | |
layers = ZeroPadding2D((1,1))(input_layer) | |
layers = Convolution2D(nb_filters, (3, 3), activation='relu')(layers) | |
layers = ZeroPadding2D((1,1))(layers) | |
layers = MaxPooling2D(pool_size, strides=(2,2))(layers) | |
layers= Flatten()(layers) | |
layers= Dense(128, activation='relu')(layers) | |
output_layer=Dense(10, activation='sigmoid')(layers) | |
model = Model(inputs=input_layer, outputs=output_layer) | |
model.compile(loss='categorical_crossentropy', | |
optimizer='adam', | |
metrics=['accuracy']) | |
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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment