gpt4 book ai didi

python - 属性错误 : 'Tensor' object has no attribute 'numpy' when using a Keras-based custom loss function

转载 作者:行者123 更新时间:2023-12-05 03:38:07 24 4
gpt4 key购买 nike

我阅读了题为“改进神经网络可训练校准方法”的出版物医学影像分类网络”可在 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 来热切训练

关于python - 属性错误 : 'Tensor' object has no attribute 'numpy' when using a Keras-based custom loss function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69077453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com