1.argmax()方法:
>>> import torch
>>> import torch.nn.functional as F
>>> logits = torch.rand(4,10)
>>> pred = F.softmax(logits,dim=1)
>>> pred.shape
torch.Size([4, 10])
# 使用argmax(dim=1)方法取出dim=1维度的最大值所在位置
# 返回的结果就是每个的预测值
>>> pred_label = pred.argmax(dim=1)
>>> pred_label
tensor([0, 4, 7, 3])
# 对logits做还是对logits之后的值做argmax,返回的结果都是一样的
>>> logits.argmax(dim=1)
tensor([0, 4, 7, 3])
>>> label = torch.tensor([9,4,2,3])
# 使用eq()方法,判断元素是否相等
>>> correct = torch.eq(pred_label,label)
>>> correct
tensor([0, 1, 0, 1], dtype=torch.uint8)
# 计算准确率accuracy
# 上述eq()方法得到的值取sum,就得到预测正确的数量
# .item()取numpy值,因为其实一个tensor
>>> correct.sum().float().item()/4
0.5
2.MNIST数据集实战求解Accuracy:
import torch
import torch.nn.functional as F
from torch import nn
from torch import optim
from torchvision import datasets, transforms
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.module = nn.Sequential(
nn.Linear(784, 200),
nn.ReLU(inplace=True),
nn.Linear(200, 200),
nn.ReLU(inplace=True),
nn.Linear(200, 10),
nn.ReLU(inplace=True)
)
def forward(self, x):
x = self.module(x)
return x
batch_size = 200
learning_rate = 0.01
epochs = 10
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
net = MLP()
optimizer = optim.SGD(net.parameters(), lr=learning_rate)
Loss = nn.CrossEntropyLoss()
for epoch in range(epochs):
for batch_idx, (data, target) in enumerate(train_loader):
data = data.reshape(-1, 28 * 28)
logits = net(data)
loss = Loss(logits, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
# 上面为train过程
test_loss = 0
correct = 0
for data, target in test_loader:
data = data.reshape(-1, 28 * 28)
logits = net(data)
test_loss += Loss(logits, target).item()
# 对logits做argmax操作
pred = logits.data.argmax(dim=1)
correct += pred.eq(target.data).sum()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
运行得到如下结果,可以看到得到了test过程总的Accuracy:
Train Epoch: 0 [0/60000 (0%)] Loss: 2.303407
Train Epoch: 0 [20000/60000 (33%)] Loss: 1.977869
Train Epoch: 0 [40000/60000 (67%)] Loss: 1.269896
Test set: Average loss: 0.0047, Accuracy: 7757/10000 (77%)
Train Epoch: 1 [0/60000 (0%)] Loss: 1.018467
Train Epoch: 1 [20000/60000 (33%)] Loss: 0.713700
......(略)