用python写一个神经网络算法示例
以下是一个使用Python编写的简单神经网络算法示例:
import numpy as np
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.bias1 = np.random.randn(self.hidden_size)
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
self.bias2 = np.random.randn(self.output_size)
def sigmoid(self, x):
# sigmoid激活函数
return 1 / (1 + np.exp(-x))
def forward(self, x):
# 正向传播
self.z1 = np.dot(x, self.weights1) + self.bias1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.sigmoid(self.z2)
return self.a2
def sigmoid_derivative(self, x):
# sigmoid激活函数的导数
return x * (1 - x)
def backward(self, x, y, output):
# 反向传播
self.error = y - output
self.delta2 = self.error * self.sigmoid_derivative(output)
self.weights2 += np.dot(self.a1.T, self.delta2)
self.bias2 += np.sum(self.delta2, axis=0)
self.delta1 = np.dot(self.delta2, self.weights2.T) * self.sigmoid_derivative(self.a1)
self.weights1 += np.dot(x.T, self.delta1)
self.bias1 += np.sum(self.delta1, axis=0)
def train(self, x, y, epochs):
# 训练神经网络
for i in range(epochs):
output = self.forward(x)
self.backward(x, y, output)
if i % 1000 == 0:
print("Epoch:", i, "Loss:", np.mean(np.abs(self.error)))
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("Predictions:", nn.predict(X))
在这个示例中,我们创建了一个具有3个输入,4个隐藏神经元和1个输出的神经网络。我们使用sigmoid激活函数,并使用随机初始化的权重和偏置。我们使用反向传播算法来训练神经网络,并使用梯度下降来更新权重和偏置。最后,我们对训练数据集进行预测,并输出结果。
原文地址: https://www.cveoy.top/t/topic/9tg 著作权归作者所有。请勿转载和采集!