你好我想要一个python的torch实现的简易神经网络
好的,以下是一个简单的神经网络实现示例:
import torch
# 定义神经网络模型
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = torch.nn.Linear(2, 10) # 输入层到隐藏层
self.relu = torch.nn.ReLU() # 激活函数
self.fc2 = torch.nn.Linear(10, 1) # 隐藏层到输出层
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# 训练数据
x_train = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float)
y_train = torch.tensor([[0], [1], [1], [0]], dtype=torch.float)
# 定义损失函数和优化器
net = Net()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
# 训练模型
for epoch in range(5000):
optimizer.zero_grad() # 梯度清零
output = net(x_train) # 前向传播
loss = criterion(output, y_train) # 计算损失函数
loss.backward() # 反向传播
optimizer.step() # 更新参数
if (epoch + 1) % 1000 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 5000, loss.item()))
# 测试模型
with torch.no_grad():
x_test = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float)
y_test = net(x_test)
print(y_test)
这个神经网络模型是一个两层的全连接神经网络,使用ReLU作为激活函数,输入维度是2,输出维度是1。训练数据是逻辑异或(xor)的数据,最终输出的结果应该接近于[[0], [1], [1], [0]]。模型训练5000个epoch,每1000个epoch输出一次损失函数的值。最后使用训练好的模型进行测试,输出预测的结果
原文地址: https://www.cveoy.top/t/topic/ciOu 著作权归作者所有。请勿转载和采集!