AttributeError: 'Tensor' object has no attribute 'numpy' when using a Keras-based custom loss function

AttributeError: 'Tensor' object has no attribute 'numpy' when using a Keras-based custom loss function

我阅读了题为“改进神经可训练校准方法”的出版物 NETWORKS ON MEDICAL IMAGING CLASSIFICATION”可在 https://arxiv.org/pdf/2009.04057.pdf 获得。在这项研究中,他们提出了一个自定义损失函数,将校准纳入模型训练过程。他们将校准组件包含在分类交叉熵损失中以创建此自定义函数. 我已经创建了这个函数的 Keras 版本,如下所示:

def dca_loss(y_true, y_pred, beta=1):
    # y_true: one-hot encoding
    # y_pred: predicted probability (i.e., softmax(logits))
 
    ## calculating cross-entropy loss ##
    loss_ce = K.mean(keras.losses.categorical_crossentropy(y_true, y_pred)) 
    
    ## calculating the DCA term ##
    # get gt labels
    gt_labels = tf.argmax(y_true, axis=1).numpy()
    # get pred labels
    pred_labels = tf.argmax(y_pred, axis=1).numpy()
    # get accuracy 
    acc = np.sum(gt_labels==pred_labels)/len(gt_labels)
    # get pred mean prob
    temp_prop = 0
    for i in range(len(y_true)):
      temp_prop+=y_pred[i, pred_labels[i]]
    prob = temp_prop/len(y_true)
    # calculating dca
    dca = np.abs(acc-prob)

    loss = loss_ce + beta*dca
    
    return loss

我编译的模型如下图:

model.compile(optimizer='sgd', 
                    loss=[dca_loss],  
                    metrics=['accuracy']) 

报错如下:

c:\users\appdata\local\continuum\anaconda3\envs\tf_2.4\lib\site-packages\tensorflow\python\keras\engine\training.py:805 train_function  *
        return step_function(self, iterator)
    C:\Users\codes\custom_loss_final.py:560 dca_loss  *
        gt_labels = tf.argmax(y_true, axis=1).numpy()

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

我了解在自定义函数声明中不应使用 numpy。我需要帮助来使用 tf 函数或 Keras 后端函数作为替代。

您有两个选择:

a) 将 Tensorflow ufuncs 用于损失函数,例如不使用 .numpy() 并将 np.sum() 替换为 tf.reduce_sum()

b) 使用 NumPy ufuncs,但通过在 model.compile()

中传递 run_eagerly=True 来热切地训练