我试图使用自定义损失函数在Keras中实现一个简单的线性回归。假设错误为函数值的1%,我正在计算chi2。我将1%高斯噪声加到线性模型中。当我使用均方误差损失函数('mse')时,我可以添加custom_loss()函数作为度量,并且我看到它收敛到非常接近1 (chi2/ndf)。如果我直接使用custom_loss()作为损失函数,如下面的片段所示,神经元的重量根本不会移动。
我做错了什么?
from keras.models import Sequential
from keras.layers import Dense
from keras import optimizers
from keras import backend as K
import numpy as np
def custom_loss(y_true, y_pred):
return K.mean(K.square(y_pred-y_true)/K.clip(K.square(0.01*y_pred), K.epsilon(), None), axis=-1)
def build_model():
model = Sequential()
model.add(Dense(1, input_dim=1, activation='linear'))
sgd = optimizers.SGD(lr=0.01, momentum=0.01, nesterov=False)
model.compile(optimizer=sgd, loss=custom_loss, metrics=['mape', 'mse', custom_loss])
return model
if __name__ == '__main__':
model = build_model()
x_train = np.linspace(0.0, 1.0, 500)
y_train = np.array(map(lambda x: x + 0.01*x*np.random.randn(1), x_train))
model.fit(x_train, y_train, shuffle=True, epochs=1000, batch_size=10)
https://stackoverflow.com/questions/43986699
复制相似问题