Python构建一个BP神经网络的代码
时间: 2023-06-12 20:02:23 浏览: 108
以下是Python构建一个BP神经网络的代码:
```
import numpy as np
# 构建 BP 神经网络类
class BPNeuralNetwork(object):
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.weights_input_hidden = np.random.randn(self.input_size, self.hidden_size) * 0.01
self.bias_hidden = np.zeros((1, self.hidden_size))
self.weights_hidden_output = np.random.randn(self.hidden_size, self.output_size) * 0.01
self.bias_output = np.zeros((1, self.output_size))
# 定义 sigmoid 函数
def sigmoid(self, x):
return 1.0 / (1.0 + np.exp(-x))
# 定义 sigmoid 的导数函数
def sigmoid_derivative(self, x):
return x * (1.0 - x)
def train(self, X, y, epochs, learning_rate):
for i in range(epochs): # 迭代次数
# 正向传播
hidden_layer_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
hidden_layer_output = self.sigmoid(hidden_layer_activation)
output_layer_activation = np.dot(hidden_layer_output, self.weights_hidden_output) + self.bias_output
predicted_output = self.sigmoid(output_layer_activation)
# 反向传播
error = y - predicted_output
d_predicted_output = error * self.sigmoid_derivative(predicted_output)
error_hidden_layer = d_predicted_output.dot(self.weights_hidden_output.T)
d_hidden_layer = error_hidden_layer * self.sigmoid_derivative(hidden_layer_output)
# 更新权重和偏置
self.weights_hidden_output += hidden_layer_output.T.dot(d_predicted_output) * learning_rate
self.bias_output += np.sum(d_predicted_output, axis=0, keepdims=True) * learning_rate
self.weights_input_hidden += X.T.dot(d_hidden_layer) * learning_rate
self.bias_hidden += np.sum(d_hidden_layer, axis=0, keepdims=True) * learning_rate
# 预测
def predict(self, X):
hidden_layer_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
hidden_layer_output = self.sigmoid(hidden_layer_activation)
output_layer_activation = np.dot(hidden_layer_output, self.weights_hidden_output) + self.bias_output
predicted_output = self.sigmoid(output_layer_activation)
return predicted_output
```
以上是构建 BP 神经网络的 Python 代码,可以通过该类进行训练和预测。
阅读全文