在Keras中使用預(yù)訓(xùn)練的模型進行遷移學(xué)習(xí)可以通過以下步驟實現(xiàn):
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中使用預(yù)訓(xùn)練的模型進行遷移學(xué)習(xí)了。通過凍結(jié)預(yù)訓(xùn)練模型的層,可以保留其學(xué)到的特征表示,然后在頂部添加自定義層進行新的任務(wù)訓(xùn)練。