- Load model
model_A = keras.models.load_model("model_A.h5")
- Clone Architecture
model_A_clone = keras.models.clone_model(model_A)
- Clone Weights
model_A_clone.set_weights(model_A.get_weights())
- Delete Last Layer
model_B = keras.models.Sequential(model_A_clone.layers[:-1])
- Add Final layer => Change to Binary classifier
model_B.add(keras.layers.Dense(1, activation="sigmoid"))
You can prevent copied layers to be affected when training for another task
for layer in model_B.layers[:-1]:
layer.trainable = False
Finally, before you do anything, you should always remember to compile the model
model_B.compile(loss="binary_crossentropy",
optimizer=keras.optimizers.SGD(learning_rate=1e-3),
metrics=["accuracy"])
References:
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition