Tensorflow 自定义keras训练损失函数中的数据缩减
我为我的LSTM模型(RMSE函数)定义了一个自定义损失函数,如下所示:Tensorflow 自定义keras训练损失函数中的数据缩减,tensorflow,keras,loss-function,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.reverse_transform函数,但是没有运气
def RMSE(y_true, y_pred):
return K.sqrt(K.mean(K.square(y_pred - y_true)))
到目前为止,一切都很好,但问题是我将输入数据缩放到[-1,1]的范围内,因此报告的损失将与此比例相关联,我希望模型在我的原始数据范围内报告训练损失,例如,通过在y_true和y_pred上应用scaler.reverse_transform函数,但是没有运气这么做。。。因为它们是张量和定标器。逆_变换需要numpy数组
知道如何强制重新缩放数据并以正确的比例报告损失值吗?
scaler.inverse\u transform
基本上使用scaler.min\u
和scaler.scale\u
参数在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)))
您使用的是
sklearn.preprocessing.StandardScaler
?@giser\u yugangsklearn.preprocessing.minmaxscaler