Python实现2输入层3输出层BP神经网络代码
下面是一个简单的2输入层,3输出层的BP神经网络的代码示例:
import numpy as np
# 定义激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义神经网络类
class NeuralNetwork:
def __init__(self, input_size, output_size):
self.input_size = input_size
self.output_size = output_size
# 初始化权重和偏置
self.weights1 = np.random.randn(self.input_size, self.output_size)
self.bias1 = np.random.randn(self.output_size)
def forward(self, X):
# 前向传播
self.z = np.dot(X, self.weights1) + self.bias1
self.output = sigmoid(self.z)
return self.output
def backward(self, X, y, output):
# 反向传播
self.error = output - y
self.gradient = sigmoid(self.z) * (1 - sigmoid(self.z))
self.weights1 -= np.dot(X.T, self.error * self.gradient)
self.bias1 -= np.sum(self.error * self.gradient, axis=0)
def train(self, X, y, epochs):
for epoch in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
output = self.forward(X)
predictions = np.round(output)
return predictions
# 创建神经网络对象
nn = NeuralNetwork(2, 3)
# 定义输入和输出数据
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
# 训练神经网络
nn.train(X, y, epochs=10000)
# 预测新数据
new_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
predictions = nn.predict(new_data)
print(predictions)
这段代码创建了一个2输入层,3输出层的BP神经网络对象,并使用训练数据进行训练。然后,使用训练好的神经网络对象对新数据进行预测,并输出预测结果。
原文地址: https://www.cveoy.top/t/topic/fM1v 著作权归作者所有。请勿转载和采集!