[Keras实战1]手写数字识别

话不多说直接上代码

from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical

# 加载数据,预先下载。资源可以看我的资源文件里
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 查看数据集的统计数据
print(train_images.shape)
print(train_labels.shape)
# 调用模型
network = models.Sequential()
# 添加学习的层
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10, activation='softmax'))
# 添加优化器
network.compile(optimizer='rmsprop',  loss='categorical_crossentropy', metrics=['accuracy'])
# 基本的数据处理!这里必须会
train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype('float32')/255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# 模型拟合数据
network.fit(train_images, train_labels, epochs=5, batch_size=128)
# 用测试集去测试模型
test_loss, test_acc = network.evaluate(test_images, test_labels)
print(test_loss, test_acc)

成果:

编译器使用的是内嵌conda的pycharm
[Keras实战1]手写数字识别_第1张图片

你可能感兴趣的:([Keras实战1]手写数字识别)