When use my custom loss function I get this error: 'Tensor' object has no attribute '_numpy'

When use my custom loss function I get this error: 'Tensor' object has no attribute '_numpy'

我正在尝试为我的 CNN 创建自定义损失函数,但是当我编译模型时出现此错误:'Tensor' object has no attribute '_numpy'。 我不知道如何解决它。谁能帮帮我?

def custom_loss(y_true, y_pred):
  y_pred = tf.keras.backend.get_value(y_pred)
  y_true = tf.keras.backend.get_value(y_true)
  errors = []
  for x in range(0,y_pred.shape[0]):
    error = 0
    true_range = np.argmax(y_true[x])
    for i in range(0, y_pred[x].shape[0]):
      error = error + ((i-true_range)**2)*y_pred[x][i]
    errors.append(error)
  return tf.convert_to_tensor(np.array(errors))

model.compile(loss = custom_loss, metrics=['accuracy'], optimizer=keras.optimizers.Adam())

在程序开头添加 tf.enable_eager_execution()。这将添加对 numpy 的支持。

https://github.com/tensorflow/tensorflow/issues/27519