Keras神经网络函数逼近

问题描述 投票:0回答:3

我正在尝试近似以下函数:

但我最好的结果是这样的:

(右边的损失函数) 我什至尝试过 50k 个时期,结果相似。

型号:

model = Sequential()
model.add(Dense(40, input_dim=1,kernel_initializer='he_normal', activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1,input_dim=1, activation=activation_fun))
model.compile(loss='mse', optimizer='adam', metrics=['mse', 'mae', 'mape', 'cosine'])
history = model.fit(x, y, batch_size=32, epochs=5000, verbose=0)

preds = model.predict(x_test)
prettyPlot(x,y,x_test,preds,history,'linear',5000)
model.summary()

prettyPlot 函数创建绘图。

如何在不改变神经网络拓扑结构的情况下取得更好的效果?我不希望它变大或变宽。如果可能的话,我想使用更少的隐藏层和神经元。

我要逼近的函数:

def fun(X):
    return math.sin(1.2*X + 0.5) + math.cos(2.5*X + 0.2) + math.atan(2*X + 1) -  math.cos(2*X + 0.5) 

样品:

range = 20
x = np.arange(0, range, 0.01).reshape(-1,1)
y = np.array(list(map(fun, x))).reshape(-1,1)

x_test = (np.random.rand(range*10)*range).reshape(-1,1)
y_test = np.array(list(map(fun, x_test))).reshape(-1,1)

然后使用 MinMaxScaler 对 y 和 y_test 进行归一化。

scalerY= MinMaxScaler((0,1))
scalerY.fit(y)
scalerY.fit(y_test)
y = scalerY.transform(y)
y_test = scalerY.transform(y_test)

最后一层的激活函数是线性的。

neural-network keras
3个回答
1
投票

如果您仍然对准确性有疑问,请尝试使用大量数据点,例如 10k-100k。


0
投票

有相同的任务,你应该在输出层使用“tanh”激活函数(或者只使用一层)


0
投票

请原谅,我是这个领域的新手,大约 2-3 天前才开始研究 AI 模型 然而,我也试图在我的电脑上解决上述问题,我认为 OP 的模型有一些问题

  • 模型的第一层存在“dying ReLU”问题,用 LeakyReLU 替换它可以解决
  • 不需要接下来的两个隐藏的 relu 层,因为我看不到它们会完成什么。与第一个 relu 层不同的是,第一个 relu 层将区分图中的每个山丘和山谷,并将输入路由到下一层中的适当神经元
  • 下一层可以只是一个 tanh 层,由于它的形状可以合理地近似山丘或山谷
  • 我数了一下我们要拟合的函数中大约有 18 个山丘和山谷,因此第一层可能有 18 个神经元/单元。但在我的测试中,大约 20 个给出了不错的结果,而 30 个给出了足够的余地,可以在合理的时间内获得完美的结果。
  • 给出了这个模型:
epochs = 16000
bs = 200

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=1),
    tf.keras.layers.Dense(units=30, kernel_initializer="random_uniform"),  
    tf.keras.layers.LeakyReLU(alpha=0.15),
    tf.keras.layers.Dense(units=30, activation="tanh"),
    
    tf.keras.layers.Dense(units=1)
])

opt = tf.keras.optimizers.RMSprop(learning_rate=.001, momentum=0.9)
model.compile(optimizer=opt, loss='mean_squared_error')

es = tf.keras.callbacks.EarlyStopping(monitor="loss", mode="min", verbose=1, patience=5000, min_delta=0.0001, baseline=None)
cblist = [es]
model.fit(xs, ys, epochs=epochs, batch_size=bs, callbacks=cblist)

fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(in1, out1, color="green")
ax.plot(in1, preds, color="red")
fig.tight_layout()
plt.show(block=True)

in1 和 out2 正在使用我们试图匹配的 OPs 函数,有 200 个数据样本 我发现像 OP 使用的批量大小为 32 会产生太不稳定的损失值,并且只需将整个数据集批量化(基本上每个时期一个批次)就可以产生更好的结果。近乎完美的匹配,损失 0.082:

希望这会有所帮助,如果我的任何陈述有误,请告诉我,我是新手,渴望学习。

© www.soinside.com 2019 - 2024. All rights reserved.