TensorFlow + Keras 入门项目:Classifying Images of Clothing(基于Fashion-MNIST数据集)

本文主要是介绍TensorFlow + Keras 入门项目:Classifying Images of Clothing(基于Fashion-MNIST数据集),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

OS:Win10

Interpreter: Python3.7

Environment: Anaconda3 + Tensorflow-gpu2.0.0 + Spyder

 

Fashion-MNIST 数据集简介:

https://github.com/zalandoresearch/fashion-mnist

'Fashion-MNIST is a dataset of Zalando's article images consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes.'

其实就是模仿MNIST数据集(手写数字识别)做的一个简单的衣物(clothing)数据集,有10种类别共70000张带标签的灰度图(28*28),灰度值为[0,255],标签是一个整数数组,值为[0,9],对应关系如下:

 

Classifying Images of Clothing 项目简介:

我们要设计和训练一个神经网络,使它在未知的测试集上能达到一个较好的识别准确率。取60000张图片作为Training Data(85.7%),剩余10000张作为Test Data(14.3%)。输入是28*28的灰度图,是10*1的向量,对应10个输出神经元,每个神经元的输出值(activation value)是属于某一类的概率(Probability of each class)。

 

 

神经网络架构:

输入层:tf.keras.layers.Flatten( input_shape=(28, 28, 1) )   这一层把2D矩阵(28,28)转为1D向量(784,1)

中间层:tf.keras.layers.Dense( 128,activation=tf.nn.relu )  采用Relu(线性神经单元),密集全连接层

 

代码实现:

1.安装和加载依赖项

在命令行里输入,pip会自动下载安装依赖项

pip install -U tensorflow_datasets

导入相关模块:

# Never mind this statement, for compatibility reasons
from __future__ import absolute_import, division, print_function, unicode_literals# Import TensorFlow and TensorFlow Datasets
import tensorflow as tf
import tensorflow_datasets as tfds
tfds.disable_progress_bar()# Helper libraries
import math
import numpy as np
import matplotlib.pyplot as pltimport logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR) # 只打印ERROR

2.  导入Fashion MNIST 数据集

# 如果之前没下载过,这里会先下载fashion_mnist数据集,
# 然后返回包含tensorflow.python.data.ops.dataset_ops._OptionsDataset对象的字典
#  和tensorflow_datasets.core.dataset_info.DatasetInfo对象
dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True)
train_dataset, test_dataset = dataset['train'], dataset['test']class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal',      'Shirt',   'Sneaker',  'Bag',   'Ankle boot']

3. 检查数据

num_train_examples = metadata.splits['train'].num_examples
num_test_examples = metadata.splits['test'].num_examples
print("Number of training examples: {}".format(num_train_examples))
print("Number of test examples:     {}".format(num_test_examples))

 

 

4. 数据预处理

原图像灰度值是在[0,255],为了使神经网络正常工作,要归一化到[0,1]。

def normalize(images, labels):images = tf.cast(images, tf.float32)images /= 255return images, labelstrain_dataset =  train_dataset.map(normalize)
test_dataset  =  test_dataset.map(normalize)

5. 检查经过处理的数据

# 取一张图片,重标定为(28,28)的格式用于打印
for image, label in test_dataset.take(1):break
image = image.numpy().reshape((28,28))# 画出图片(采用线性分段映射的方式绘图,0为白色,1为黑色)
plt.figure()
plt.imshow(image, cmap=plt.cm.binary)
plt.colorbar()
plt.show()

# 显示前25张图片,在每张图片下显示类别
plt.figure(figsize=(10,10))
i = 0
for (image, label) in test_dataset.take(25):image = image.numpy().reshape((28,28))plt.subplot(5,5,i+1)plt.xticks([])plt.yticks([])plt.imshow(image, cmap=plt.cm.binary)plt.xlabel(class_names[label])i += 1
plt.show()

 

 

6. 构建模型

a. 建立网络层

model = tf.keras.Sequential([tf.keras.layers.Flatten(input_shape=(28, 28, 1)),tf.keras.layers.Dense(128, activation=tf.nn.relu),tf.keras.layers.Dense(10,  activation=tf.nn.softmax)
])

b.编译模型

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',metrics=['accuracy'])

7. 训练模型

BATCH_SIZE = 32
train_dataset = train_dataset.repeat().shuffle(num_train_examples).batch(BATCH_SIZE)
test_dataset = test_dataset.batch(BATCH_SIZE)model.fit(train_dataset, epochs=5, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE))

训练的时候会打印相关信息,包括训练进度、时间、速度、损失、精确度等,可以看到,第一轮训练过后精确度已经达到82.4%部分截图如下:

 

8. 评估精确度

在测试集上评估精确度

test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32))
print('Accuracy on test dataset:', test_accuracy)

9. 预测和探索

 用训练后的模型对一些图片做预测

# test_dataset已经批处理了,所以取出的是32张图片和标签
for test_images, test_labels in test_dataset.take(1):test_images = test_images.numpy()test_labels = test_labels.numpy()predictions = model.predict(test_images)predictions.shape # (32, 10)

看一下对于第一张图片的预测结果

predictions[0]
np.argmax(predictions[0]) # 6

因此,模型最确信此图像是衬衫(数字6对应的标签是shirt),或class_names[6]。我们可以检查一下对应的标签看是否正确:

结果一致!

 

绘图

我们可以画出这幅图来查看完整的10个类别的预测值(直方图形式)

def plot_image(i, predictions_array, true_labels, images):predictions_array, true_label, img = predictions_array[i], true_labels[i], images[i]plt.grid(False)plt.xticks([])plt.yticks([])plt.imshow(img[...,0], 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[i], true_label[i]plt.grid(False)plt.xticks([])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')

先看一下第1张图片的预测结果图片和预测值直方图:

i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions,  test_labels)

第4张图片的预测结果

i = 3
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions,  test_labels)

看一下前18张图片的预测结果,正确的预测值为标蓝,错误的为标红

# Plot the first X test images, their predicted label, and the true label
# Color correct predictions in blue, incorrect predictions in red
num_rows = 6
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, test_labels, test_images)plt.subplot(num_rows, 2*num_cols, 2*i+2)plot_value_array(i, predictions, test_labels)

最后,利用训练后的模型对单个图像进行预测

# 从测试数据集中获取图像
img = test_images[0]
print(img.shape)

tf.keras 模型经过优化,可以同时对一批或一组示例进行预测。所以即使我们使用的是一张图片,也需要把它添加到一个列表中:

# 将这张图片作为唯一的成员添加到一个批次里
img = np.array([img])
print(img.shape)

# 预测图片
predictions_single = model.predict(img)print(predictions_single)plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)

提取预测的标签,和之前结果一样

扩展:

类似于上面这样,你可以把自己制作的图片(28,28)和整理成标准的格式,使用模型进行预测~

 

练习:

用不同的模型进行实验,看看结果的准确性有何不同。可以试着改变以下参数:

  1. 将训练的迭代次数(epochs)设置为1
  2. 平整层(Flatten layer)后面的密集层(Dense layer)中神经元的数量。例如,从非常低的值(例如10)上升到512这个范围内,看看精度如何变化
  3. 在平整层和最终的密集层(10,activation=tf.n .softmax)之间添加额外的密集层,在这些层中使用不同的units进行实验
  4. 不要对像素值进行归一化( normalize ),看看效果如何

 

加油~

这篇关于TensorFlow + Keras 入门项目:Classifying Images of Clothing(基于Fashion-MNIST数据集)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/741062

相关文章

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Pandas统计每行数据中的空值的方法示例

《Pandas统计每行数据中的空值的方法示例》处理缺失数据(NaN值)是一个非常常见的问题,本文主要介绍了Pandas统计每行数据中的空值的方法示例,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是空值?为什么要统计空值?准备工作创建示例数据统计每行空值数量进一步分析www.chinasem.cn处

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring