1、导包

  1. #导入TensorFlow和tf.keras
  2. import tensorflow as tf
  3. from tensorflow import keras
  4.  
  5. # Helper libraries
  6. import numpy as np
  7. import matplotlib.pyplot as plt

2、导入Fashion MNIST数据集

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

3、指定名称

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

4、预处理数据

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

5、浏览数据(可选)

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

6、检测图像(可选)

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

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

7、构建模型

  1. #该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。
  2.  
  3. 展平像素后,网络会包括两个 tf.keras.layers.Dense 层的序列。它们是密集连接或全连接神经层。第一个 Dense 层有 128 个节点(或神经元)。第二个(也是最后一个)层会返回一个长度为 10 logits 数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。
  4. model = keras.Sequential([
  5. keras.layers.Flatten(input_shape=(28, 28)),
  6. keras.layers.Dense(128, activation='relu'),
  7. keras.layers.Dense(10)
  8. ])

8、编译模型

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

9、训练模型

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

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

向模型馈送数据

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

评估准确率

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

10、进行预测

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

[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、绘制图表

  1. def plot_image(i, predictions_array, true_label, img):
  2. predictions_array, true_label, img = predictions_array, true_label[i], img[i]
  3. plt.grid(False)
  4. plt.xticks([])
  5. plt.yticks([])
  6.  
  7. plt.imshow(img, cmap=plt.cm.binary)
  8.  
  9. predicted_label = np.argmax(predictions_array)
  10. if predicted_label == true_label:
  11. color = 'blue'
  12. else:
  13. color = 'red'
  14.  
  15. plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
  16. 100*np.max(predictions_array),
  17. class_names[true_label]),
  18. color=color)
  19.  
  20. def plot_value_array(i, predictions_array, true_label):
  21. predictions_array, true_label = predictions_array, true_label[i]
  22. plt.grid(False)
  23. plt.xticks(range(10))
  24. plt.yticks([])
  25. thisplot = plt.bar(range(10), predictions_array, color="#777777")
  26. plt.ylim([0, 1])
  27. predicted_label = np.argmax(predictions_array)
  28.  
  29. thisplot[predicted_label].set_color('red')
  30. thisplot[true_label].set_color('blue')

12、验证预测结果

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

13、使用训练的模型

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

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

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

14、源代码

  1. # -*- coding = utf-8 -*-
  2. # @Time : 2021/3/16
  3. # @Author : pistachio
  4. # @File : imagesort1.py
  5. # @Software : PyCharm
  6.  
  7. #导入TensorFlow和tf.keras
  8. import tensorflow as tf
  9. from tensorflow import keras
  10.  
  11. # Helper libraries
  12. import numpy as np
  13. import matplotlib.pyplot as plt
  14.  
  15. #从 TensorFlow中导入和加载Fashion MNIST数据
  16. fashion_mnist = keras.datasets.fashion_mnist
  17. (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
  18.  
  19. #每个图像都会被映射到一个标签。由于数据集不包括类名称,请将它们存储在下方,供稍后绘制图像时使用
  20. class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
  21. 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
  22.  
  23. #这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型
  24. train_images = train_images / 255.0
  25. test_images = test_images / 255.0
  26.  
  27. #浏览数据
  28. print(train_images.shape)
  29. print(len(train_labels))
  30. print(train_labels)
  31. print(test_images.shape)
  32. print(len(test_labels))
  33.  
  34. plt.figure()
  35. plt.imshow(train_images[0])
  36. plt.colorbar()
  37. plt.grid(False)
  38. plt.show()
  39. #为了验证数据的格式是否正确,以及您是否已准备好构建和训练网络,让我们显示训练集中的前 25 个图像,并在每个图像下方显示类名称
  40. plt.figure(figsize=(10, 10))
  41. for i in range(25):
  42. plt.subplot(5, 5, i+1)
  43. plt.xticks([])
  44. plt.yticks([])
  45. plt.grid(False)
  46. plt.imshow(train_images[i], cmap=plt.cm.binary)
  47. plt.xlabel(class_names[train_labels[i]])
  48. plt.show()
  49.  
  50. #训练模型
  51. model = keras.Sequential([
  52. keras.layers.Flatten(input_shape=(28, 28)),
  53. keras.layers.Dense(128, activation='relu'),
  54. keras.layers.Dense(10)
  55. ])
  56.  
  57. model.compile(optimizer='adam',
  58. loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
  59. metrics=['accuracy'])
  60.  
  61. model.fit(train_images, train_labels, epochs=10)
  62.  
  63. test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
  64.  
  65. print('\nTest accuracy:', test_acc)
  66.  
  67. #进行预测
  68. probability_model = tf.keras.Sequential([model,
  69. tf.keras.layers.Softmax()])
  70. predictions = probability_model.predict(test_images)
  71. #测试第一个预测结果
  72. print(predictions[0])
  73. #找出置信度最大的标签
  74. print(np.argmax(predictions[0]))
  75. #检查测试标签
  76. print(test_labels[0])
  77.  
  78. #将其绘制成图表,看看模型对于全部 10 个类的预测
  79. def plot_image(i, predictions_array, true_label, img):
  80. predictions_array, true_label, img = predictions_array, true_label[i], img[i]
  81. plt.grid(False)
  82. plt.xticks([])
  83. plt.yticks([])
  84.  
  85. plt.imshow(img, cmap=plt.cm.binary)
  86.  
  87. predicted_label = np.argmax(predictions_array)
  88. if predicted_label == true_label:
  89. color = 'blue'
  90. else:
  91. color = 'red'
  92.  
  93. plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
  94. 100*np.max(predictions_array),
  95. class_names[true_label]),
  96. color=color)
  97.  
  98. def plot_value_array(i, predictions_array, true_label):
  99. predictions_array, true_label = predictions_array, true_label[i]
  100. plt.grid(False)
  101. plt.xticks(range(10))
  102. plt.yticks([])
  103. thisplot = plt.bar(range(10), predictions_array, color="#777777")
  104. plt.ylim([0, 1])
  105. predicted_label = np.argmax(predictions_array)
  106.  
  107. thisplot[predicted_label].set_color('red')
  108. thisplot[true_label].set_color('blue')
  109.  
  110. #对图像进行检测
  111. #看看第 0 个图像、预测结果和预测数组。正确的预测标签为蓝色,错误的预测标签为红色。数字表示预测标签的百分比(总计为 100)。
  112. i = 0
  113. plt.figure(figsize=(6,3))
  114. plt.subplot(1,2,1)
  115. plot_image(i, predictions[i], test_labels, test_images)
  116. plt.subplot(1,2,2)
  117. plot_value_array(i, predictions[i], test_labels)
  118. plt.show()
  119. #看第12个图像
  120. i = 12
  121. plt.figure(figsize=(6,3))
  122. plt.subplot(1,2,1)
  123. plot_image(i, predictions[i], test_labels, test_images)
  124. plt.subplot(1,2,2)
  125. plot_value_array(i, predictions[i], test_labels)
  126. plt.show()
  127. #用模型预测绘制几张图像
  128. # Plot the first X test images, their predicted labels, and the true labels.
  129. # Color correct predictions in blue and incorrect predictions in red.
  130. num_rows = 5
  131. num_cols = 3
  132. num_images = num_rows*num_cols
  133. plt.figure(figsize=(2*2*num_cols, 2*num_rows))
  134. for i in range(num_images):
  135. plt.subplot(num_rows, 2*num_cols, 2*i+1)
  136. plot_image(i, predictions[i], test_labels, test_images)
  137. plt.subplot(num_rows, 2*num_cols, 2*i+2)
  138. plot_value_array(i, predictions[i], test_labels)
  139. plt.tight_layout()
  140. plt.show()
  141.  
  142. #使用训练好的模型对单个图像进行预测
  143. # Grab an image from the test dataset.
  144. img = test_images[1]
  145. print(img.shape)
  146.  
  147. #将其添加到列表中
  148. # Add the image to a batch where it's the only member.
  149. img = (np.expand_dims(img,0))
  150. print(img.shape)
  151.  
  152. #预测这个图像的正确标签
  153. predictions_single = probability_model.predict(img)
  154.  
  155. print(predictions_single)
  156.  
  157. plot_value_array(1, predictions_single[0], test_labels)
  158. _ = plt.xticks(range(10), class_names, rotation=45)
  159. plt.show()
  160. 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. Arduino+DS18b20+OLED Display

    DS18b20获取到温度数值保存到变量中,然后和天气图标还有滚动字幕一起发送到OLED 屏幕上显示 需要用到的库均可在Arduino库管理器下载. 电路图: 图中屏幕接线已在代码中写出,温度传感器da ...

  2. layui中的多图上传

    效果展示: 1.html部分: 注:<input> 作为隐藏域,用于保存多图上传的资源数组,方便后期进行 form 表单的提交 <input type="hidden&qu ...

  3. 【springMVC】<mvc:annotation-driven />标签的使用、作用?

    不牵扯源码的显式的作用 在使用interceptor时,显式的作用. 这是不配置<mvc:annotation-driven/>标签时的public boolean preHandle(H ...

  4. [源码解析] 并行分布式任务队列 Celery 之 EventDispatcher & Event 组件

    [源码解析] 并行分布式任务队列 Celery 之 EventDispatcher & Event 组件 目录 [源码解析] 并行分布式任务队列 Celery 之 EventDispatche ...

  5. ConcurrentHashMap源码解读三

    今天首先讲解helpTransfer方法 final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) ...

  6. VS中光标变成方块状,输入时会把光标覆盖的部分替换掉的解决方法

    按下键盘上的Insert键,切换为插入模式.

  7. MySQL字段默认值设置详解

    前言: 在 MySQL 中,我们可以为表字段设置默认值,在表中插入一条新记录时,如果没有为某个字段赋值,系统就会自动为这个字段插入默认值.关于默认值,有些知识还是需要了解的,本篇文章我们一起来学习下字 ...

  8. 33.2.NIO

    4.1概述[理解] BIO Blocking IO,阻塞型IO NIO No Blocking IO,非阻塞型IO 阻塞IO的弊端 在等待的过程中,什么事也做不了 非阻塞IO的好处 不需要一直等待,当 ...

  9. 把el-element的日期格式改为CRON

    在日常的开发当中,经常会遇到格式的不匹配造成的困扰. 在日期管理上,el-element也是贴心的准备了相关的日期选择器,但是在取值的时候发现,el-element所给出的值格式可能并不是我们常用的. ...

  10. traefik ingress Controller使用

    Kubernetes Ingress Kubernetes Ingress是路由规则的集合,这些规则控制外部用户如何访问Kubernetes集群中运行的服务. 在Kubernetes中,有三种方式可以 ...