用最少层数训练神经网络以获得绝对函数

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

我正在尝试训练神经网络来学习 y = |x|功能。我们知道,绝对函数有两条不同的线在零点处相互连接。所以我尝试使用以下顺序模型:

隐藏层: 2 致密层(激活relu) 输出层: 1 致密层

训练模型后,它只拟合函数的一半边。大多数时候是右手边,有时是左手边。一旦我在隐藏层中再添加 1 层,那么我就用 3 层代替 2 层,它就完全符合该功能了。谁能解释为什么当绝对函数只有一次切割时需要额外的一层?

这是代码:

import numpy as np


X = np.linspace(-1000,1000,400)
np.random.shuffle(X)
Y = np.abs(X)

# Reshape data to fit the model input
X = X.reshape(-1, 1)
Y = Y.reshape(-1, 1)

import tensorflow as tf
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# Build the model
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(2, activation='relu'),
    tf.keras.layers.Dense(1)
])

# Compile the model
model.compile(optimizer='adam', loss='mse',metrics=['mae'])
model.fit(X, Y, epochs=1000)
# Predict using the model
Y_pred = model.predict(X)

# Plot the results
plt.scatter(X, Y, color='blue', label='Actual')
plt.scatter(X, Y_pred, color='red', label='Predicted')
plt.title('Actual vs Predicted')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()

2 个密集层的绘图:

3 个密集层的绘图:

python tensorflow machine-learning keras deep-learning
1个回答
0
投票

有了 2 个密集层,基本上就有一个输入层和一个输出层。这使您可以近似一阶函数,例如用于分类、回归等的线。每次迭代仅计算两次梯度,本质上为您提供两个锚点 - 非常适合线,但对于寓言来说不太好。

如果再添加一层,现在输入和输出之间就有一个隐藏层。这允许更复杂的建模,因为现在每次迭代都会计算三次梯度。通常它用于近似二阶函数,例如x^2 之类的。

np.abs(x) 类似于寓言,需要一个三层模型。如果您对神经网络如何以及为何工作感兴趣,Coursera 上有 Andrew Ng 提供的一门非常好的课程“机器学习”。如果您不需要证书,它是免费的。

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