1、导包

#导入TensorFlow和tf.keras
import tensorflow as tf
from tensorflow import keras # Helper libraries
import numpy as np
import matplotlib.pyplot as plt

2、导入Fashion MNIST数据集

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

3、指定名称

#每个图像都会被映射到一个标签。由于数据集不包括类名称,请将它们存储在下方,供稍后绘制图像时使用
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

4、预处理数据

#这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型
train_images = train_images / 255.0
test_images = test_images / 255.0

5、浏览数据(可选)

#显示训练集中有 60,000 个图像,每个图像由 28 x 28 的像素表示
print(train_images.shape)
#训练集中有 60,000 个标签
print(len(train_labels))
#每个标签都是一个 0 到 9 之间的整数
print(train_labels)
#测试集中有 10,000 个图像。同样,每个图像都由 28x28 个像素表示
print(test_images.shape)
#测试集包含 10,000 个图像标签
print(len(test_labels))
(60000, 28, 28)
60000
[9 0 0 ... 3 0 5]
(10000, 28, 28)
10000

6、检测图像(可选)

#检查训练集中的第一个图像,您会看到像素值处于 0 到 255 之间
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

#验证数据的格式是否正确,以及是否已准备好构建和训练网络,显示训练集中的前 25 个图像,并在每个图像下方显示类名称
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()

7、构建模型

#该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。

展平像素后,网络会包括两个 tf.keras.layers.Dense 层的序列。它们是密集连接或全连接神经层。第一个 Dense 层有 128 个节点(或神经元)。第二个(也是最后一个)层会返回一个长度为 10 的 logits 数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])

8、编译模型

#损失函数 - 用于测量模型在训练期间的准确率。您会希望最小化此函数,以便将模型“引导”到正确的方向上。
#优化器 - 决定模型如何根据其看到的数据和自身的损失函数进行更新。
#指标 - 用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])

9、训练模型

训练神经网络模型需要执行以下步骤:

  1. 将训练数据馈送给模型。在本例中,训练数据位于 train_images 和 train_labels 数组中。
  2. 模型学习将图像和标签关联起来。
  3. 要求模型对测试集(在本例中为 test_images 数组)进行预测。
  4. 验证预测是否与 test_labels 数组中的标签相匹配。

向模型馈送数据

#调用 model.fit 方法,这样命名是因为该方法会将模型与训练数据进行“拟合”
model.fit(train_images, train_labels, epochs=10)
Epoch 1/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.4970 - accuracy: 0.8263
Epoch 2/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.3764 - accuracy: 0.8646
Epoch 3/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.3386 - accuracy: 0.8768
Epoch 4/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.3131 - accuracy: 0.8852
Epoch 5/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2979 - accuracy: 0.8905
Epoch 6/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2817 - accuracy: 0.8946
Epoch 7/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2701 - accuracy: 0.8997
Epoch 8/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2584 - accuracy: 0.9039
Epoch 9/10
1875/1875 [==============================] - 3s 1ms/step - loss: 0.2494 - accuracy: 0.9071
Epoch 10/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2416 - accuracy: 0.9094

评估准确率

#比较模型在测试集上的表现
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\nTest accuracy:', test_acc)
Test accuracy: 0.8792999982833862

10、进行预测

#进行预测
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
#测试第一个预测结果
print(predictions[0])
#找出置信度最大的标签
print(np.argmax(predictions[0]))
#检查测试标签
print(test_labels[0])

[1.4007558e-08 6.0697776e-09 6.0778667e-08 3.8483901e-08 1.5276806e-08
2.0785581e-03 2.9759491e-07 5.4935408e-03 5.0426343e-07 9.9242699e-01]
9
9

11、绘制图表

def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color) def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')

12、验证预测结果

#对图像进行检测
#看看第 0 个图像、预测结果和预测数组。正确的预测标签为蓝色,错误的预测标签为红色。数字表示预测标签的百分比(总计为 100)。
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
#看第12个图像
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
#用模型预测绘制几张图像
# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

13、使用训练的模型

使用训练好的模型对单张图片进行预测

#使用训练好的模型对单个图像进行预测
# Grab an image from the test dataset.
img = test_images[1]
print(img.shape)
(28, 28)
#将其添加到列表中
# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0)) print(img.shape)
(1, 28, 28)
#预测这个图像的正确标签
predictions_single = probability_model.predict(img) print(predictions_single)
[[1.0675135e-05 2.4023437e-12 9.9772269e-01 1.3299730e-09 1.2968916e-03
8.7469149e-14 9.6970733e-04 5.4669354e-19 2.4514609e-11 1.8405429e-12]]
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)

#在批次中获取对我们(唯一)图像的预测
print(np.argmax(predictions_single[0]))
2

14、源代码

# -*- coding = utf-8 -*-
# @Time : 2021/3/16
# @Author : pistachio
# @File : imagesort1.py
# @Software : PyCharm #导入TensorFlow和tf.keras
import tensorflow as tf
from tensorflow import keras # Helper libraries
import numpy as np
import matplotlib.pyplot as plt #从 TensorFlow中导入和加载Fashion MNIST数据
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() #每个图像都会被映射到一个标签。由于数据集不包括类名称,请将它们存储在下方,供稍后绘制图像时使用
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] #这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型
train_images = train_images / 255.0
test_images = test_images / 255.0 #浏览数据
print(train_images.shape)
print(len(train_labels))
print(train_labels)
print(test_images.shape)
print(len(test_labels)) plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
#为了验证数据的格式是否正确,以及您是否已准备好构建和训练网络,让我们显示训练集中的前 25 个图像,并在每个图像下方显示类名称
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
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, epochs=10) test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\nTest accuracy:', test_acc) #进行预测
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
#测试第一个预测结果
print(predictions[0])
#找出置信度最大的标签
print(np.argmax(predictions[0]))
#检查测试标签
print(test_labels[0]) #将其绘制成图表,看看模型对于全部 10 个类的预测
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color) def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue') #对图像进行检测
#看看第 0 个图像、预测结果和预测数组。正确的预测标签为蓝色,错误的预测标签为红色。数字表示预测标签的百分比(总计为 100)。
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
#看第12个图像
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
#用模型预测绘制几张图像
# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show() #使用训练好的模型对单个图像进行预测
# Grab an image from the test dataset.
img = test_images[1]
print(img.shape) #将其添加到列表中
# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))
print(img.shape) #预测这个图像的正确标签
predictions_single = probability_model.predict(img) print(predictions_single) plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
plt.show()
print(np.argmax(predictions_single[0]))

基于TensorFlow的服装分类的更多相关文章

  1. 基于tensorflow的文本分类总结(数据集是复旦中文语料)

    代码已上传到github:https://github.com/taishan1994/tensorflow-text-classification 往期精彩: 利用TfidfVectorizer进行 ...

  2. 基于tensorflow的逻辑分类

    #!/usr/local/bin/python3 ##ljj [2] ##logic classify model import tensorflow as tf import matplotlib. ...

  3. 使用Python基于TensorFlow的CIFAR-10分类训练

    TensorFlow Models GitHub:https://github.com/tensorflow/models Document:https://github.com/jikexueyua ...

  4. Chinese-Text-Classification,用卷积神经网络基于 Tensorflow 实现的中文文本分类。

    用卷积神经网络基于 Tensorflow 实现的中文文本分类 项目地址: https://github.com/fendouai/Chinese-Text-Classification 欢迎提问:ht ...

  5. tensorflow实现基于LSTM的文本分类方法

    tensorflow实现基于LSTM的文本分类方法 作者:u010223750 引言 学习一段时间的tensor flow之后,想找个项目试试手,然后想起了之前在看Theano教程中的一个文本分类的实 ...

  6. 一文详解如何用 TensorFlow 实现基于 LSTM 的文本分类(附源码)

    雷锋网按:本文作者陆池,原文载于作者个人博客,雷锋网已获授权. 引言 学习一段时间的tensor flow之后,想找个项目试试手,然后想起了之前在看Theano教程中的一个文本分类的实例,这个星期就用 ...

  7. 基于 TensorFlow 在手机端实现文档检测

    作者:冯牮 前言 本文不是神经网络或机器学习的入门教学,而是通过一个真实的产品案例,展示了在手机客户端上运行一个神经网络的关键技术点 在卷积神经网络适用的领域里,已经出现了一些很经典的图像分类网络,比 ...

  8. 基于tensorflow的MNIST手写数字识别(二)--入门篇

    http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...

  9. 【小白学PyTorch】15 TF2实现一个简单的服装分类任务

    [新闻]:机器学习炼丹术的粉丝的人工智能交流群已经建立,目前有目标检测.医学图像.时间序列等多个目标为技术学习的分群和水群唠嗑的总群,欢迎大家加炼丹兄为好友,加入炼丹协会.微信:cyx64501661 ...

随机推荐

  1. postman Variables变量的详解与应用

    变量 变量类型(按照作用域划分) 全局变量(全局环境里面的变量) 集合变量(请求集合里声明的变量) 自定义环境变量 数据变量(在runner时文件变量) 本地变量 变量权重类型 全局变量 < 集 ...

  2. 痞子衡嵌入式:在i.MXRT启动头FDCB里使能串行NOR Flash的Continuous read模式

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是在FDCB里使能串行NOR Flash的Continuous read模式. 前面关于串行Flash传输时序的文章 <Fast R ...

  3. 交叉编译参数--build、host和target的区别

    build.host和target 在交叉编译中比较 常见 的一些参数就是build.host和target了,正确的理解这三者的含义对于交叉编译是非常重要的,下面就此进行解释 --build=编译该 ...

  4. 封装axios在util中

    创建util工具类,封装通用的get和post请求 封装axios成工具类,方便大家请求调用 1.创建util文件夹 2.创建request.js 3.封装 //封装请求相关方法 //初始化一个axi ...

  5. [C] gcc

    概述 GNU C Compiler 流程 预处理,生成.i文件(中间文件,看不到) 编译,生成.s文件(中间文件,看不到) 汇编,生成.o文件 链接,生成可执行文件 参数 -E:预处理 -S:预处理, ...

  6. BRAM 和 DRAM 区别

    转载: BRAM和DRAM的区别 Xilinx的FPGA开发板可以直接调用RAM,其中包括了BRAM和DRAM.经过网上查找资料发现,这两者的区别在于: 选择distributed memory ge ...

  7. Redis SWAPDB 命令背后做了什么

    Redis SWAPDB 命令背后做了什么 目录 Redis SWAPDB 命令背后做了什么 0x00 摘要 0x01 SWAPDB 基础 1.1 命令说明 1.2 演示 0x02 预先校验 0x03 ...

  8. CF1513F Swapping Problem(模型转化)

    题目描述 You are given 2 arrays a a a and b b b , both of size n n n . You can swap two elements in b b ...

  9. 高可用 | Xenon:后 MHA 时代的选择

    原创:知数堂 | MySQL 高可用的选择 在 MySQL(5.5 及以下)传统复制的时代,MHA(Master High Availability)在 MySQL 高可用应用中非常成熟.在 MySQ ...

  10. GO学习-(3) VS Code配置Go语言开发环境

    VS Code配置Go语言开发环境 VS Code配置Go语言开发环境 说在前面的话,Go语言是采用UTF8编码的,理论上使用任何文本编辑器都能做Go语言开发.大家可以根据自己的喜好自行选择.编辑器/ ...