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.<