Fashion MNIST图像识别(独热编码)

需要了解:onehot独热编码

概述

Fashion MNIST的分类是0-9之间的数字,本文对 类别 进行 onehot独热编码,然后实现

关键代码

keras的独热编码api

train_label_onehot=tf.keras.utils.to_categorical(train_label)

print(train_label[0])
print(train_label_onehot[0])

执行结果如下:

9
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

配置训练模型 指定损失函数

model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])

代码

加载数据

import tensorflow as tf

(train_image,train_label),(test_image,test_label)=tf.keras.datasets.fashion_mnist.load_data()

其中 训练 数据有 60000 张图像,测试 数据有 10000 张图像

查看图像数据形状

# 查看形状
print(train_image.shape)

print(test_image.shape)

结果:

(60000, 28, 28)
(10000, 28, 28)

训练数据 有60000个,图像是 28宽 28高,也就是说每个图像有28*28=784个特征

也就是说,在神经网络模型中,输入值 共有 784 个

测试数据 有10000个,图像是 28宽 28高

显示图像

通过matplotlib显示图像

# 显示第一张图像

plt.imshow(train_image[0])

分析图像数据

print(train_image[0].shape)
# 查看最大值
np.max(train_image[0])

图像数据,是0-255之间的RGB值

查看类别数据形状

print(train_label.shape)

print(test_label.shape)

执行结果:

(60000,)
(10000,)

分析类别数据

train_label

类别是数字,每个数字对应一个类别,上面有对应表格,共有10个类别

也就是说,在神经网络模型中,输出层 有 10个 感知机(神经元)

对类别进行独热编码

train_label_onehot=tf.keras.utils.to_categorical(train_label)
print(train_label[0])
print(train_label_onehot[0])

test_label_onehot=tf.keras.utils.to_categorical(test_label)
print(test_label[0])
print(test_label_onehot[0])

图像数据 归一化

将图像0-255的RGB转换成0-1的数据

train_image=train_image/255
test_image=test_image/255

train_image[0]

建立模型

model=tf.keras.Sequential()

# 线性回归中是一维数据,而图像数据是二维数据,需要将二维数据转换成一维数据
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
# 数量不能太少,会欠拟合,也不能太多,会过拟合
model.add(tf.keras.layers.Dense(128,activation='relu'))
# 10个分类,softmax的作用就是将10个输出值变成概率值,这些概率值之和为1
model.add(tf.keras.layers.Dense(10,activation='softmax'))

model.summary()

配置训练模型

由于目标值 分类 是 one-hot 独热编码 ,所以使用 categorical_crossentropy 损失函数

model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])

开始训练

model.fit(train_image,train_label_onehot,epochs=5)

评估模型

评估模型,就是预测训练数据,将预测结果与真实结果做比对,并计算出正确率

model.evaluate(test_image,test_label_onehot)

进行预测

通过模型预测训练数据

prd_label=model.predict(test_image)

查看预测结果

# 预测结果是长度为10的数组,分别表示各个类别的概率,其和是1
print(prd_label[0])
# 获取最大概率的索引
label_num=tf.argmax(prd_label[0])
print(type(label_num))
label_num=int(label_num)
print(type(label_num))
print(label_num,test_label[0])

显示预测结果,并计算预测准确率,看与评估结果是否一致

# 显示预测结果,并计算预测准确率,看与评估结果是否一致
error_num=0
for item in range(10000):
    label_num=tf.argmax(prd_label[item])
    label_num=int(label_num)
#     print(label_num,test_label[item])
    if label_num!=test_label[item]:
        error_num+=1

print('错误总数:',error_num)
print('正确率:',1-error_num/10000)

原文出处:/show_1EF449OIwfXl.html