实验:通过卷积神经网络实现fashion识别

导入包

import tensorflow as tf
import numpy as np
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D,MaxPool2D,GlobalAveragePooling2D,Dense,Dropout
from tensorflow.keras.datasets.fashion_mnist import load_data
import matplotlib.pyplot as plt

加载数据

(train_images,train_labels),(test_images,test_labels)=load_data()
train_images.shape

归一化

train_images=train_images/255
test_images=test_images/255

改变维度

train_images=np.expand_dims(train_images,-1)
test_images=np.expand_dims(test_images,-1)
test_images.shape

获取输入维度

input_shape=train_images.shape[1:]
input_shape

建立模型

model=Sequential()
"""
第一层用卷积层,提取图片特征
卷积核数量:32个
卷积核大小:3*3
激活函数:relu

"""

model.add(Conv2D(64,(3,3),input_shape=input_shape,activation='relu',padding="same"))
model.add(MaxPool2D())
model.add(Dropout(0.5))

model.add(Conv2D(64,(3,3),activation='relu',padding="same"))
model.add(Dropout(0.5))

"""
全连接(Dense)层,接收2维数据,所以要将上面的数据处理层2维
采用:全局的平均值化,在所有的维度上做了一个平均
不能用flatten层,因为数据量过大
"""
model.add(GlobalAveragePooling2D())

model.add(Dense(10,activation='softmax'))

model.summary()

编译

"""
optimizer:
loss:类别是1,2,3。。。,所以损失函数用sparse_categorical_crossentropy
metrics:训练时显示正确率
"""
model.compile(optimizer="adam",
             loss="sparse_categorical_crossentropy",
             metrics=["acc"])

训练数据

"""

validation_data:训练过程中测试数据的损失和正确率
"""
history=model.fit(
    train_images,
    train_labels,
    epochs=5,
    validation_data=(test_images,test_labels))
model.save("fashion卷积网络-优化-训练25次")

查看损失值

plt.plot(history.epoch,history.history.get("loss"),label="loss")
plt.plot(history.epoch,history.history.get("val_loss"),label="val_loss")
plt.legend()

查看准确率

plt.plot(history.epoch,history.history.get("acc"),label="acc")
plt.plot(history.epoch,history.history.get("val_acc"),label="val_acc")
plt.legend()

原文出处:/show_1EF4V9jd7Pa3.html