BP神经网络分类代码
时间: 2023-10-11 17:08:10 浏览: 45
这是一个使用BP神经网络进行分类的代码示例:
```python
import numpy as np
class BPNeuralNetwork:
def __init__(self, n_feature, n_hidden, n_output):
self.n_input = n_feature
self.n_hidden = n_hidden
self.n_output = n_output
self.hidden_weights = np.random.rand(self.n_input, self.n_hidden) # 隐含层权重
self.output_weights = np.random.rand(self.n_hidden, self.n_output) # 输出层权重
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward_propagation(self, X):
hidden_output = self.sigmoid(np.dot(X, self.hidden_weights))
output = self.sigmoid(np.dot(hidden_output, self.output_weights))
return output
def backward_propagation(self, X, y, output):
output_error = y - output
output_delta = output_error * output * (1 - output)
hidden_error = np.dot(output_delta, self.output_weights.T)
hidden_delta = hidden_error * hidden_output * (1 - hidden_output)
self.output_weights += np.dot(hidden_output.T, output_delta)
self.hidden_weights += np.dot(X.T, hidden_delta)
def train(self, X, y, epochs, lr):
for epoch in range(epochs):
output = self.forward_propagation(X)
self.backward_propagation(X, y, output)
def predict(self, X):
return self.forward_propagation(X)
# 使用示例:
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # 输入数据
y = np.array([[0], [1], [1], [0]]) # 输出标签
nn = BPNeuralNetwork(n_feature=2, n_hidden=4, n_output=1) # 创建BP神经网络模型
nn.train(X, y, epochs=1000, lr=0.1) # 训练模型
test_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # 测试数据
predictions = nn.predict(test_data) # 进行预测
print(predictions)
```