【发布时间】:2021-05-23 00:53:03
【问题描述】:
我正在尝试在我的神经网络上实现一个自定义损失函数,如果张量是 numpy 数组,它看起来像这样:
def custom_loss(y_true, y_pred):
activated = y_pred[y_true > 1]
return np.abs(activated.mean() - activated.std()) / activated.std()
y's 的形状为(batch_size, 1);也就是说,它是每个输入行的标量输出。
obs:这篇文章 (Converting Tensor to np.array using K.eval() in Keras returns InvalidArgumentError) 给了我一个初步的前进方向。
编辑:
这是我尝试应用自定义损失函数的可重现设置:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
X = np.random.normal(0, 1, (256, 5))
Y = np.random.normal(0, 1, (256, 1))
model = keras.Sequential([
layers.Dense(1),
])
model.compile(optimizer='adam', loss=custom_loss)
model.fit(X, Y)
如果我按照上面的问题定义custom_loss,最后一行的.fit() 会引发错误AttributeError: 'Tensor' object has no attribute 'mean'。
【问题讨论】:
-
这能回答你的问题吗? Make a custom loss function in keras
-
@M.Innat,我无法根据您的情况调整您建议的答案。我什至尝试使用相同的代码(答案中的那个),但我收到了错误
TypeError: Input 'y' of 'Mul' Op has type bool that does not match type float32 of argument 'x'.。不确定最新的张量流和那里的张量流之间是否存在版本兼容性问题。 -
你能给出一些可重现的代码吗?我遇到过这样的问题,如果你能提供一些重现代码,那就太好了。
标签: python tensorflow keras