给出python实现BP神经网络的代码,不使用sklearn库,完成对二分类任务
时间: 2024-05-03 14:20:39 浏览: 51
Python实现BP神经网络预测
好的,请参考下面的代码实现:
```python
import numpy as np
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.learning_rate = learning_rate
self.weights_input_hidden = np.random.normal(0.0, pow(self.input_nodes, -0.5), (self.input_nodes, self.hidden_nodes))
self.weights_hidden_output = np.random.normal(0.0, pow(self.hidden_nodes, -0.5), (self.hidden_nodes, self.output_nodes))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
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_input_hidden.T, inputs)
hidden_outputs = self.sigmoid(hidden_inputs)
final_inputs = np.dot(self.weights_hidden_output.T, hidden_outputs)
final_outputs = self.sigmoid(final_inputs)
output_errors = targets - final_outputs
hidden_errors = np.dot(self.weights_hidden_output, output_errors)
self.weights_hidden_output += self.learning_rate * np.dot((output_errors * final_outputs * (1 - final_outputs)), hidden_outputs.T)
self.weights_input_hidden += self.learning_rate * np.dot((hidden_errors * hidden_outputs * (1 - hidden_outputs)), inputs.T)
def query(self, inputs_list):
inputs = np.array(inputs_list, ndmin=2).T
hidden_inputs = np.dot(self.weights_input_hidden.T, inputs)
hidden_outputs = self.sigmoid(hidden_inputs)
final_inputs = np.dot(self.weights_hidden_output.T, hidden_outputs)
final_outputs = self.sigmoid(final_inputs)
return final_outputs
```
其中,input_nodes、hidden_nodes、output_nodes分别代表输入层、隐层、输出层的节点数;learning_rate为学习率。train方法用于对神经网络进行训练,inputs_list和targets_list分别为训练数据和目标数据。query方法用于对新数据进行预测。
阅读全文