bp神经网络python代码
时间: 2023-08-25 21:07:38 浏览: 204
用Python实现BP神经网络(附代码)
5星 · 资源好评率100%
以下是一个简单的 Python 代码实现 BP 神经网络的例子:
```
import numpy as np
class NeuralNetwork:
def __init__(self, layers_size):
self.layers_size = layers_size
self.weights = []
self.bias = []
self.num_layers = len(layers_size)
for i in range(self.num_layers - 1):
self.weights.append(np.random.rand(layers_size[i], layers_size[i+1]))
self.bias.append(np.random.rand(layers_size[i+1]))
def sigmoid(self, x):
return 1/(1+np.exp(-x))
def feedforward(self, X):
output = X
for i in range(self.num_layers - 2):
output = self.sigmoid(np.dot(output, self.weights[i]) + self.bias[i])
output = np.dot(output, self.weights[-1]) + self.bias[-1]
return output
def backpropagation(self, X, y, learning_rate):
outputs = []
output = X
for i in range(self.num_layers - 2):
output = self.sigmoid(np.dot(output, self.weights[i]) + self.bias[i])
outputs.append(output)
output = np.dot(output, self.weights[-1]) + self.bias[-1]
outputs.append(output)
deltas = [None] * self.num_layers
deltas[-1] = y - outputs[-1]
for i in reversed(range(self.num_layers - 1)):
error = deltas[i].dot(self.weights[i].T)
deltas[i-1] = error * outputs[i-1] * (1 - outputs[i-1])
for i in range(self.num_layers - 1):
self.weights[i] += learning_rate * outputs[i].T.dot(deltas[i])
self.bias[i] += learning_rate * deltas[i]
def train(self, X, y, learning_rate=0.1, epochs=1000):
for i in range(epochs):
self.backpropagation(X, y, learning_rate)
def predict(self, X):
return self.feedforward(X)
```
以上代码实现了一个三层神经网络,可以根据输入的数据进行训练和预测。其中 `layers_size` 参数是一个数组,指定了每层神经元的数量。 `backpropagation` 方法实现了反向传播算法, `train` 方法可以用来训练模型, `predict` 方法用来进行预测。
阅读全文