一个神经网络示例
-
加载 Keras 中的 MNIST 数据集 from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
-
网络架构 from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))
-
编译步骤
编译步骤的三个参数
network.complice(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
-
准备图像数据
将数据进行预处理,将其变换为网络要求的形状,并缩放放到所有值都在 [0, 1] 区间。
train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((1000,28*28))
test_images = test_images.astype('float32') / 255
-
准备标签 from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
现在可以准备开始训练网络,在 Keras 中这一步通过调用网络的 fit 方法来完成的——在训练数据上拟合(fit)模型 >>>network.fit(train_image, train_labels, epochs=5, batch_size=128)
Epoch 1/5
60000/60000 [==========================] - 9s - loss:0.2524 - acc: 0.9273
Epoch 2/5
51328/60000 [======================>...] - ETA: 1s - loss: 0.1035 - acc: 0.9692
训练过程中显示了两个数字:
- 网络在训练数据上的损失(loss)
- 网络在训练数据上的精度(acc)
>>> test_loss, test_acc = network.evaluate(test_images, test_labels)
>>> print('test_acc:', test_acc)
test_acc: 0.9785
|