LeNet-5训练
导包
import tensorflow as tf
from tensorflow.keras import layers, models, datasets, optimizers
加载Fashion-MNIST数据集
(train_images, train_labels), (test_images, test_labels) = datasets.fashion_mnist.load_data()
归一化像素值到[0, 1]区间
train_images = train_images.astype("float32") / 255
test_images = test_images.astype("float32") / 255
对标签进行分类编码
train_labels = tf.keras.utils.to_categorical(train_labels, 10)
test_labels = tf.keras.utils.to_categorical(test_labels, 10)
定义LeNet-5模型
model = models.Sequential([
layers.Conv2D(6, (5, 5), activation='relu', input_shape=(28, 28, 1)),
layers.AveragePooling2D((2, 2)),
layers.Conv2D(16, (5, 5), activation='relu'),
layers.AveragePooling2D((2, 2)),
layers.Conv2D(120, (3, 3), activation='relu', padding='valid'),
# 注意:这里可能需要调整以避免过拟合或尺寸问题
layers.Flatten(),
layers.Dense(84, activation='relu'),
layers.Dense(10, activation='softmax')
])
编译模型
model.compile(optimizer=optimizers.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:\\图像处理、深度学习\\训练保存\\LeNet-5.h5'
model.save(save_path)