bp神经网络python代码实例
时间: 2024-04-26 09:18:44 浏览: 174
当然可以!下面是一个简单的用Python实现的BP神经网络的代码示例:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, layers):
self.layers = layers
self.weights = [np.random.randn(layers[i], layers[i+1]) for i in range(len(layers)-1)]
self.biases = [np.random.randn(1, layers[i+1]) for i in range(len(layers)-1)]
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def feed_forward(self, X):
activations = [X]
for i in range(len(self.layers)-1):
activation = self.sigmoid(np.dot(activations[i], self.weights[i]) + self.biases[i])
activations.append(activation)
return activations
def back_propagation(self, X, y, learning_rate):
activations = self.feed_forward(X)
deltas = [activations[-1] - y]
for i in range(len(self.layers)-2, 0, -1):
delta = np.dot(deltas, self.weights[i].T) * self.sigmoid_derivative(activations[i])
deltas.insert(0, delta)
for i in range(len(self.layers)-1):
self.weights[i] -= learning_rate * np.dot(activations[i].T, deltas[i])
self.biases[i] -= learning_rate * np.sum(deltas[i], axis=0)
def train(self, X, y, epochs, learning_rate):
for epoch in range(epochs):
self.back_propagation(X, y, learning_rate)
print("Training completed!")
def predict(self, X):
activations = self.feed_forward(X)
return activations[-1]
# 使用示例
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([, , , ])
nn = NeuralNetwork([2, 4, 1]) # 创建一个有2个输入节点,4个隐藏节点和1个输出节点的神经网络
nn.train(X, y, epochs=10000, learning_rate=0.1) # 训练神经网络
print(nn.predict(X)) # 预测输出
```
这段代码实现了一个具有2个输入节点、4个隐藏节点和1个输出节点的BP神经网络。使用sigmoid作为激活函数,并使用随机初始化的权重和偏置项进行训练。在示例中,我们使用XOR逻辑门的数据进行训练和预测。
阅读全文