深度学习VGG16的迁移学习模型代码
时间: 2023-09-25 10:06:16 浏览: 109
以下是使用VGG16进行迁移学习的代码示例:
```python
from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.layers import Dense, Flatten
# 加载预训练模型VGG16
vgg16 = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# 禁止训练预训练模型的权重
for layer in vgg16.layers:
layer.trainable = False
# 添加自定义的输出层
x = vgg16.output
x = Flatten()(x)
x = Dense(256, activation='relu')(x)
x = Dense(128, activation='relu')(x)
predictions = Dense(2, activation='softmax')(x)
# 构建新的模型
model = Model(inputs=vgg16.input, outputs=predictions)
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 定义数据生成器
train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory('train', target_size=(224, 224), batch_size=32, class_mode='categorical')
validation_generator = test_datagen.flow_from_directory('validation', target_size=(224, 224), batch_size=32, class_mode='categorical')
# 训练模型
model.fit_generator(train_generator, steps_per_epoch=2000, epochs=50, validation_data=validation_generator, validation_steps=800)
```
在此代码示例中,我们加载了预训练的VGG16模型,并禁止了它的所有权重进行训练。然后,我们添加了自定义的输出层,并根据需要进行了编译。接下来,我们定义了用于训练模型的数据生成器,并使用fit_generator方法对模型进行训练。
阅读全文