【发布时间】:2017-10-14 15:56:13
【问题描述】:
我正在尝试使用自定义损失函数在 Keras 中实现简单的线性回归。我正在计算 chi2 假设误差是函数值的 1%。我在线性模型中添加了 1% 的高斯噪声。当我使用均方误差损失函数 ('mse') 时,我可以添加 custom_loss() 函数作为度量,我看到它收敛到非常接近 1 (chi2/ndf)。如果我直接使用custom_loss()作为如下sn-p所示的损失函数,神经元的权重根本不动。
我做错了什么?
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)
【问题讨论】:
标签: machine-learning neural-network keras