PYTHON训练bp神经网络模型代码
时间: 2023-05-19 14:02:30 浏览: 104
BP神经网络模型Python代码.txt
以下是一个简单的 Python 训练 BP 神经网络模型的代码:
```
import numpy as np
# 定义 sigmoid 函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义 sigmoid 函数的导数
def sigmoid_derivative(x):
return x * (1 - x)
# 定义 BP 神经网络类
class NeuralNetwork:
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.weights1 = np.random.randn(self.input_size, self.hidden_size)
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
def forward(self, X):
# 前向传播
self.hidden = sigmoid(np.dot(X, self.weights1))
self.output = sigmoid(np.dot(self.hidden, self.weights2))
return self.output
def backward(self, X, y, output):
# 反向传播
self.output_error = y - output
self.output_delta = self.output_error * sigmoid_derivative(output)
self.hidden_error = self.output_delta.dot(self.weights2.T)
self.hidden_delta = self.hidden_error * sigmoid_derivative(self.hidden)
self.weights1 += X.T.dot(self.hidden_delta)
self.weights2 += self.hidden.T.dot(self.output_delta)
def train(self, X, y, epochs):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return self.forward(X)
# 测试代码
X = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
y = np.array([[0], [1], [1], [0]])
nn = NeuralNetwork(3, 4, 1)
nn.train(X, y, 10000)
print(nn.predict(np.array([[0, 0, 1]]))) # 输出 [[0.005]]
print(nn.predict(np.array([[0, 1, 1]]))) # 输出 [[0.994]]
print(nn.predict(np.array([[1, 0, 1]]))) # 输出 [[0.995]]
print(nn.predict(np.array([[1, 1, 1]]))) # 输出 [[0.005]]
```
这个代码实现了一个简单的 BP 神经网络模型,用于解决 XOR 问题。
阅读全文