您好,登錄后才能下訂單哦!
這幾天關(guān)于accuracy和loss的計(jì)算有一些疑惑,原來是自己還沒有弄清楚。
給出實(shí)例
def train(train_loader, model, criteon, optimizer, epoch): train_loss = 0 train_acc = 0 num_correct= 0 for step, (x,y) in enumerate(train_loader): # x: [b, 3, 224, 224], y: [b] x, y = x.to(device), y.to(device) model.train() logits = model(x) loss = criteon(logits, y) optimizer.zero_grad() loss.backward() optimizer.step() train_loss += float(loss.item()) train_losses.append(train_loss) pred = logits.argmax(dim=1) num_correct += torch.eq(pred, y).sum().float().item() logger.info("Train Epoch: {}\t Loss: {:.6f}\t Acc: {:.6f}".format(epoch,train_loss/len(train_loader),num_correct/len(train_loader.dataset))) return num_correct/len(train_loader.dataset), train_loss/len(train_loader)
首先這樣一次訓(xùn)練稱為一個(gè)epoch,樣本總數(shù)/batchsize是走完一個(gè)epoch所需的“步數(shù)”,相對應(yīng)的,len(train_loader.dataset)也就是樣本總數(shù),len(train_loader)就是這個(gè)步數(shù)。
那么,accuracy的計(jì)算也就是在整個(gè)train_loader的for循環(huán)中(步數(shù)),把每個(gè)mini_batch中判斷正確的個(gè)數(shù)累加起來,然后除以樣本總數(shù)就行了;
而loss的計(jì)算有講究了,首先在這里我們是計(jì)算交叉熵,關(guān)于交叉熵,也就是涉及到兩個(gè)值,一個(gè)是模型給出的logits,也就是10個(gè)類,每個(gè)類的概率分布,另一個(gè)是樣本自身的
label,在Pytorch中,只要把這兩個(gè)值輸進(jìn)去就能計(jì)算交叉熵,用的方法是nn.CrossEntropyLoss,這個(gè)方法其實(shí)是計(jì)算了一個(gè)minibatch的均值了,因此累加以后需要除以的步數(shù),也就是
minibatch的個(gè)數(shù),而不是像accuracy那樣是樣本個(gè)數(shù),這一點(diǎn)非常重要。
以上就是本次介紹的全部知識點(diǎn)內(nèi)容,感謝大家對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。