VGG-19训练
导包
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
由于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)
定义一个简单的卷积层来增加图像的尺寸,使其适合VGG-19的输入
preprocessing = models.Sequential([
layers.Conv2D(3, (1, 1), activation='relu', input_shape=(28, 28, 1)),
layers.UpSampling2D((2, 2)), # 将图像尺寸增加到56x56
])
应用预处理
train_images = preprocessing(train_images)
test_images = preprocessing(test_images)
加载VGG19模型并冻结所有层
base_model = tf.keras.applications.VGG19(weights='imagenet', include_top=False, input_shape=(56, 56, 3))
base_model.trainable = False
添加自定义分类器
model = models.Sequential([
base_model,
layers.GlobalAveragePooling2D(),
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:\\图像处理、深度学习\\训练保存\\VGG-19.h5'
model.save(save_path)