简体   繁体   English

如何在 Keras model 中使用加权 MSE 作为损失 function?

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

I am trying to use a custom loss function for calculating a weighted MSE in a regression taks (values in the task:-1,-0.5, 0, 0.5, 1, 1.5, 3 etc.).我正在尝试使用自定义损失 function 来计算回归任务中的加权 MSE(任务中的值:-1、-0.5、0、0.5、1、1.5、3 等)。 Here is my implementation of custom loss function:这是我对自定义损失 function 的实现:

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))

I am running an example which is working:我正在运行一个正在运行的示例:

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)

But when inputted into my model, it throws the following error:但是当输入到我的 model 时,它会抛出以下错误:

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

Here is how I use the custom loss function:这是我如何使用自定义损失 function:

    model.compile(
    optimizer=opt,
    loss={
        "predicted_class": weighted_mse
    })

EDIT:编辑:

when changing weight_dict[kb.get_value(yi)] to weight_dict[float(yi)] I get the following error: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'

What you want is basically the idea of sample weight.你想要的基本上是样本重量的想法。 When using training API of Keras, alongside your data you can pass another array containing the weight for each sample which is used to determine the contribution of each sample in the loss function.当使用 Keras 的训练 API 时,除了您的数据,您可以传递另一个数组,其中包含每个样本的权重,用于确定每个样本在损失 function 中的贡献。

To use it, you can use sample_weight argument of fit method:要使用它,您可以使用fit方法的sample_weight参数:

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

Note that X_weight should be an array of the same length as X (ie one weight value for each training sample).请注意, X_weight应该是一个与X长度相同的数组(即每个训练样本一个权重值)。 Further, if X is a tf.data.Dataset instance or a generator, this argument does not work and instead you need to pass the sample weight as the third element of the tuple returned by X .此外,如果Xtf.data.Dataset实例或生成器,则此参数不起作用,您需要将样本权重作为X返回的元组的第三个元素传递。

This usually happens in an old version of tensorflow.这通常发生在旧版本的 tensorflow 中。 There are 2 things you can try:您可以尝试 2 件事:

  1. Add this line to the jupyter notebook when you are importing tensorflow like so:当您像这样导入 tensorflow 时,将此行添加到 jupyter 笔记本中:
import tensorflow as tf
tf.enable_eager_execution()
  1. Upgrade tensorflow with the following command in prompt:在提示符下使用以下命令升级 tensorflow:
pip install tensorflow --upgrade

This is most probably because of eager execution.这很可能是因为急切的执行。 See the docs here for more info.有关更多信息,请参阅此处的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM