导包
import tensorflow as tffrom tensorflow.keras import datasets, layers, models
加载Fashion-MNIST数据集
(train_images, train_labels), (test_images, test_labels) =datasets.fashion_mnist.load_data()
归一化像素值到[0, 1]区间
train_images, test_images = train_images / 255.0, test_images / 255.0
由于Fashion-MNIST的图像是灰度图像,需要增加一个颜色通道
train_images = train_images.reshape(-1, 28, 28, 1)test_images = test_images.reshape(-1, 28, 28, 1)
对标签进行分类编码
train_labels = tf.keras.utils.to_categorical(train_labels, 10)test_labels = tf.keras.utils.to_categorical(test_labels, 10)
定义AlexNet模型
model = models.Sequential([layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),layers.MaxPooling2D((2, 2)),layers.Conv2D(64, (3, 3), activation='relu'),layers.MaxPooling2D((2, 2)),layers.Conv2D(128, (3, 3), activation='relu'),layers.MaxPooling2D((2, 2)),layers.Flatten(),layers.Dense(128, activation='relu'),layers.Dense(10, activation='softmax')])
编译模型
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])
训练模型
model.fit(train_images, train_labels, epochs=10, batch_size=64, validation_data=(test_images, test_labels))
评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)print(f'Test Accuracy: {test_acc:.4f}')
训练模型保存
save_path = r'D:\\图像处理、深度学习\\训练保存\\AlexNet.h5'model.save(save_path)