在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中使用預訓練的模型進行遷移學習了。通過凍結預訓練模型的層,可以保留其學到的特征表示,然后在頂部添加自定義層進行新的任務訓練。