在Keras中進行模型微調通常需要以下步驟:
from keras.applications import VGG16
base_model = VGG16(weights='imagenet', include_top=False)
from keras.models import Model
from keras.layers import Flatten, Dense
x = base_model.output
x = Flatten()(x)
predictions = Dense(num_classes, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
for layer in base_model.layers:
layer.trainable = False
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=32, epochs=10, validation_data=(X_val, y_val))
for layer in model.layers[:10]:
layer.trainable = True
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=32, epochs=10, validation_data=(X_val, y_val))
通過以上步驟,就可以在Keras中進行模型微調。