搭建一个简单的卷积神经网络实现MNIST分类

# coding: utf-8
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
from datasets.mnist import load_mnist


# ------------------------实例化一个小型的卷积网络---------------------------
model = models.Sequential()

model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPool2D(2, 2))

model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPool2D(2, 2))

model.add(layers.Conv2D(64, (3, 3), activation='relu'))

# -------------------------添加分类器---------------------------------------
"""分类器处理1D张量,而前面的输出为3D张量,要先铺开"""
model.add(layers.Flatten()) # 将3D张量铺开为1D张量
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

# ---------------------------model的架构输出-----------------------------------
model.summary() # 神经网络的架构 summary(概述)

在这里插入图片描述

# -----------------------------在mnist上训练CNN----------------------------------------
"""加载数据集"""
(train_images, train_labels), (test_images, test_labels) = load_mnist(normalize=False, one_hot_label=False, flatten=False)

"""数据预处理"""
train_images = train_images.reshape(60000, 28, 28, 1) # 变形为神经网络的输入格式
train_images = train_images.astype('float32') / 255 # 标准化,[0, 1]之间

test_images = test_images.reshape(10000, 28, 28, 1)
test_images = test_images.astype('float32') / 255

train_labels = to_categorical(train_labels) # 标签one-hot化
test_labels = to_categorical(test_labels) # 标签one-hot化

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

"""简单的留出验证集"""
x_val = train_images[:10000] # 时间问题仅仅选择1000个样本,主要是学习思路和代码编写
partial_x_train = train_images[10000:]

t_val = train_labels[:10000]
partial_t_train = train_labels[10000:]

"""训练模型"""
history = model.fit(partial_x_train, partial_t_train, epochs=5, batch_size=64, validation_data=(x_val, t_val))
# --------------------------------绘制精度和损失图-------------------------
import matplotlib.pyplot as plt


# --------------------------------损失图----------------------------------
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(1, 5 + 1) # 横坐标

plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.title('Training and Validation loss')
plt.legend()
plt.show()

# ---------------------------精度图----------------------------------------
acc = history.history['acc']
val_acc = history.history['val_acc']

epochs = range(1, 5 + 1) # 横坐标

plt.plot(epochs, acc, 'ro', label='Training accuracy')
plt.plot(epochs, val_acc, 'r', label='Validation accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.title('Training and Validation accuracy')
plt.legend()
plt.show()
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值