搭建全连接网络训练mnist数据集

1. 导入相关的包

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, losses, datasets, Sequential
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, GlobalMaxPool2D
from tensorflow.keras.optimizers import RMSprop
import matplotlib.pyplot as plt
import numpy as np

2. 载入数据集

# 将数据集载入,x_train为训练集数据,y_train为训练集标签,x_test为测试集数据,y_test为测试集标签
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 打印查看数据
print('x_train.shape:' + str(x_train.shape))
print('y_train.shape:' + str(y_train.shape))
print('x_test.shape:' + str(x_test.shape))
print('y_test.shape:' + str(y_test.shape))

3. 搭建4层全连接神经网络,除输入层以外,各层神经元个数分别为1000,300,64,10,激活函数自选

# 将数据集进行转换为一维,数值归到0-1之间
x_train = x_train.reshape(60000, 784).astype('float32') /255
x_test = x_test.reshape(10000, 784).astype('float32') /255
# 模型建立
inputs = tf.keras.Input(shape=(784,), name='img')
# 搭建4层全连接神经网络
h1 = layers.Dense(1000, activation='relu')(inputs)
h2 = layers.Dense(300, activation='relu')(h1)
h3 = layers.Dense(64, activation='relu')(h2)
outputs = layers.Dense(10, activation='softmax')(h3)
model = tf.keras.Model(inputs=inputs, outputs=outputs, name='mnist_model')

model.summary()
keras.utils.plot_model(model, 'mnist_model.png')
keras.utils.plot_model(model, 'model_info.png', show_shapes=True)

在这里插入图片描述

4. 模型训练

# 模型训练
model.compile(optimizer=keras.optimizers.RMSprop(),
             loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

history = model.fit(x_train, y_train, batch_size=64, epochs=10, validation_split=0.2)

在这里插入图片描述

5. 模型测试

# 模型测试
test_scores = model.evaluate(x_test, y_test, verbose=1)
print('test loss:', test_scores[0])
print('test accuracy:', test_scores[1]) # 识别准确率
keras.utils.plot_model(model, 'model_info.png', show_shapes=True)

在这里插入图片描述

6. 训练过程可视化

# 绘制全连接神经网络训练过程中训练集和测试集合的准确率值
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
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()

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Vicky__3021

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

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

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

打赏作者

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

抵扣说明:

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

余额充值