给一个python的BP神经网络算法
时间: 2023-02-28 07:59:15 浏览: 113
BP(反向传播)神经网络算法是一种常用的人工神经网络训练方法,其通过反向传播算法不断修正权值以提高模型的预测准确度。
以下是一个使用 Python 实现 BP 神经网络算法的示例代码:
```
import numpy as np
class NeuralNetwork:
def __init__(self, layers, alpha=0.1):
# 初始化每层的节点数
self.layers = layers
self.alpha = alpha
# 初始化权重和偏移量
self.weights = [np.random.randn(y, x) for x, y in zip(layers[:-1], layers[1:])]
self.biases = [np.random.randn(y, 1) for y in layers[1:]]
def sigmoid(self, x):
return 1.0 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def fit(self, X, y, epochs=1000):
for epoch in range(epochs):
# 前向传播
a = [X]
for w, b in zip(self.weights, self.biases):
z = np.dot(w, a[-1]) + b
a.append(self.sigmoid(z))
# 计算误差
error = y - a[-1]
deltas = [error * self.sigmoid_derivative(a[-1])]
# 反向传播
for i in range(len(a) - 2, 0, -1):
delta = np.dot(self.weights[i].T, deltas[-1]) * self.sigmoid_derivative(a[i])
deltas.append(delta)
deltas.reverse()
# 更新权重和偏移量
for i in range(len(self.weights)):
a_i = np.atleast_2d(a[i])
delta_i = np.atleast_2d(deltas[i])
self.weights[i] += self.alpha * np.dot(delta_i, a_i.T)
self.biases[i] += self.alpha * delta_i.sum(axis=1