Skip to content
Advertisement

Keras my_layer.output returning KerasTensor object instead of Tensor object (in custom loss function)

I’m trying to build a custom loss function in Keras v2.4.3: (as explained in this answer)

JavaScript

But I think it’s behaving much different than expected (perhaps because of my Keras version?), I’m getting this error:

JavaScript

And I think that’s because encoder.get_layer('mean').output is returning a KerasTensor object instead of a tf.Tensor object (as the other answer indicates).

What am I doing wrong here? How can I access the output of a given layer from inside a custom loss function?

Advertisement

Answer

I think it’s very simple using model.add_loss(). this functionality enables you to pass multiple inputs to your custom loss.

To make a reliable example I produce a simple VAE where I add the VAE loss using model.add_loss()

The full model structure is like below:

JavaScript

The running notebook is available here: https://colab.research.google.com/drive/18day9KMEbH8FeYNJlCum0xMLOtf1bXn8?usp=sharing

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement