在Keras中使用預(yù)訓(xùn)練模型有兩種常見的方法:遷移學(xué)習(xí)和模型微調(diào)。
from keras.applications import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
# 加載ResNet50預(yù)訓(xùn)練模型
base_model = ResNet50(weights='imagenet', include_top=False)
# 添加自定義的分類層
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(num_classes, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
# 凍結(jié)預(yù)訓(xùn)練模型的所有層
for layer in base_model.layers:
layer.trainable = False
# 編譯模型并訓(xùn)練
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit_generator(...)
# 解凍預(yù)訓(xùn)練模型的部分層
for layer in model.layers[:100]:
layer.trainable = False
for layer in model.layers[100:]:
layer.trainable = True
# 編譯模型并繼續(xù)訓(xùn)練
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit_generator(...)
通過這兩種方法,您可以靈活地使用預(yù)訓(xùn)練模型,并根據(jù)自己的需求進(jìn)行遷移學(xué)習(xí)或模型微調(diào)。