【发布时间】:2020-11-03 17:40:36
【问题描述】:
我正在尝试使用自定义损失函数来计算回归任务中的加权 MSE(任务中的值:-1、-0.5、0、0.5、1、1.5、3 等)。这是我的自定义损失函数的实现:
import tensorflow
import tensorflow.keras.backend as kb
def weighted_mse(y, yhat):
ind_losses = tensorflow.keras.losses.mean_squared_error(y, yhat)
weights_ind = kb.map_fn(lambda yi: weight_dict[kb.get_value(yi)], y, dtype='float32')
# average loss over weighted sum of the batch
return tensorflow.math.divide(tensorflow.math.reduce_sum(tensorflow.math.multiply(ind_losses, weights_ind)), len(y))
我正在运行一个正在运行的示例:
weight_dict = {-1.0: 70.78125, 0.0: 1.7224334600760458, 0.5: 4.58502024291498, 1.0: 7.524916943521595, 1.5: 32.357142857142854, 2.0: 50.33333333333333, 2.5: 566.25, 3.0: 566.25}
y_true = tensorflow.convert_to_tensor([[0.5],[3]])
y_pred = tensorflow.convert_to_tensor([[0.5],[0]])
weighted_mse(y_true, y_pred)
但是当输入到我的模型中时,它会抛出以下错误:
AttributeError: 'Tensor' object has no attribute '_numpy'
这是我如何使用自定义损失函数:
model.compile(
optimizer=opt,
loss={
"predicted_class": weighted_mse
})
编辑:
将weight_dict[kb.get_value(yi)] 更改为weight_dict[float(yi)] 时出现以下错误:
TypeError: float() argument must be a string or a number, not 'builtin_function_or_method'
【问题讨论】:
-
两个问题:1)是否保证您的模型只输出-1.0、0、0.5、1.0等? (这对于回归模型来说很奇怪!),以及 2)我是否认为您想要实现的是
weight_y_true * mse(y_true, y_pred)其中weight_y_true取决于y_true的值? -
1) 是的,保证 2) 完全正确
标签: python tensorflow machine-learning keras loss-function