机器学习笔记(一)Tensorflow / keras 对服装图像进行分类( Fashion MNIST 数据集)

开发环境

Anaconda 4.9.2 / Python 3.6.12 / Tensorflow 2.4.1(CPU版)

程序简介

本程序旨在利用 TensorFlow 中用来构建和训练模型的高级 API —— keras 训练一个神经网络模型,对服装图像进行分类(10类)。程序中的数据集使用 Fashion MNIST 数据集,包含 T-shirt 、Trouser 、Pullover 等10个类别的70000个灰度图像(28x28 像素)。
本程序使用60000个图像(训练集)来训练网络,使用10000个图像(测试集) 来测试网络学习对图像分类的准确率。

程序分解

输出 Tensorflow 版本

代码

import tensorflow as tf 
from tensorflow import keras
import numpy as np 
import matplotlib.pyplot as plt 
print(tf.__version__)

结果:版本 Tensorflow 2.4.1
在这里插入图片描述

下载 Fashion MNIST 数据集

代码

fashion_mnist = keras.datasets.fashion_mnist
(train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt','Trouser','Pullover','Dress','Coat','Sandal','Shirt','Sneaker','Bag','Ankle boot']

load_data() 会返回四个 NumPy 数组:train_images 与 train_labels 数组是训练集,test_images 和 test_labels 数组是测试集。
图像是28x28的 NumPy 数组,像素值介于0到255之间
标签是整数数组,介于0到9之间。这些标签对应于 class_names 数组中的 T-shirt、Trouser、Pullover、Dress、Coat、Sandal、Shirt、Sneaker、Bag、Ankle boot。

结果:在路径为 > .keras > datasets > fashion_mnist 的 fashion_mnist 文件夹下下载了如图所示的4个 .gz 格式的压缩包
在这里插入图片描述
在这里插入图片描述

预处理数据

代码

train_images = train_images/255.0
test_images = test_images/255.0
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()

将 train_images 与 test_images 这些值除以255缩小至0-1之间,以便将其送到神经网络中。
为了验证数据格式是否正确、是否已准备好构建和训练网络,此处显示训练集中前 25 个图像,并在每个图像下方显示类名称。

结果
在这里插入图片描述

构建神经网络模型

代码

model = keras.Sequential([keras.layers.Flatten(input_shape=(28,28)),keras.layers.Dense(128,activation='relu'),keras.layers.Dense(10)])

网络第一层keras.layers.Flatten :将图像格式从二维数组(28x28像素)转换成一维数组(28x28=784像素)。该层没有要学习的参数,它只会重新格式化数据。
网络第二层 keras.layers.Dense :全连接层,128个神经元,激活函数采用线性整流函数ReLU。
网络第三层 keras.layers.Dense :返回一个长度为10的 logits 数组(线性输出)。

编译模型

代码

model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])

设置三个度量
优化器:决定模型如何根据其看到的数据和自身的损失函数进行更新。
损失函数:用于测量模型在训练期间的准确率,希望最小化此函数,以便将模型“引导”到正确的方向上。
准确率:被正确分类的图像的比率。

训练与预测

1.将训练数据送至模型

代码

model.fit(train_images,train_labels,epochs=10)

使用训练集的全部数据对模型进行10次训练。在模型训练期间,会显示损失和准确率指标。此模型在训练数据上的准确率达到了0.91(或91%)左右。

结果
在这里插入图片描述

2.在测试集上评估

代码

test_loss,test_acc = model.evaluate(test_images,test_labels,verbose=2)
print('\nTest accuracy:',test_acc)
print('\nTest loss:',test_loss)

结果
在这里插入图片描述

结果表明,模型在测试集上的准确率略低于训练集。
训练准确率和测试准确率之间的差距代表过拟合。
过拟合是指机器学习模型在新的、以前未曾见过的输入上的表现不如在训练集上的表现。过拟合的模型会“记住”训练集中的噪声和细节,从而对模型在新数据上的表现产生负面影响。

3.进行预测

代码

probability_model = tf.keras.Sequential([model,tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print(np.argmax(predictions[8]))

经过训练后,使用它对一些图像进行预测。模型具有线性输出,即 logits 。此处再附加一个 softmax 层,将 logits 转换成更容易理解的概率。

此处预测测试集中第9幅图像(从0开始)的预测结果,predictions[8]是一个包含10个数字的数组,代表模型对10种不同服装中每种服装的“置信度”,取置信度最大(argmax)的标签即为预测结果。

结果
在这里插入图片描述

完整代码

import tensorflow as tf 
from tensorflow import keras
import numpy as np 
import matplotlib.pyplot as plt 
print(tf.__version__)
fashion_mnist = keras.datasets.fashion_mnist
(train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt','Trouser','Pullover','Dress','Coat','Sandal','Shirt','Sneaker','Bag','Ankle boot']
train_images = train_images/255.0
test_images = test_images/255.0
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)
print('\nTest loss:',test_loss)
probability_model = tf.keras.Sequential([model,tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print(np.argmax(predictions[8]))

猜你喜欢

转载自blog.csdn.net/Echoshit8/article/details/114025500