|
| 1 | +import mnist |
| 2 | +import candle_keras as candle |
| 3 | + |
| 4 | +from keras.callbacks import CSVLogger |
| 5 | +from keras import backend as K |
| 6 | + |
| 7 | +def initialize_parameters(): |
| 8 | + mnist_common = mnist.MNIST(mnist.file_path, |
| 9 | + 'mnist_params.txt', |
| 10 | + 'keras', |
| 11 | + prog='mnist_cnn', |
| 12 | + desc='MNIST CNN example' |
| 13 | + ) |
| 14 | + |
| 15 | + # Initialize parameters |
| 16 | + gParameters = candle.initialize_parameters(mnist_common) |
| 17 | + csv_logger = CSVLogger('{}/params.log'.format(gParameters)) |
| 18 | + |
| 19 | + return gParameters |
| 20 | + |
| 21 | +def run(gParameters): |
| 22 | + ########################################## |
| 23 | + # Your DL start here. See mnist_cnn.py # |
| 24 | + ########################################## |
| 25 | + |
| 26 | + '''Trains a simple convnet on the MNIST dataset. |
| 27 | +
|
| 28 | + Gets to 99.25% test accuracy after 12 epochs |
| 29 | + (there is still a lot of margin for parameter tuning). |
| 30 | + 16 seconds per epoch on a GRID K520 GPU. |
| 31 | + ''' |
| 32 | + |
| 33 | + # from __future__ import print_function |
| 34 | + |
| 35 | + import keras |
| 36 | + from keras.datasets import mnist |
| 37 | + from keras.models import Sequential |
| 38 | + from keras.layers import Dense, Dropout, Flatten |
| 39 | + from keras.layers import Conv2D, MaxPooling2D |
| 40 | + from keras import backend as K |
| 41 | + |
| 42 | + batch_size = gParameters['batch_size'] |
| 43 | + num_classes = 10 |
| 44 | + epochs = gParameters['epochs'] |
| 45 | + |
| 46 | + activation = gParameters['activation'] |
| 47 | + optimizer = gParameters['optimizer'] |
| 48 | + |
| 49 | + # input image dimensions |
| 50 | + img_rows, img_cols = 28, 28 |
| 51 | + |
| 52 | + # the data, split between train and test sets |
| 53 | + (x_train, y_train), (x_test, y_test) = mnist.load_data() |
| 54 | + |
| 55 | + if K.image_data_format() == 'channels_first': |
| 56 | + x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) |
| 57 | + x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) |
| 58 | + input_shape = (1, img_rows, img_cols) |
| 59 | + else: |
| 60 | + x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) |
| 61 | + x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) |
| 62 | + input_shape = (img_rows, img_cols, 1) |
| 63 | + |
| 64 | + x_train = x_train.astype('float32') |
| 65 | + x_test = x_test.astype('float32') |
| 66 | + x_train /= 255 |
| 67 | + x_test /= 255 |
| 68 | + print('x_train shape:', x_train.shape) |
| 69 | + print(x_train.shape[0], 'train samples') |
| 70 | + print(x_test.shape[0], 'test samples') |
| 71 | + |
| 72 | + # convert class vectors to binary class matrices |
| 73 | + y_train = keras.utils.to_categorical(y_train, num_classes) |
| 74 | + y_test = keras.utils.to_categorical(y_test, num_classes) |
| 75 | + |
| 76 | + model = Sequential() |
| 77 | + model.add(Conv2D(32, kernel_size=(3, 3), |
| 78 | + activation='relu', |
| 79 | + input_shape=input_shape)) |
| 80 | + model.add(Conv2D(64, (3, 3), activation='relu')) |
| 81 | + model.add(MaxPooling2D(pool_size=(2, 2))) |
| 82 | + model.add(Dropout(0.25)) |
| 83 | + model.add(Flatten()) |
| 84 | + model.add(Dense(128, activation='relu')) |
| 85 | + model.add(Dropout(0.5)) |
| 86 | + model.add(Dense(num_classes, activation='softmax')) |
| 87 | + |
| 88 | + model.compile(loss=keras.losses.categorical_crossentropy, |
| 89 | + optimizer=keras.optimizers.Adadelta(), |
| 90 | + metrics=['accuracy']) |
| 91 | + |
| 92 | + history = model.fit(x_train, y_train, |
| 93 | + batch_size=batch_size, |
| 94 | + epochs=epochs, |
| 95 | + verbose=1, |
| 96 | + validation_data=(x_test, y_test)) |
| 97 | + score = model.evaluate(x_test, y_test, verbose=0) |
| 98 | + print('Test loss:', score[0]) |
| 99 | + print('Test accuracy:', score[1]) |
| 100 | + ########################################## |
| 101 | + # End of mnist_mlp.py #################### |
| 102 | + ########################################## |
| 103 | + |
| 104 | + return history |
| 105 | + |
| 106 | +def main(): |
| 107 | + |
| 108 | + gParameters = initialize_parameters() |
| 109 | + run(gParameters) |
| 110 | + |
| 111 | +if __name__ == '__main__': |
| 112 | + main() |
| 113 | + try: |
| 114 | + K.clear_session() |
| 115 | + except AttributeError: |
| 116 | + pass |
0 commit comments