MNIST图像分类 - Keras

1. 序贯模型的网络拓扑

实例中的小模型,由输入层、卷积层、池化层、扁平层和稠密层,以及输出层等网络层构成。
在这里插入图片描述

2. 代码实现

图像分类的网络拓扑相对简单,准备数据集、构建序贯模型、编译模型、训练模型,并且评估模型。

# encoding=utf-8 **

import keras
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input, Reshape, Dense, Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.datasets import mnist

# 设置参数
num_classes = 10
batch_size = 32
epochs = 30

# 图像维度
img_rows, img_cols = 28, 28

# 加载数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
y_train = keras.utils.to_categorical(y_train, num_classes=num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes=num_classes)

# 设置输入数据维度
input_shape = (img_rows, img_cols)
inputs = Input(input_shape)
print(input_shape + (1, ))

# 构建网络模型
x = Reshape(input_shape + (1, ), input_shape=input_shape)(inputs)
conv1 = Conv2D(14, kernel_size=3, activation='relu')(x)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(7, kernel_size=3, activation='relu')(pool1)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
flatten = Flatten()(pool2)
output = Dense(10, activation='sigmoid')(flatten)
model = Model(inputs=inputs, outputs=output)

# 输出网络图
print(model.summary())

# 绘制网络图
plot_model(model, to_file='convolutional_neural_network.png', show_shapes=True, show_layer_names=True)

# 优化函数
opt = keras.optimizers.RMSprop(lr=1e-4, decay=1e-6)

# 编译模型
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

# 训练模型
history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,validation_data=(x_test, y_test), shuffle=True)

# 评估模型
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])

# 绘制准确率曲线
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

# 绘制损失率曲线
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

3. 训练结果

评估一个模型的好坏,可以从精确率、召回率、损失率等方面评价。

Test loss: 0.06894081085920334
Test accuracy: 0.9801999926567078

准确率在这里插入图片描述

损失率在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南风无良

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值