【发布时间】: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