# 1. Data Preprocessing import hard from keras import backend as K from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D num_classes = 10 img_rows, img_cols = 28, 28 # By Keras MNIST encapsulated API loading data. Which is a trainX 60,000 * 28 * 28 array, # trainY is the number that corresponds to each picture. (trainX, trainY), (testX, testy) = mnist.load_data () # Set the format of the input layer according to the format requirements of the encoded image. IF K.image_data_format () == ' channels_first ' : trainX = trainX.reshape(trainX.shape[0], 1, img_rows, img_cols) testX = testX.reshape(testX.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: trainX = trainX.reshape(trainX.shape[0], img_rows, img_cols, 1) testX = testX.reshape(testX.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) trainX = trainX.astype('float32') testX = testX.astype('float32') trainX /= 255.0 testX /= 255.0 # The standard answer into a format (one-hot encoding) needs. = trainY keras.utils.to_categorical (trainY, num_classes) testY = keras.utils.to_categorical(testY, num_classes)
# 2. Keras API definitions winder neural network. # Use Keras API defined model. = Model the Sequential () model.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(500, activation='relu')) model.add(Dense(num_classes, activation='softmax')) # Define the loss function, function optimization and evaluation methods. model.compile (Loss = keras.losses.categorical_crossentropy, keras.optimizers.SGD Optimizer = (), metrics = [ ' Accuracy ' ])
# 3 by API Keras training model and calculating accuracy on the test data. model.fit (trainX, trainY, the batch_size = 128, 10 = epochs, validation_data = (testX, testy)) # Calculation accuracy on the test data. = Score model.evaluate (testX, testy) Print ( ' the Test Loss: ' , Score [0]) Print ( ' the Test Accuracy: ' , Score [. 1])