给我一个神经网络的python程序demo
这是一个简单的神经网络的Python程序demo:
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义sigmoid函数的导数
def sigmoid_derivative(x):
return x * (1 - x)
# 定义神经网络类
class NeuralNetwork:
def __init__(self, x, y):
self.input = x
self.weights1 = np.random.rand(self.input.shape[1], 4)
self.weights2 = np.random.rand(4, 1)
self.y = y
self.output = np.zeros(self.y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))
self.weights1 += d_weights1
self.weights2 += d_weights2
# 输入数据
X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
y = np.array([[0],[1],[1],[0]])
# 定义神经网络
nn = NeuralNetwork(X, y)
# 训练神经网络
for i in range(1500):
nn.feedforward()
nn.backprop()
# 输出结果
print(nn.output)
这个程序实现了一个简单的神经网络,使用sigmoid函数作为激活函数,使用反向传播算法进行训练。程序的输入数据是一个4x3的矩阵X和一个4x1的矩阵y,表示4个样本的特征和标签。程序训练1500次后输出神经网络的预测结果
原文地址: https://www.cveoy.top/t/topic/e9Az 著作权归作者所有。请勿转载和采集!