CIFAR-10 数据集是一个广泛使用的图像分类数据集,包含 60000 张 32x32 像素的彩色图像,分为 10 个类别,每个类别有 6000 张图像。其中 50000 张用于训练,10000 张用于测试。ResNet50 是一种深度残差网络,它在 ImageNet 数据集上表现出色,但在 CIFAR-10 这样的小图像数据集上,需要进行一些调整以提高精度。
以下是一个使用 TensorFlow 和 Keras 构建和训练 ResNet50 模型的示例代码:
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 加载 CIFAR-10 数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # 归一化
# 数据增强
datagen = ImageDataGenerator(
rotation_range=15,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
zoom_range=0.1
)
datagen.fit(x_train)
# 构建模型
base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3))
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = BatchNormalization()(x)
x = Dropout(0.5)(x)
predictions = Dense(10, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
# 编译模型
model.compile(optimizer=Adam(lr=0.001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(datagen.flow(x_train, y_train, batch_size=64),
epochs=100,
validation_data=(x_test, y_test))
# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'\nTest accuracy: {test_acc}')
通过上述方法和策略,可以有效提高 ResNet50 在 CIFAR-10 数据集上的分类精度。
领取专属 10元无门槛券
手把手带您无忧上云