gpt4 book ai didi

python - 如何使用 Keras 预测函数/表?

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:53 24 4
gpt4 key购买 nike

我目前正在学习keras。我的目标是创建一个简单的模型来预测函数的值。首先我创建了两个数组,一个用于 X 值,一个用于相应的 Y 值。

# declare and init arrays for training-data
X = np.arange(0.0, 10.0, 0.05)
Y = np.empty(shape=0, dtype=float)

# Calculate Y-Values
for 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 architecture
model = Sequential()
model.add(Dense(1, input_shape=(1,)))
model.add(Dense(5))
model.add(Dense(1, activation='linear'))

# compile model
model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])

# train model
model.fit(X, Y, epochs=150, batch_size=10)

并使用模型预测值

# declare and init arrays for prediction
YPredict = np.empty(shape=0, dtype=float)

# Predict Y
YPredict = model.predict(X)

# plot training-data and prediction
plt.plot(X, Y, 'C0')
plt.plot(X, YPredict, 'C1')

# show graph
plt.show()

我得到了这个输出(蓝色是训练数据,橙色是预测):

link

我做错了什么?我想这是网络架构的一个基本问题,对吧?

最佳答案

问题确实出在您的网络架构上。具体来说,您在所有层中都使用线性激活:这意味着网络只能拟合线性函数。你应该在输出层保持线性激活,但你应该在隐藏层使用 ReLU 激活:

model.add(Dense(1, input_shape=(1,)))
model.add(Dense(5, activation='relu'))
model.add(Dense(1, activation='linear'))

然后,调整隐藏层的数量/大小;我建议你多用几个。

关于python - 如何使用 Keras 预测函数/表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48486598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com