用fashion_mnist数据集构建模型

发布时间 2023-09-08 07:41:58作者: 立体风
#预处理数据
import tensorflow as tf
#加载数据
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data()
#映射数据分类
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
#归一化数据
train_images,test_images = train_images/255.0,test_images/255.0

# 构建模型
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28,28)),
    tf.keras.layers.Dense(128,activation='relu'),
    tf.keras.layers.Dense(10,activation='softmax')
])

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

#训练模型
model.fit(train_images,train_labels,epochs=5)

#评估模型
test_loss,test_acc = model.evaluate(test_images,test_labels,verbose=2)

#挑选单个数据测试
import numpy as np
img = test_images[5]
img = np.expand_dims(img,0)
single = model.predict(img)
single_index = np.argmax(single[0])
class_names[single_index]
输出:Trouser 裤子
#查看具体的图像,看看是否正确
import matplotlib.pyplot as plt
plt.figure(figsize=(1,1))
plt.imshow(test_images[5])
plt.show()