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)
这是我用PyTorch建立的神经网络,它基于Sentdex。我正在使用由功能get_strange_symbol_loader(batch_size=128)
导入的大学课程管理员提供的数据集。
当我运行这段代码时,它告诉我每个时代的准确性应该是1.0
。但是,在包含纪元的for循环迭代之后运行#Test块会产生一些更实际的结果。为什么会这样?
我的目标是将测试精度与历时数作图,以在模型开始过度拟合之前找到模型的最佳历时数。
答案 0 :(得分:1)
您正在区块中同时递增correct
和total
if torch.argmax(i) == label[idx]:
correct += 1
total += 1
因此,两者始终具有相同的值,并且一个除以1.0即可。
检查您的意图,我认为应该从total +=1
中删除一个标签。
编辑:我假设通过“在……之后运行#test块之后”,您的意思是您运行了另一个可能不同的代码段(也许是正确的意图)