神经网络拟合正弦曲线
时间: 2024-02-02 18:09:37 浏览: 71
神经网络拟合曲线
5星 · 资源好评率100%
以下是一个使用BP人工神经网络拟合正弦曲线的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 创建训练数据
X = np.linspace(-np.pi, np.pi, 100)
y = np.sin(X)
# 构建神经网络
class NeuralNetwork:
def __init__(self):
self.input_size = 1
self.hidden_size = 10
self.output_size = 1
self.W1 = np.random.randn(self.input_size, self.hidden_size)
self.b1 = np.zeros((1, self.hidden_size))
self.W2 = np.random.randn(self.hidden_size, self.output_size)
self.b2 = np.zeros((1, self.output_size))
def forward(self, X):
self.z1 = np.dot(X, self.W1) + self.b1
self.a1 = np.tanh(self.z1)
self.z2 = np.dot(self.a1, self.W2) + self.b2
self.y_hat = np.sin(self.z2)
return self.y_hat
def backward(self, X, y, learning_rate):
delta3 = self.y_hat - y
dW2 = np.dot(self.a1.T, delta3)
db2 = np.sum(delta3, axis=0, keepdims=True)
delta2 = np.dot(delta3, self.W2.T) * (1 - np.power(self.a1, 2))
dW1 = np.dot(X.T, delta2)
db1 = np.sum(delta2, axis=0)
self.W2 -= learning_rate * dW2
self.b2 -= learning_rate * db2
self.W1 -= learning_rate * dW1
self.b1 -= learning_rate * db1
def train(self, X, y, num_epochs, learning_rate):
for epoch in range(num_epochs):
y_hat = self.forward(X)
self.backward(X, y, learning_rate)
if epoch % 100 == 0:
loss = np.mean(np.square(y_hat - y))
print(f"Epoch {epoch}, Loss: {loss}")
print("Training complete!")
# 创建神经网络对象并进行训练
nn = NeuralNetwork()
nn.train(X.reshape(-1, 1), y.reshape(-1, 1), num_epochs=1000, learning_rate=0.01)
# 使用训练好的神经网络进行预测
X_test = np.linspace(-np.pi, np.pi, 100)
y_pred = nn.forward(X_test.reshape(-1, 1))
# 绘制拟合曲线
plt.plot(X, y, label='Ground Truth')
plt.plot(X_test, y_pred, label='Predicted')
plt.legend()
plt.show()
```
这段代码使用了一个简单的单隐藏层的神经网络来拟合正弦曲线。它通过反向传播算法来更新网络的权重和偏置,以最小化预测值与真实值之间的均方误差。训练完成后,使用训练好的神经网络对新的输入数据进行预测,并将拟合曲线与真实曲线进行对比。
阅读全文