在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中进行模型微调。