为什么神经网络不学习曲线?

时间:2019-11-16 03:29:56

标签: python tensorflow

出于实验目的,我使用tf.keras构建了一个神经网络,其中一个神经元附着在S形上。要学习的目标曲线是:

#target function
f = lambda x:  - 1./(np.exp(10.*x)+1.)

我从曲线上采样了一些点作为训练数据。

#creat training data

x_train = np.linspace(-1, 1, 111)
y_train = f(x_train)


#test data

x_test = np.linspace(-1, 1, 11)
y_test = f(x_test)

模型如下:

model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(1, activation='sigmoid', input_shape=(1,), use_bias=True)
])

model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
              loss='mse',
              metrics=['MeanAbsoluteError'])

但是它不学习曲线。测试代码是

x_test = np.linspace(-1, 1, 11)
plt.plot(x_test, f(x_test), label='true')
y_pred = model.predict(x_test)
plt.plot(x_test, y_pred, label='predict')
plt.legend()
plt.show()

enter image description here

该代码由colab共享,请参见

https://colab.research.google.com/drive/1LQ9MXjrMxsImc80o6wMk1oKfeadnNaG3

会有明显的错误,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

sigmoid激活功能只能输出0到1之间的值。由于f(x)的所有值均为负,因此无法学习该功能。

一种解决方法是简单地将值归一化为[0, 1]。就您而言,只需学习f = lambda x: 1./(np.exp(10.*x)+1.)即可。