bp神经网络python代码
时间: 2023-09-21 14:03:29 浏览: 64
以下是一个简单的基于Python的BP神经网络的代码实现:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BPNeuralNetwork:
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
self.lr = learning_rate
# 初始化权重矩阵
self.weights_ih = np.random.normal(0.0, pow(self.hidden_nodes, -0.5), (self.hidden_nodes, self.input_nodes))
self.weights_ho = np.random.normal(0.0, pow(self.output_nodes, -0.5), (self.output_nodes, self.hidden_nodes))
def train(self, inputs_list, targets_list):
inputs = np.array(inputs_list, ndmin=2).T
targets = np.array(targets_list, ndmin=2).T
# 前向传播
hidden_inputs = np.dot(self.weights_ih, inputs)
hidden_outputs = sigmoid(hidden_inputs)
final_inputs = np.dot(self.weights_ho, hidden_outputs)
final_outputs = sigmoid(final_inputs)
# 计算误差
output_errors = targets - final_outputs
hidden_errors = np.dot(self.weights_ho.T, output_errors)
# 反向传播
self.weights_ho += self.lr * np.dot((output_errors * final_outputs * (1 - final_outputs)), np.transpose(hidden_outputs))
self.weights_ih += self.lr * np.dot((hidden_errors * hidden_outputs * (1 - hidden_outputs)), np.transpose(inputs))
def query(self, inputs_list):
inputs = np.array(inputs_list, ndmin=2).T
# 前向传播
hidden_inputs = np.dot(self.weights_ih, inputs)
hidden_outputs = sigmoid(hidden_inputs)
final_inputs = np.dot(self.weights_ho, hidden_outputs)
final_outputs = sigmoid(final_inputs)
return final_outputs
```
使用方法:
```python
# 创建一个BP神经网络对象
input_nodes = 784
hidden_nodes = 100
output_nodes = 10
learning_rate = 0.3
nn = BPNeuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
# 训练神经网络
for record in training_data_list:
inputs = (np.asfarray(record[1:]) / 255.0 * 0.99) + 0.01
targets = np.zeros(output_nodes) + 0.01
targets[int(record[0])] = 0.99
nn.train(inputs, targets)
# 测试神经网络
scorecard = []
for record in test_data_list:
correct_label = int(record[0])
inputs = (np.asfarray(record[1:]) / 255.0 * 0.99) + 0.01
outputs = nn.query(inputs)
label = np.argmax(outputs)
if label == correct_label:
scorecard.append(1)
else:
scorecard.append(0)
scorecard_array = np.asarray(scorecard)
print("performance = ", scorecard_array.sum() / scorecard_array.size)
```
阅读全文