2 Save CNN network and one sample of train data. 4 Run one iteration of training of convnet on the MNIST dataset. 7 from __future__
import print_function
11 from keras.datasets
import mnist
12 from keras.models
import Sequential
13 from keras.layers.core
import Dense, Dropout, Activation, Flatten
14 from keras.layers.convolutional
import Convolution2D, MaxPooling2D
15 from keras.utils
import np_utils
22 img_rows, img_cols = 28, 28
31 (X_train, y_train), (X_test, y_test) = mnist.load_data()
33 X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
34 X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
35 X_train = X_train.astype(
'float32')
36 X_test = X_test.astype(
'float32')
39 print(
'X_train shape:', X_train.shape)
40 print(X_train.shape[0],
'train samples')
41 print(X_test.shape[0],
'test samples')
44 Y_train = np_utils.to_categorical(y_train, nb_classes)
45 Y_test = np_utils.to_categorical(y_test, nb_classes)
49 model.add(Convolution2D(nb_filters, nb_conv, nb_conv, border_mode=
'valid',
50 input_shape=(1, img_rows, img_cols)))
51 model.add(Activation(
'relu'))
52 model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
53 model.add(Activation(
'relu'))
54 model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
55 model.add(Dropout(0.25))
59 model.add(Activation(
'relu'))
60 model.add(Dropout(0.5))
61 model.add(Dense(nb_classes))
62 model.add(Activation(
'softmax'))
64 model.compile(loss=
'categorical_crossentropy',
67 model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
68 verbose=1, validation_data=(X_test, Y_test))
71 with
open(
'./my_nn_arch.json',
'w')
as fout:
72 fout.write(model.to_json())
73 model.save_weights(
'./my_nn_weights.h5', overwrite=
True)
76 with
open(
"./sample_mnist.dat",
"w")
as fin:
77 fin.write(
"1 28 28\n")
80 fin.write(
str(b)+
'\n')
84 print(
'Prediction on saved sample:')
85 print(
str(model.predict(X_train[:1])))
int open(const char *, int)
Opens a file descriptor.