MNIST 数据集的 Keras 序列模型示例
以下是构建简单多层感知机(在第 5 章中详细介绍)的一个小例子,用于对 MNIST 集中的手写数字进行分类:
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import SGD
from keras import utils
import numpy as np
# define some hyper parameters
batch_size = 100
n_inputs = 784
n_classes = 10
n_epochs = 10
# get the data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# reshape the two dimensional 28 x 28 pixels
# sized images into a single vector of 784 pixels
x_train = x_train.reshape(60000, n_inputs)
x_test = x_test.reshape(10000, n_inputs)
# convert the input values to float32
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)
# normalize the values of image vectors to fit under 1
x_train /= 255
x_test /= 255
# convert output data into one hot encoded format
y_train = utils.to_categorical(y_train, n_classes)
y_test = utils.to_categorical(y_test, n_classes)
# build a sequential model
model = Sequential()
# the first layer has to specify the dimensions of the input vector
model.add(Dense(units=128, activation='sigmoid', input_shape=(n_inputs,)))
# add dropout layer for preventing overfitting
model.add(Dropout(0.1))
model.add(Dense(units=128, activation='sigmoid'))
model.add(Dropout(0.1))
# output layer can only have the neurons equal to the number of outputs
model.add(Dense(units=n_classes, activation='softmax'))
# print the summary of our model
model.summary()
# compile the model
model.compile(loss='categorical_crossentropy',
optimizer=SGD(),
metrics=['accuracy'])
# train the model
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=n_epochs)
# evaluate the model and print the accuracy score
scores = model.evaluate(x_test, y_test)
print('\n loss:', scores[0])
print('\n accuracy:', scores[1])
我们从描述和训练 Keras 模型得到以下输出:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_7 (Dense) (None, 128) 100480
_________________________________________________________________
dropout_5 (Dropout) (None, 128) 0
_________________________________________________________________
dense_8 (Dense) (None, 128) 16512
_________________________________________________________________
dropout_6 (Dropout) (None, 128) 0
_________________________________________________________________
dense_9 (Dense) (None, 10) 1290
=================================================================
Total params: 118,282
Trainable params: 118,282
Non-trainable params: 0
_________________________________________________________________
Epoch 1/10
60000/60000 [========================] - 3s - loss: 2.3018 - acc: 0.1312
Epoch 2/10
60000/60000 [========================] - 2s - loss: 2.2395 - acc: 0.1920
Epoch 3/10
60000/60000 [========================] - 2s - loss: 2.1539 - acc: 0.2843
Epoch 4/10
60000/60000 [========================] - 2s - loss: 2.0214 - acc: 0.3856
Epoch 5/10
60000/60000 [========================] - 3s - loss: 1.8269 - acc: 0.4739
Epoch 6/10
60000/60000 [========================] - 2s - loss: 1.5973 - acc: 0.5426
Epoch 7/10
60000/60000 [========================] - 2s - loss: 1.3846 - acc: 0.6028
Epoch 8/10
60000/60000 [========================] - 3s - loss: 1.2133 - acc: 0.6502
Epoch 9/10
60000/60000 [========================] - 3s - loss: 1.0821 - acc: 0.6842
Epoch 10/10
60000/60000 [========================] - 3s - loss: 0.9799 - acc: 0.7157
loss: 0.859834249687
accuracy: 0.788
您可以看到,在 Keras 中构建和训练模型是多么容易。
您可以从他们记录完备的网站 https://keras.io 获取有关 Keras 的更多信息。