用Python写一个3*4*5*1的BP神经网络模型
时间: 2023-11-14 10:35:22 浏览: 81
基于python实现BP神经网络
好的,我可以提供一些python的代码。首先,需要导入一些必要的库,如numpy等。
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class NeuralNetwork:
def __init__(self):
# 初始化神经网络的结构
self.input_size = 3
self.hidden_size = 4
self.output_size = 5
# 随机初始化权重
self.weights_1 = np.random.randn(self.input_size, self.hidden_size)
self.weights_2 = np.random.randn(self.hidden_size, self.output_size)
def forward(self, inputs):
# 前向传播
self.hidden = sigmoid(np.dot(inputs, self.weights_1))
self.output = sigmoid(np.dot(self.hidden, self.weights_2))
return self.output
def backward(self, inputs, targets, lr):
# 后向传播
error = targets - self.output
output_delta = error * self.output * (1 - self.output)
hidden_error = np.dot(output_delta, self.weights_2.T)
hidden_delta = hidden_error * self.hidden * (1 - self.hidden)
self.weights_2 += lr * np.dot(self.hidden.T, output_delta)
self.weights_1 += lr * np.dot(inputs.T, hidden_delta)
def train(self, inputs, targets, lr, epochs):
for i in range(epochs):
# 训练神经网络
self.forward(inputs)
self.backward(inputs, targets, lr)
def predict(self, inputs):
# 预测结果
return self.forward(inputs)
nn = NeuralNetwork()
inputs = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
targets = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0]])
nn.train(inputs, targets, 0.1, 1000)
test_inputs = np.array([[1, 2, 3]])
print(nn.predict(test_inputs))
阅读全文