深度学习VGG16迁移学习模型代码
时间: 2023-11-09 22:16:08 浏览: 112
以下是使用预训练的VGG16模型进行迁移学习的代码示例:
```python
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.applications import VGG16
# 设置数据集路径和参数
train_data_dir = 'train/'
validation_data_dir = 'validation/'
img_width, img_height = 224, 224
batch_size = 32
epochs = 10
# 加载预训练的VGG16模型
vgg16_model = VGG16(weights='imagenet', include_top=False, input_shape=(img_width, img_height, 3))
# 冻结预训练模型的所有层
for layer in vgg16_model.layers:
layer.trainable = False
# 构建模型
model = Sequential()
model.add(vgg16_model)
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.Adam(lr=0.0001),
metrics=['accuracy'])
# 数据增强
train_datagen = ImageDataGenerator(rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
# 训练模型
model.fit(train_generator,
steps_per_epoch=train_generator.samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_generator.samples // batch_size)
```
在这个示例中,我们使用预训练的VGG16模型作为特征提取器,并添加了几个全连接层来进行分类。我们还对预训练模型的所有层进行了冻结,并使用ImageDataGenerator进行数据增强。最后,我们使用fit()方法来训练模型。
阅读全文