Francesco Pegoraro
Francesco Pegoraro

Reputation: 808

Use layer output in keras custom loss

I am developing a custom loss function in Keras and I need the first layer output.

How can I retrieve it?

def custom_loss(y_true, y_pred):
    cross = K.mean(K.binary_crossentropy(y_true, y_pred), axis = 1)
    layer_output = model.get_layer_output(1) # this is what i'd like to use
    return cross  + perturb

Upvotes: 4

Views: 2160

Answers (1)

DarkCygnus
DarkCygnus

Reputation: 7838

Checking the docs you can retrieve a layer by using the model.get_layer() method. You can then pass the desired index or well pass the name of the layer.

After getting a layer you can easily obtain its output by using the layer.output attribute, as explained here on the docs.

Combining both you can obtain the output of your desired layer.

Upvotes: 2

Related Questions