bp神经网络识别代码
时间: 2024-04-16 19:21:08 浏览: 109
BP神经网络是一种常用的人工神经网络模型,用于解决分类和回归问题。下面是一个简单的BP神经网络识别代码的示例:
```python
import numpy as np
# 定义激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class NeuralNetwork:
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 = sigmoid(self.z2)
return self.a2
def backward(self, X, y, learning_rate):
# 反向传播
m = X.shape[0]
# 计算输出层的误差
delta2 = self.a2 - y
# 计算隐藏层的误差
delta1 = np.dot(delta2, self.W2.T) * (self.a1 * (1 - self.a1))
# 更新权重和偏置
dW2 = np.dot(self.a1.T, delta2) / m
db2 = np.sum(delta2, axis=0) / m
dW1 = np.dot(X.T, delta1) / m
db1 = np.sum(delta1, axis=0) / m
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, epochs, learning_rate):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, learning_rate)
def predict(self, X):
return np.round(self.forward(X))
# 创建一个BP神经网络实例
input_size = 2
hidden_size = 4
output_size = 1
nn = NeuralNetwork(input_size, hidden_size, output_size)
# 定义训练数据集
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# 训练神经网络
nn.train(X, y, epochs=10000, learning_rate=0.1)
# 预测新样本
new_X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
predictions = nn.predict(new_X)
print(predictions)
```
这段代码实现了一个简单的BP神经网络,用于解决异或逻辑门问题。代码中定义了激活函数sigmoid,以及BP神经网络类NeuralNetwork。通过调用train方法进行训练,然后使用predict方法进行预测。
阅读全文