在Keras中使用预训练的模型进行迁移学习可以通过以下步骤实现:
from keras.applications import VGG16
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
for layer in base_model.layers:
layer.trainable = False
from keras.models import Model
from keras.layers import Flatten, Dense
x = Flatten()(base_model.output)
x = Dense(256, activation='relu')(x)
predictions = Dense(num_classes, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit_generator(train_generator, steps_per_epoch=train_steps, epochs=num_epochs, validation_data=val_generator, validation_steps=val_steps)
这样就可以在Keras中使用预训练的模型进行迁移学习了。通过冻结预训练模型的层,可以保留其学到的特征表示,然后在顶部添加自定义层进行新的任务训练。