本文介绍了keras中的加权MSE自定义损失函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理时间序列数据,可以提前输出60天的预测日期.

I'm working with time series data, outputting 60 predicted days ahead.

我目前使用均方误差作为损失函数,结果很差

I'm currently using mean squared error as my loss function and the results are bad

我想实现加权均方误差,以使早期输出比以后的输出重要得多.

I want to implement a weighted mean squared error such that the early outputs are much more important than later ones.

加权均方根公式:

因此,我需要某种方式来遍历带有索引的张量元素(因为我需要同时遍历预测值和真实值,然后将结果仅写入一个元素到张量中.)都是(?,60)但实际上(1,60)个列表.

So I need some way to iterate over a tensor's elements, with an index (since I need to iterate over both the predicted and the true values at the same time, then write the results to a tensor with only one element. They're both (?,60) but really (1,60) lists.

我正在尝试的一切都没有用.这是损坏版本的代码

And nothing I'm trying is working. Here's the code for the broken version

def weighted_mse(y_true,y_pred):
    wmse = K.cast(0.0,'float')

    size = K.shape(y_true)[0]
    for i in range(0,K.eval(size)):
        wmse += 1/(i+1)*K.square((y_true[i]-y_pred)[i])

    wmse /= K.eval(size)
    return wmse

目前,我收到此错误消息:

I am currently getting this error as a result:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'dense_2_target' with dtype float
 [[Node: dense_2_target = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

阅读过类似帖子的回复后,我认为掩码无法完成任务,并且由于无法访问另一个张量中的相应元素,因此无法在一个张量中循环元素

Having read the replies to similar posts, I don't think a mask can accomplish the task, and looping over elements in one tensor would also not work since I'd not be able to access the corresponding element in the other tensor.

任何建议将不胜感激

推荐答案

您可以使用以下方法:

def weighted_mse(yTrue,yPred):

    ones = K.ones_like(yTrue[0,:]) #a simple vector with ones shaped as (60,)
    idx = K.cumsum(ones) #similar to a 'range(1,61)'


    return K.mean((1/idx)*K.square(yTrue-yPred))

ones_likecumsum结合使用,可以将这种损失函数用于任何类型的(samples,classes)输出.

The use of ones_like with cumsum allows you to use this loss function to any kind of (samples,classes) outputs.

提示:使用张量时,始终使用后端函数.您可以使用切片,但要避免迭代.

Hint: always use backend functions when working with tensors. You can use slices, but avoid iterating.

这篇关于keras中的加权MSE自定义损失函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 20:35