【问题标题】:Evaluating accuracy of neural network after every epoch在每个 epoch 之后评估神经网络的准确性
【发布时间】:2020-03-07 05:48:51
【问题描述】:
from dataset import get_strange_symbol_loader, get_strange_symbols_test_data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim


class Net(nn.Module):
   def __init__(self):
    super().__init__()
    self.fc1 = nn.Linear(28*28, 512)
    self.fc2 = nn.Linear(512, 256)
    self.fc3 = nn.Linear(256, 15)

def forward(self,x):
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)

    return F.softmax(x, dim=1)


if __name__ == '__main__':
   net = Net()
   train, test = get_strange_symbol_loader(batch_size=128)
   loss_function = nn.CrossEntropyLoss()
   optimizer = optim.Adam(net.parameters(), lr=1e-3)
   Accuracy = []

   for epoch in range(30):   
       print("epoch",epoch)
       #Train
       for data in train:
           img, label = data  
           net.zero_grad()
           output = net(img.view(-1,28*28))
           loss = F.nll_loss(output, label)
           loss.backward()
           optimizer.step()
       #Test    
       correct, total = 0, 0
       with torch.no_grad():
          for data in test:
               img, label = data
               output = net(img.view(-1,784))
               for idx, i in enumerate(output):
                   if torch.argmax(i) == label[idx]:
                       correct += 1
                       total += 1
       Accuracy.append(round(correct/total, 3))
       print("Accuracy: ",Accuracy)

这是我基于Sentdex 使用 PyTorch 制作的神经网络。我正在使用由函数get_strange_symbol_loader(batch_size=128) 导入的大学课程管理员给我的数据集。

当我运行这段代码时,它告诉我每个时期的准确度应该是1.0。但是,在包含 epoch 的 for 循环的迭代之后运行 #Test 块会给出更真实的结果。为什么会这样?

我的目标是根据 epoch 数绘制测试准确性,以在模型开始过度拟合之前找到模型的最佳 epoch 数。

【问题讨论】:

  • 请更具体。代码在哪里告诉您“每个时期的准确度应该是 1.0”?为什么会发生what
  • 我的意思是,在 for 循环之后运行测试块会返回更可信的准确度,例如 85%

标签: python machine-learning neural-network


【解决方案1】:

您正在增加块中的correcttotal

if torch.argmax(i) == label[idx]:
    correct += 1
    total += 1

因此两者始终具有相同的值,一个除以另一个得到 1.0

检查您的意图,我认为从total +=1 中删除标签应该可以。

编辑:我假设“在运行 #test 块之后......”你的意思是你运行另一个可能不同的 sn-p(也许是正确的)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2017-08-31
    • 2018-04-30
    • 1970-01-01
    • 2013-06-30
    • 2019-11-17
    • 2016-11-04
    相关资源
    最近更新 更多