基于tensorflow迁移学习resnet50完整代码
时间: 2023-07-17 13:07:06 浏览: 120
当使用TensorFlow进行迁移学习时,可以使用预训练的ResNet-50模型作为基础模型,并在其基础上进行微调。以下是一个基于TensorFlow的完整代码示例:
```python
import tensorflow as tf
from tensorflow import keras
# 加载预训练模型
base_model = keras.applications.ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# 冻结预训练模型的权重
for layer in base_model.layers:
layer.trainable = False
# 添加自定义的分类器层
x = base_model.output
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dense(256, activation='relu')(x)
predictions = keras.layers.Dense(num_classes, activation='softmax')(x)
# 创建完整的模型
model = keras.models.Model(inputs=base_model.input, outputs=predictions)
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 数据准备和增强
train_datagen = keras.preprocessing.image.ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode='categorical')
# 训练模型
model.fit(
train_generator,
steps_per_epoch=train_steps_per_epoch,
epochs=num_epochs,
validation_data=validation_generator,
validation_steps=validation_steps_per_epoch)
# 评估模型
test_generator = test_datagen.flow_from_directory(
test_data_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode='categorical',
shuffle=False)
scores = model.evaluate(test_generator)
print(f'Test loss: {scores[0]}')
print(f'Test accuracy: {scores[1]}')
```
请注意,上述代码中的数据集路径、类别数量、训练轮数、批次大小等需要根据您的具体情况进行适当修改。此代码将在训练集上微调预训练的ResNet-50模型,并在验证集和测试集上评估性能。
阅读全文