在定制的keras训练损失函数中缩减数据 [英] scaling back data in customized keras training loss function

查看:122
本文介绍了在定制的keras训练损失函数中缩减数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的LSTM模型定义了定制的损失函数(RMSE函数),如下所示:

I define a customized loss function for my LSTM model (RMSE function) to be as follows:

def RMSE(y_true, y_pred):
        return K.sqrt(K.mean(K.square(y_pred - y_true)))

到目前为止一切都很好,但是问题是我将输入数据缩放到[-1,1]范围内,所以报告的损失将与此比例相关,我希望模型报告训练在原始数据范围内丢失,例如通过以某种方式在y_true和y_pred上应用scaler.inverse_transform函数,但没有运气...因为它们是张量和scaler.inverse_transform需要numpy数组....

everything good so far, but the issue is that I scale my input data to be in the range of [-1, 1], so the reported loss will be associated with this scale, I want the model to report the training loss in the range of my original data, for example by applying the scaler.inverse_transform function on the y_true and y_pred somehow, but no luck doing it... as they are tensor and the scaler.inverse_transform requires numpy array....

有什么主意如何强制重新缩放数据并以正确的比例报告损失值?

any idea how to force re-scaling the data and reporting the loss values in the right scale?

推荐答案

scaler.inverse_transform本质上使用scaler.min_scaler.scale_参数来转换sklearn.preprocessing.minmaxscaler中的数据.一个例子:

scaler.inverse_transform essentially uses scaler.min_ and scaler.scale_ parameters to convert data in sklearn.preprocessing.minmaxscaler. An example:

from sklearn.preprocessing import MinMaxScaler
import numpy as np

data = np.array([[-1, 2], [-0.5, 6], [0, 10], [1, 18]])
scaler = MinMaxScaler()
data_trans = scaler.fit_transform(data)
print('transform:\n',data_trans)

data_inverse = (data_trans - scaler.min_)/scaler.scale_
print('inverse transform:\n',data_inverse)

# print
transform:
 [[0.   0.  ]
 [0.25 0.25]
 [0.5  0.5 ]
 [1.   1.  ]]
inverse transform:
 [[-1.   2. ]
 [-0.5  6. ]
 [ 0.  10. ]
 [ 1.  18. ]]

因此,您只需要使用它们即可实现RMSE功能中的目标.

So you just need to use them to achieve your goals in RMSE function.

def RMSE_inverse(y_true, y_pred):
    y_true = (y_true - K.constant(scaler.min_)) / K.constant(scaler.scale_)
    y_pred = (y_pred - K.constant(scaler.min_)) / K.constant(scaler.scale_)
    return K.sqrt(K.mean(K.square(y_pred - y_true)))

这篇关于在定制的keras训练损失函数中缩减数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆