Skip to content

Instantly share code, notes, and snippets.

@ruslangrimov
Last active August 28, 2018 18:11
Show Gist options
  • Save ruslangrimov/ece6bb9d8b6c3475cff6b0209ebfc8de to your computer and use it in GitHub Desktop.
Save ruslangrimov/ece6bb9d8b6c3475cff6b0209ebfc8de to your computer and use it in GitHub Desktop.
Split the last layer of a keras model into a linear layer and an activation layer
import tempfile
from keras.models import load_model
from keras import activations
from keras.layers import Activation
def split_last_layer(model):
def apply_modifications(model, custom_objects=None):
model_path = os.path.join(tempfile.gettempdir(), next(tempfile._get_candidate_names()) + '.h5')
try:
model.save(model_path)
return load_model(model_path, custom_objects=custom_objects)
finally:
os.remove(model_path)
p_act = model.layers[-1].activation
model.layers[-1].activation = activations.linear
new_model = apply_modifications(model)
new_model = Model(new_model.inputs, Activation(p_act)(new_model.layers[-1].output))
return new_model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment