bp神经网络拟合正弦曲线,Python
时间: 2023-07-08 07:31:35 浏览: 54
以下是一个使用Python和Numpy库来实现一个bp神经网络拟合正弦曲线的示例代码:
```python
import numpy as np
# 准备数据
X = np.arange(0, 2*np.pi, 0.1)
y = np.sin(X)
# 设计网络结构
input_layer_size = 1
hidden_layer_size = 10
output_layer_size = 1
learning_rate = 0.01
num_iterations = 10000
# 初始化权重与偏置
W1 = np.random.randn(hidden_layer_size, input_layer_size)
b1 = np.zeros((hidden_layer_size, 1))
W2 = np.random.randn(output_layer_size, hidden_layer_size)
b2 = np.zeros((output_layer_size, 1))
# 训练模型
for i in range(num_iterations):
# 前向传播
z1 = np.dot(W1, X.reshape(1,-1)) + b1
a1 = np.tanh(z1)
z2 = np.dot(W2, a1) + b2
y_hat = z2
# 计算损失
cost = np.mean((y - y_hat)**2)
# 反向传播
delta2 = y_hat - y
delta1 = np.dot(W2.T, delta2) * (1 - np.power(a1, 2))
# 更新权重与偏置
dW2 = np.dot(delta2, a1.T)
db2 = np.sum(delta2, axis=1, keepdims=True)
dW1 = np.dot(delta1, X.reshape(1,-1))
db1 = np.sum(delta1, axis=1, keepdims=True)
W2 -= learning_rate * dW2
b2 -= learning_rate * db2
W1 -= learning_rate * dW1.T
b1 -= learning_rate * db1
# 输出损失
if i % 1000 == 0:
print("Iteration:", i, "Cost:", cost)
# 预测结果
z1 = np.dot(W1, X.reshape(1,-1)) + b1
a1 = np.tanh(z1)
z2 = np.dot(W2, a1) + b2
y_hat = z2
# 输出结果
print(y_hat)
```
在这个示例代码中,我们首先生成了一些正弦曲线的数据作为训练集,然后使用Numpy库来实现了一个包含一个10个节点的隐藏层的bp神经网络。我们使用均方误差作为损失函数,使用梯度下降算法进行权重更新。训练模型时,我们将训练集输入到网络中,并迭代10000次进行训练。最后,我们使用训练好的模型来预测结果,并输出结果。
需要注意的是,这只是一个简单的示例,实际上,更复杂的神经网络结构和更多的训练数据可能会得到更好的结果。