BP神经网络python
时间: 2023-10-07 21:07:13 浏览: 117
您好!对于BP神经网络的实现,您可以使用Python来进行编程。以下是一个简单的示例代码,用于构建一个基本的BP神经网络:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, layers):
self.layers = layers
self.weights = []
self.biases = []
self.initialize_weights()
def initialize_weights(self):
for i in range(1, len(self.layers)):
w = np.random.randn(self.layers[i], self.layers[i-1])
b = np.zeros((self.layers[i], 1))
self.weights.append(w)
self.biases.append(b)
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def sigmoid_derivative(self, z):
return self.sigmoid(z) * (1 - self.sigmoid(z))
def feedforward(self, x):
a = x
for w, b in zip(self.weights, self.biases):
z = np.dot(w, a) + b
a = self.sigmoid(z)
return a
def train(self, x_train, y_train, epochs, learning_rate):
m = x_train.shape[1]
for epoch in range(epochs):
dw = [np.zeros(w.shape) for w in self.weights]
db = [np.zeros(b.shape) for b in self.biases]
for x, y in zip(x_train, y_train):
a = x.reshape(-1, 1)
# Forward propagation
activations = [a]
zs = []
for w, b in zip(self.weights, self.biases):
z = np.dot(w, a) + b
zs.append(z)
a = self.sigmoid(z)
activations.append(a)
# Backward propagation
delta = (activations[-1] - y.reshape(-1, 1)) * self.sigmoid_derivative(zs[-1])
dw[-1] += np.dot(delta, activations[-2].T)
db[-1] += delta
for l in range(2, len(self.layers)):
delta = np.dot(self.weights[-l+1].T, delta) * self.sigmoid_derivative(zs[-l])
dw[-l] += np.dot(delta, activations[-l-1].T)
db[-l] += delta
# Update weights and biases
for i in range(len(self.weights)):
self.weights[i] -= (learning_rate / m) * dw[i]
self.biases[i] -= (learning_rate / m) * db[i]
# 示例用法
x_train = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_train = np.array([[0], [1], [1], [0]])
layers = [2, 4, 1] # 输入层、隐藏层、输出层的神经元数量
nn = NeuralNetwork(layers)
nn.train(x_train, y_train, epochs=10000, learning_rate=0.1)
# 测试神经网络
x_test = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
for x in x_test:
print(f"Input: {x}, Predicted: {nn.feedforward(x)[0]}")
```
这个示例展示了如何使用BP神经网络来训练一个XOR逻辑门的模型。您可以根据自己的需求修改网络的层数、神经元数量、训练数据等。希望对您有所帮助!
阅读全文