我目前正在学习Keras。我的目标是创建一个简单的模型,用于预测函数的值。首先,我创建了两个数组,一个用于X值,另一个用于对应的Y值。
# declare and init arrays for training-dataX = np.arange(0.0, 10.0, 0.05)Y = np.empty(shape=0, dtype=float)# Calculate Y-Valuesfor x in X: Y = np.append(Y, float(0.05*(15.72807*x - 7.273893*x**2 + 1.4912*x**3 - 0.1384615*x**4 + 0.00474359*x**5)))
然后我创建并训练模型
# model architecturemodel = Sequential()model.add(Dense(1, input_shape=(1,)))model.add(Dense(5))model.add(Dense(1, activation='linear'))# compile modelmodel.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])# train modelmodel.fit(X, Y, epochs=150, batch_size=10)
并使用模型预测值
# declare and init arrays for predictionYPredict = np.empty(shape=0, dtype=float)# Predict YYPredict = model.predict(X)# plot training-data and predictionplt.plot(X, Y, 'C0')plt.plot(X, YPredict, 'C1')# show graphplt.show()
我得到了这样的输出(蓝色是训练数据,橙色是预测):
我哪里做错了?我猜是网络架构的基本问题,对吗?
回答:
问题确实出在你的网络架构上。具体来说,你在所有层中都使用了线性激活函数:这意味着网络只能拟合线性函数。你应该在输出层保持线性激活函数,但在隐藏层使用ReLU激活函数:
model.add(Dense(1, input_shape=(1,)))model.add(Dense(5, activation='relu'))model.add(Dense(1, activation='linear'))
然后,尝试调整隐藏层的数量和大小;我建议你多使用几个隐藏层。