1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import keras import numpy as np from keras.layers import Dense,Dropout,Convolution2D,MaxPool2D,Flatten from keras.models import Sequential from keras.optimizers import Adam from keras.utils import np_utils from keras.utils.vis_utils import plot_model from keras.datasets import mnist import matplotlib.pyplot as plt
(x_train,y_train),(x_test,y_test) = mnist.load_data() x_train = x_train.reshape(-1,28,28,1)/255.0 x_test = x_test.reshape(-1,28,28,1)/255.0
y_train = np_utils.to_categorical(y_train,num_classes=10) y_test = np_utils.to_categorical(y_test,num_classes=10)
model = Sequential() model.add(Convolution2D( input_shape = (28,28,1), filters = 32, kernel_size = 5, strides = 1, padding = 'same', activation = 'relu', name = 'conv1' ))
model.add(MaxPool2D( pool_size = 2, strides = 2, padding = 'same', name = 'pool1' ))
model.add(Convolution2D( 64,5,strides=1,padding='same',activation='relu',name='conv2' ))
model.add(MaxPool2D(2,2,'same',name='pool2'))
model.add(Flatten())
model.add(Dense(1024,activation='relu')) model.add(Dropout(0.3))
model.add(Dense(10,activation='softmax'))
adam = Adam(lr=1e-4)
model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy']) model.fit(x_train,y_train,batch_size=64,epochs=1)
loss,accuracy = model.evaluate(x_train,y_train) print('x_train loss:%f / x_train accuracy: %f'%(loss,accuracy))
loss,accuracy = model.evaluate(x_test,y_test) print('x_test loss:%f / y_test accuracy: %f'%(loss,accuracy))
|