模型训练好后,就可以使用测试数据评估模型的性能。
score = model.evaluate(X_test, Y_test, verbose=0)
到此为止,我们已经完成了一个完整的Keras应用。进一步了解Keras,可参考更多Keras例子。
完整代码
下面是本教程的完整代码:
# Keras 导入库与模块
import numpy as np
np.random.seed(123) # 种子相同,随机数产生可以重现
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
from keras import backend as K
# 将预打乱的MNIST数据加载到培训和测试集中
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 预处理输入数据
if K.image_data_format() == 'channels_first':
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
input_shape = (1, 28, 28)
else:
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
# 预处理类标签
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)
# 定义模型架构
model = Sequential()
model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=input_shape))
model.add(Convolution2D(32, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# 根据训练数据拟合模型
model.fit(X_train, Y_train,
batch_size=32, nb_epoch=10, verbose=1)
# 根据测试数据评估模型
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
运行输出:
...
60000/60000 [==============================] - 148s 2ms/step - loss: 0.2055 - acc: 0.9372
Epoch 2/10
60000/60000 [==============================] - 131s 2ms/step - loss: 0.0857 - acc: 0.9746
Epoch 3/10
60000/60000 [==============================] - 128s 2ms/step - loss: 0.0661 - acc: 0.9802
Epoch 4/10
60000/60000 [==============================] - 120s 2ms/step - loss: 0.0551 - acc: 0.9831
Epoch 5/10
60000/60000 [==============================] - 124s 2ms/step - loss: 0.0469 - acc: 0.9856
Epoch 6/10
60000/60000 [==============================] - 134s 2ms/step - loss: 0.0411 - acc: 0.9875
Epoch 7/10
60000/60000 [==============================] - 120s 2ms/step - loss: 0.0350 - acc: 0.9890
Epoch 8/10
60000/60000 [==============================] - 117s 2ms/step - loss: 0.0321 - acc: 0.9898
Epoch 9/10
60000/60000 [==============================] - 123s 2ms/step - loss: 0.0317 - acc: 0.9898
Epoch 10/10
60000/60000 [==============================] - 122s 2ms/step - loss: 0.0281 - acc: 0.9913
Test loss: 0.024244179409698335
Test accuracy: 0.9925