如何在 Keras 模型中使用加权 M​​SE 作为损失函数?

How can I use a weighted MSE as loss function in a Keras model?

我正在尝试使用自定义损失函数来计算回归任务中的加权 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'

这通常发生在旧版本的tensorflow中。您可以尝试两件事:

  1. 像这样导入 tensorflow 时,将此行添加到 jupyter notebook 中:
import tensorflow as tf
tf.enable_eager_execution()
  1. 在提示符下使用以下命令升级 tensorflow:
pip install tensorflow --upgrade

This is most probably because of eager execution. See the docs here for more info.

你想要的基本上是样本权重的想法。使用 Keras 的训练 API 时,除了您的数据之外,您还可以传递另一个数组,其中包含每个样本的权重,用于确定每个样本在损失函数中的贡献。

要使用它,您可以使用 fit 方法的 sample_weight 参数:

model.fit(X, y, sample_weight=X_weight, ...)

注意X_weight应该是一个和X等长的数组(即每个训练样本一个权重值)。此外,如果 Xtf.data.Dataset 实例或生成器,则此参数不起作用,您需要将样本权重作为 X 返回的元组的第三个元素传递。