TensorFlow神经网络模型训练

fashion_MNIST数据集的模型识别训练

# 导入相应包
import os
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
plt.rcParams["font.sans-serif"] = "Microsoft YaHei"
plt.rcParams["axes.unicode_minus"] = False

fashion_mnist数据加载

#从 TensorFlow中导入和加载Fashion MNIST数据
fashion_mnist = keras.datasets.fashion_mnist.load_data()
(train_images, train_labels), (test_images, test_labels) = fashion_mnist

图片保存

为了后期测试,这里利用OpenCV保存原尺寸的照片(训练集中的10张图)

# 利用OpenCV保存图片
for img in range(10):
    cv.imwrite("{}.jpg".format(img), train_images[img])
# 获取当前工作路径查看
print("请复制路径自行查看:", os.getcwd())
  • 保存后的图片
    在这里插入图片描述

fashion_mnist可视化

设置中文名称便于对图像及类别标签的理解

  • 类别标签
标签类别名称中文名称
0T-shirt/topT恤
1Trouser裤子
2Pullover套衫
3Dress裙子
4Coat外套
5Sandal凉鞋
6Shirt汗衫
7Sneaker运动鞋
8Bag
9Ankle boot短靴
# 设置中文名称
names = ["0-T恤", "1-裤子", "2-套衫", "3-裙子", "4-外套", "5-凉鞋", "6-汗衫", "7-运动鞋", "8-包", "9-短靴"]
for i in range(10):
    plt.figure()
    plt.title(names[test_labels[i]], fontsize=12)
    plt.imshow(test_images[i])
    plt.colorbar()
plt.show()
  • 部分图如下
    短靴
    请添加图片描述

神经网络模型训练,预测

#训练模型
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)])
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
model.fit(train_images, train_labels, batch_size=90, epochs=10)

# 准确率评估
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

#进行预测
probability_model = tf.keras.Sequential([model,tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)

accuracy: 0.87841

模型保存

# 模型保存
model.save('fashion.h5')
# 模型调用
new_model = keras.models.load_model('./fashion.h5')
# 查看网络结构
new_model.summary()
  • 模型结构
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
flatten (Flatten)            (None, 784)               0         
_________________________________________________________________
dense (Dense)                (None, 128)               100480    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                1290      
=================================================================
Total params: 101,770
Trainable params: 101,770
Non-trainable params: 0
_________________________________________________________________

模型重新提取及进行预测

# 从10张图中随机抽取6张进行预测
indexs = list(np.random.choice(10, 6, replace=False))
# 进行预测
plt.figure(figsize=(10, 8))
for img in range(6):
    imgs = cv.imread("./{}.jpg".format(indexs[img]))
    img_grays = cv.cvtColor(imgs, cv.COLOR_RGB2GRAY)
    img_one = img_grays.reshape(1, 28, 28)/255.0
    new_predictions = new_model.predict(img_one)
    # 找出置信度最大的标签
    print(names[np.argmax(new_predictions[0])])
    # 查看预测图 
    image = plt.imread("./{}.jpg".format(indexs[img]))
    predicted_label = names[np.argmax(new_predictions[0])]
    plt.subplot(2,3,img+1)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(image)
    plt.xlabel(names[np.argmax(new_predictions[0])], fontsize=16, color= 'c')
plt.show()

识别结果

0-T恤
3-裙子
9-短靴
5-凉鞋
0-T恤
5-凉鞋

请添加图片描述


  1. 准确率需进行多次参数(批量数batch_size)调整及迭代次数(epochs)的选取 ↩︎

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

用户名乱码嫌咦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值