AttributeError: 'Tensor' object has no attribute 'numpy' in custom loss function (Tensorflow 2.1.0)

Viewed 1540

I want to train a model with a custom loss function, in order to do that, I need to convert the tensor to numpy array inside the method below:

def median_loss_estimation(y_true, y_predicted):
    a = y_predicted.numpy()

but I have this error:

AttributeError: 'Tensor' object has no attribute 'numpy'

Why? How can I convert the tensor to a numpy array?

2 Answers

The answer is: put run_eagerly=True in model.compile!

You're doing the right thing, only Tensorflow 2.1 is currently broken in that aspect. This would normally happen if you run the code without eager mode enabled. However, Tensorflow 2 by default runs in eager mode... or at least it should. The issue is tracked here.

There are at least two solutions to this:

  1. Install the latest nightly build.
  2. Set model.run_eagerly = True.
Related