在定制的keras训练损失函数中缩减数据

时间:2019-04-25 20:33:23

标签: tensorflow keras loss-function

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

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数组。 / p>

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

1 个答案:

答案 0 :(得分:1)

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

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功能中的目标。

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