bp神经网络python代码 多元
时间: 2024-04-29 08:17:51 浏览: 100
BP神经网络是一种常见的人工神经网络,可以用来解决分类和回归问题。Python中有很多第三方库可以用来实现BP神经网络,比如TensorFlow、Keras等。
以下是一个使用Python实现BP神经网络的简单示例代码:
```python
import numpy as np
# 定义激活函数sigmoid
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BPNeuralNetwork:
def __init__(self, input_dim, hidden_dim, output_dim):
self.input_dim = input_dim # 输入层维度
self.hidden_dim = hidden_dim # 隐藏层维度
self.output_dim = output_dim # 输出层维度
# 随机初始化权重
self.weights1 = np.random.randn(self.input_dim, self.hidden_dim)
self.weights2 = np.random.randn(self.hidden_dim, self.output_dim)
# 前向传播
def forward(self, X):
# 输入层到隐藏层
self.z1 = np.dot(X, self.weights1)
self.a1 = sigmoid(self.z1)
# 隐藏层到输出层
self.z2 = np.dot(self.a1, self.weights2)
self.y_hat = sigmoid(self.z2)
return self.y_hat
# 反向传播
def backward(self, X, y, y_hat, learning_rate):
# 计算输出层误差
delta2 = (y_hat - y) * y_hat * (1 - y_hat)
# 计算隐藏层误差
delta1 = np.dot(delta2, self.weights2.T) * self.a1 * (1 - self.a1)
# 更新权重
self.weights2 -= learning_rate * np.dot(self.a1.T, delta2)
self.weights1 -= learning_rate * np.dot(X.T, delta1)
# 训练模型
def train(self, X, y, epochs, learning_rate):
for i in range(epochs):
y_hat = self.forward(X)
self.backward(X, y, y_hat, learning_rate)
# 预测
def predict(self, X):
y_hat = self.forward(X)
return np.round(y_hat)
```
使用示例:
```python
# 准备数据
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([, , , ])
# 创建BP神经网络模型,输入层维度为2,隐藏层维度为4,输出层维度为1
model = BPNeuralNetwork(2, 4, 1)
# 训练模型,学习率为0.1,训练10000次
model.train(X, y, epochs=10000, learning_rate=0.1)
# 预测
y_pred = model.predict(X)
print(y_pred)
```
阅读全文