Size
[1,2,3]
[[1,2,3]]
[[1],[2],[3]]
分类top1 Demo:
for i, (inputs, labels) in enumerate(train_loader, 0):
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs,labels)
loss.backward()
optimizer.step()
_, predicted = torch.max(outputs.data, dim=1)
total = labels.size(0)
correct = predicted.eq(labels.data).cpu().sum()
"""
topk会保持维度,不降维
k表示topk
dim维度,dim=1,一行中取topk,dim=0,每一列取topk
largest = True,从大到小排序,反之从小到大排序
sorted=True,按顺序返回结果
当maxk=1时,等同于 _, predicted = torch.max(outputs.data, dim=1, keepdim=True)
"""
_, topk_predicted = outputs.top(k=1,dim=1,largest=True,sorted=True)
topk_predicted = topk_predicted.t()
correct = topk_predicted.eq(labels.reshape(1,-1))
correct = correct[:1].reshape(-1).float().sum(0).cpu()
if i % 200 == 0:
print('Acc: {:.4f}'.format(correct/total))
分类top5 Demo:
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
maxk = min(max(topk), output.size()[1])
batch_size = target.size(0)
_, pred = output.topk(k=maxk,dim=1,largest=True,sorted=True)
pred = pred.t()
correct = pred.eq(target.reshape(1, -1).expand_as(pred))
return [correct[:min(k, maxk)].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
...
for i, (inputs, labels) in enumerate(train_loader, 0):
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs,labels)
loss.backward()
optimizer.step()
acc1, acc5 = accuracy(outputs, labels, topk=(1, 5))