PyTorch是一个流行的深度学习框架,可以用于构建和训练前馈神经网络(Feedforward Neural Network)。评估和获得前馈神经网络的精度可以通过以下步骤实现:
import torch
import torch.nn as nn
import torch.optim as optim
class FeedforwardNN(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(FeedforwardNN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
input_size = 784 # 输入特征的大小(例如MNIST数据集的图像大小为28x28,展开后为784)
hidden_size = 128 # 隐藏层的大小
num_classes = 10 # 分类的数量(例如MNIST数据集有10个类别)
learning_rate = 0.001 # 学习率
num_epochs = 10 # 训练的轮数
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=100, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=100, shuffle=False)
model = FeedforwardNN(input_size, hidden_size, num_classes)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.reshape(-1, input_size)
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
model.eval() # 设置模型为评估模式
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.reshape(-1, input_size)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('精度: {}%'.format(100 * correct / total))
这样,我们就可以使用PyTorch评估和获得前馈神经网络的精度了。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云