Top k error calculation

Soumyajit_Das: <p>import torch<br>
import torchvision<br>
import torchvision.transforms as transforms<br>
<span class="hashtag">#from</span> torch.autograd import Variable</p>
<p>transform=transforms.Compose([transforms.Resize(256),transforms.ToTensor(),<br>
transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])</p>
<p>trainset = torchvision.datasets.CIFAR10(root=’./data’, train=True,<br>
download=True, transform=transform)</p>
<p>trainloader=torch.utils.data.DataLoader(trainset,batch_size=4,shuffle=True,<br>
num_workers=2)</p>
<p>testset = torchvision.datasets.CIFAR10(root=’./data’, train=False,<br>
download=True, transform=transform)</p>
<p>testloader=torch.utils.data.DataLoader(testset,batch_size=4,shuffle=False,<br>
num_workers=2)</p>
<p>classes=(‘plane’,‘car’,‘bird’,‘cat’,‘deer’,‘dog’,‘frog’,‘horse’,‘ship’,‘truck’)</p>
<p>import torch.nn as nn<br>
import torch.nn.functional as F</p>
<p>device=torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)</p>
<p>import torchvision.models as models<br>
alexnet=models.alexnet(pretrained=True)<br>
alexnet.classifier[6]=nn.Linear(4096,10)<br>
print(alexnet)<br>
print(‘Model Downloaded’)</p>
<p>class CifarAlexnet(nn.Module):</p>
<pre><code>    def __init__(self,alexnet):
        super(CifarAlexnet,self).__init__()
        self.alexnet=alexnet

    def forward(self,x):
        return self.alexnet(x)
</code></pre>
<p>model=CifarAlexnet(alexnet)<br>
print(model)</p>
<p>import time<br>
import torch.optim as optim</p>
<p>batch_size=128<br>
epochs=5<br>
model.to(device)<br>
criterion=nn.CrossEntropyLoss()<br>
optimizer=optim.Adam(alexnet.parameters(),lr=0.0001)</p>
<p>for epoch in range(epochs):<br>
running_loss=0.0<br>
total=0<br>
probs=0<br>
correct_classified=0<br>
start_time=time.time()<br>
model.train()<br>
for i,data in enumerate(trainloader):<br>
inputs,labels=data<br>
inputs,labels=inputs.to(device),labels.to(device)<br>
optimizer.zero_grad()<br>
outputs=model(inputs)<br>
loss=criterion(outputs,labels)<br>
loss.backward()<br>
optimizer.step()<br>
# _,predicted=torch.max(outputs.data,1)<br>
predicted=torch.argmax(outputs,1)<br>
total+=labels.size(0)<br>
probs=F.softmax(outputs,1)[1]<br>
<span class="hashtag">#print</span>(“probs=”,probs)<br>
correct_classified+=(predicted==labels).sum().item()<br>
running_loss+=loss.item()<br>
if i % 200 == 199:<br>
avg_loss=running_loss/200<br>
print(‘Epoch:[%d, %5d] Batch: %5d loss: %.3f’ % (epoch+1,i+1,i+1,avg_loss))<br>
running_loss=0.0<br>
train_acc=(100<em>correct_classified/total)<br>
# print(“Time/epoch: {} sec”.format(time.time()-start_time))<br>
# train_acc=(correct_classified/total)<br>
# print(‘Train Accuracy :%d’%(train_acc))<br>
correct_1=0.0<br>
correct_5=0.0<br>
correct=0<br>
c=0<br>
total=0<br>
model.eval()<br>
with torch.no_grad():<br>
for data in testloader:<br>
images,labels=data<br>
inputs,labels=images.to(device),labels.to(device)<br>
#img=Variable(images).cuda()<br>
#lab=Variable(labels).cuda()<br>
outputs=model(inputs)<br>
# _,predicted=torch.max(outputs.data,1)<br>
predicted=torch.argmax(outputs,1)<br>
total+=labels.size(0)<br>
c+=(predicted==labels).sum().item()<br>
#outc=model(img)<br>
pred=outputs.topk(5,1,largest=True,sorted=True)<br>
#pred=pred.t()<br>
lab=labels.view(labels.size(0),-1).expand_as(pred)<br>
# correct=pred.eq(lab).float()<br>
correct=pred.eq(lab).float()<br>
correct_5+=correct[:,:5].sum()<br>
correct_1+=correct[:,:1].sum()<br>
test_acc=(100</em>c/total)</p>
<pre><code>    print("c=",c," total=",total,"correct_1=",correct_1,"correct_5=",correct_5)
    print('Accuracy of the network on test images:%.3f'%(test_acc))
    print('Top 1 error:%2.2f' % (1-correct_1/total))
    print('Top 5 error:%2.2f' % (1-correct_5/total))
</code></pre>
<p>print(‘trained’)</p>
<p>Error: Traceback (most recent call last):<br>
File “AlexCIFAR10.py”, line 107, in <br>
lab=labels.view(labels.size(0),-1).expand_as(pred)<br>
TypeError: expand_as(): argument ‘other’ (position 1) must be Tensor, not torch.return_types.topk</p>
<p>I want to calculate the top 1 error and top 5 error but I’m getting this error how do I correct it</p>
<p><a class="mention" href="/u/ptrblck">@ptrblck</a> help me please</p>

Oli: <aside class="quote no-group" data-username="Soumyajit_Das" data-post="1" data-topic="48815">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/soumyajit_das/48/13169_2.png" class="avatar"> Soumyajit_Das:</div>
<blockquote>
<p>pred=outputs.topk(5,1,largest=True,sorted=True)</p>
</blockquote>
</aside>
<p>That line returns both values and indexes. Do <code>pred=outputs.topk(5,1,largest=True,sorted=True)[0]</code> to only get the values (although I haven’t looked at your code)</p>

Brando_Miranda: <p>answer is here: <a href="https://gist.github.com/weiaicunzai/2a5ae6eac6712c70bde0630f3e76b77b" class="inline-onebox" rel="noopener nofollow ugc">compute top1, top5 error using pytorch · GitHub</a></p>
<p>with detailed explanation:</p>
<pre><code class="lang-auto">
def accuracy(output: torch.Tensor, target: torch.Tensor, topk=(1,)) -&gt; List[torch.FloatTensor]:
    """
    Computes the accuracy over the k top predictions for the specified values of k
    In top-5 accuracy you give yourself credit for having the right answer
    if the right answer appears in your top five guesses.

    ref:
    - https://pytorch.org/docs/stable/generated/torch.topk.html
    - https://discuss.pytorch.org/t/imagenet-example-accuracy-calculation/7840
    - https://gist.github.com/weiaicunzai/2a5ae6eac6712c70bde0630f3e76b77b
    - https://discuss.pytorch.org/t/top-k-error-calculation/48815/2
    - https://stackoverflow.com/questions/59474987/how-to-get-top-k-accuracy-in-semantic-segmentation-using-pytorch

    :param output: output is the prediction of the model e.g. scores, logits, raw y_pred before normalization or getting classes
    :param target: target is the truth
    :param topk: tuple of topk's to compute e.g. (1, 2, 5) computes top 1, top 2 and top 5.
    e.g. in top 2 it means you get a +1 if your models's top 2 predictions are in the right label.
    So if your model predicts cat, dog (0, 1) and the true label was bird (3) you get zero
    but if it were either cat or dog you'd accumulate +1 for that example.
    :return: list of topk accuracy [top1st, top2nd, ...] depending on your topk input
    """
    with torch.no_grad():
        # ---- get the topk most likely labels according to your model
        # get the largest k \in [n_classes] (i.e. the number of most likely probabilities we will use)
        maxk = max(topk)  # max number labels we will consider in the right choices for out model
        batch_size = target.size(0)

        # get top maxk indicies that correspond to the most likely probability scores
        # (note _ means we don't care about the actual top maxk scores just their corresponding indicies/labels)
        _, y_pred = output.topk(k=maxk, dim=1)  # _, [B, n_classes] -&gt; [B, maxk]
        y_pred = y_pred.t()  # [B, maxk] -&gt; [maxk, B] Expects input to be &lt;= 2-D tensor and transposes dimensions 0 and 1.

        # - get the credit for each example if the models predictions is in maxk values (main crux of code)
        # for any example, the model will get credit if it's prediction matches the ground truth
        # for each example we compare if the model's best prediction matches the truth. If yes we get an entry of 1.
        # if the k'th top answer of the model matches the truth we get 1.
        # Note: this for any example in batch we can only ever get 1 match (so we never overestimate accuracy &lt;1)
        target_reshaped = target.view(1, -1).expand_as(y_pred)  # [B] -&gt; [B, 1] -&gt; [maxk, B]
        # compare every topk's model prediction with the ground truth &amp; give credit if any matches the ground truth
        correct = (y_pred == target_reshaped)  # [maxk, B] were for each example we know which topk prediction matched truth
        # original: correct = pred.eq(target.view(1, -1).expand_as(pred))

        # -- get topk accuracy
        list_topk_accs = []  # idx is topk1, topk2, ... etc
        for k in topk:
            # get tensor of which topk answer was right
            ind_which_topk_matched_truth = correct[:k]  # [maxk, B] -&gt; [k, B]
            # flatten it to help compute if we got it correct for each example in batch
            flattened_indicator_which_topk_matched_truth = ind_which_topk_matched_truth.reshape(-1).float()  # [k, B] -&gt; [kB]
            # get if we got it right for any of our top k prediction for each example in batch
            tot_correct_topk = flattened_indicator_which_topk_matched_truth.float().sum(dim=0, keepdim=True)  # [kB] -&gt; [1]
            # compute topk accuracy - the accuracy of the mode's ability to get it right within it's top k guesses/preds
            topk_acc = tot_correct_topk / batch_size  # topk accuracy for entire batch
            list_topk_accs.append(topk_acc)
        return list_topk_accs  # list of topk accuracies for entire batch [topk1, topk2, ... etc]
</code></pre>
<p>ref:<br>
- <a href="https://pytorch.org/docs/stable/generated/torch.topk.html" class="inline-onebox" rel="noopener nofollow ugc">torch.topk — PyTorch 1.8.0 documentation</a><br>
- <a href="https://discuss.pytorch.org/t/imagenet-example-accuracy-calculation/7840" class="inline-onebox">ImageNet Example Accuracy Calculation</a><br>
- <a href="https://gist.github.com/weiaicunzai/2a5ae6eac6712c70bde0630f3e76b77b" class="inline-onebox" rel="noopener nofollow ugc">compute top1, top5 error using pytorch · GitHub</a><br>
- <a href="https://discuss.pytorch.org/t/top-k-error-calculation/48815/2" class="inline-onebox">Top k error calculation - #2 by Oli</a><br>
- <a href="https://stackoverflow.com/questions/59474987/how-to-get-top-k-accuracy-in-semantic-segmentation-using-pytorch" class="inline-onebox" rel="noopener nofollow ugc">python - how to get top k accuracy in semantic segmentation using pytorch - Stack Overflow</a></p>