使用BP算法拟合曲面代码
时间: 2023-06-20 15:03:43 浏览: 97
以下是一个使用BP算法拟合曲面的Python代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义sigmoid激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP算法类
class BPNet(object):
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
# 初始化权重和偏置
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 = sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.W2) + self.b2
self.a2 = self.z2
return self.a2
# 反向传播函数
def backward(self, X, y, learning_rate):
loss = np.mean((self.a2 - y) ** 2)
delta_a2 = self.a2 - y
delta_z2 = delta_a2
delta_W2 = np.dot(self.a1.T, delta_z2)
delta_b2 = np.sum(delta_z2, axis=0, keepdims=True)
delta_a1 = np.dot(delta_z2, self.W2.T)
delta_z1 = delta_a1 * sigmoid(self.z1) * (1 - sigmoid(self.z1))
delta_W1 = np.dot(X.T, delta_z1)
delta_b1 = np.sum(delta_z1, axis=0)
self.W1 -= learning_rate * delta_W1
self.b1 -= learning_rate * delta_b1
self.W2 -= learning_rate * delta_W2
self.b2 -= learning_rate * delta_b2
return loss
# 训练函数
def train(self, X, y, learning_rate, epochs):
losses = []
for i in range(epochs):
loss = self.backward(X, y, learning_rate)
losses.append(loss)
if i % 1000 == 0:
print('Epoch:', i, 'Loss:', loss)
return losses
# 生成训练数据
x = np.linspace(-1, 1, 100)
y = np.linspace(-1, 1, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
# 归一化处理
X = X.reshape(-1, 1)
Y = Y.reshape(-1, 1)
Z = Z.reshape(-1, 1)
X = (X - np.mean(X)) / np.std(X)
Y = (Y - np.mean(Y)) / np.std(Y)
Z = (Z - np.mean(Z)) / np.std(Z)
# 构建BP网络
net = BPNet(2, 10, 1)
# 训练BP网络
losses = net.train(np.hstack((X, Y)), Z, 0.1, 10000)
# 绘制训练误差曲线
plt.plot(losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
# 绘制拟合曲面
Z_hat = net.forward(np.hstack((X, Y)))
Z_hat = Z_hat.reshape(100, 100)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z_hat)
plt.show()
```
该代码使用BP算法拟合了一个二元二次函数曲面。首先生成训练数据,然后使用归一化处理将输入和输出数据进行标准化。接着构建一个输入层为2,隐藏层为10,输出层为1的BP网络,并使用训练数据对该网络进行训练。最后绘制训练误差曲线和拟合曲面。
阅读全文