数据挖掘算法和实践(十二):使用tf.keras实现fashion_MNIST图像分类

fashion_MNIST是一个手写图像分类数据集,主要是一些穿衣搭配的图表,数据集比较小,是一个适合练手的数据集,也是第一个多分类实例,使用softmax损失函数进行训练;softmax保证输出的分类是一个概率,且所以分类的概率结果加起来是1;

本次是首次使用图像数据集,一般需要采用卷积神经网络进行数据的特征提取,本次的数据集本身就是一些带有特征的数据(图像的边界比较清晰),先不使用卷积网络而是直接训练,比如下面的高跟鞋,数据集的特征边界很明显:

 实现如下:

from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np
rng = np.random
import matplotlib.pyplot as plt
%matplotlib inline

(train_image,train_lable),(test_image,test_lable)=tf.keras.datasets.fashion_mnist.load_data()
# type(train_image)

 # image show 查看图像
plt.imshow(train_image[0])

train_image=train_image/255 # 归一化
test_image=test_image/255

# 简历顺序模型
model=tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28))) # 28*28向量
model.add(tf.keras.layers.Dense(128,activation="relu"))
model.add(tf.keras.layers.Dense(10,activation="softmax"))
model.compile(optimizer="adam",loss="sparse_categorical_crossentropy",metrics=["acc"])


# X = np.array([[1.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1],[2]])
# Y= np.array([1.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
# Y[0:2]

#  softmax的损失函数用sparse_categorical_crossentropy 和categorical_crossentropy
#  独热编码时候用categorical_crossentropy:
# train_lable_onehot=tf.keras.utils.to_categorical(train_lable)

history=model.fit(train_image,train_lable,epochs=5)
model.evaluate(test_image,test_lable)
# 查看损失函数图像
plt.plot(history.epoch,history.history.get('loss'))
# 查看准确率图像
plt.plot(history.epoch,history.history.get('acc'))
#train_lable_onehot

可以直接查看图像观察数据,plt.imshow(train_image[0])是一个鞋子,

损失函数的变化情况:

准确率变化情况:

猜你喜欢

转载自blog.csdn.net/yezonggang/article/details/106396244