Pytorch 什么';用toy MNIST示例说明这两种推理代码之间的区别

Pytorch 什么';用toy MNIST示例说明这两种推理代码之间的区别,pytorch,mnist,Pytorch,Mnist,我发现这两个代码之间有不同的精度值。 我认为这些代码相同,但给出的值不同。 为什么这两个代码的结果不同 [代码1] def mytest(model, data_loader): with torch.no_grad(): corrected_sample = 0 for x_test, y_test in data_loader: x_test, y_test = x_test.to(device), y_test.to(devi

我发现这两个代码之间有不同的精度值。 我认为这些代码相同,但给出的值不同。 为什么这两个代码的结果不同

[代码1]

def mytest(model, data_loader):
    with torch.no_grad():
        corrected_sample = 0
        for x_test, y_test in data_loader:
            x_test, y_test = x_test.to(device), y_test.to(device)
            x_test = x_test.view(-1,28*28).float()
            prediction = model(x_test)
            #predicted_class = prediction.max(1)[1]
            predicted_class = torch.argmax(prediction, 1)
            corrected_sample += (predicted_class==y_test).float().sum().item()
    accuracy = corrected_sample / len(data_loader.dataset)
    print("Accuracy : {}".format(accuracy))

data_loader_test = torch.utils.data.DataLoader(mnist_test, batch_size=1, shuffle=False)
mytest(model, data_loader_test)
with torch.no_grad():
    x_test = mnist_test.test_data.view(-1,28*28).float().to(device)
    y_test = mnist_test.test_labels.to(device)

    prediction = model(x_test)
    correct_prediction = torch.argmax(prediction,1) == y_test
    accuracy = correct_prediction.float().mean()
    print("Accuracy ", accuracy.item())
准确度:0.92232

[代码2]

def mytest(model, data_loader):
    with torch.no_grad():
        corrected_sample = 0
        for x_test, y_test in data_loader:
            x_test, y_test = x_test.to(device), y_test.to(device)
            x_test = x_test.view(-1,28*28).float()
            prediction = model(x_test)
            #predicted_class = prediction.max(1)[1]
            predicted_class = torch.argmax(prediction, 1)
            corrected_sample += (predicted_class==y_test).float().sum().item()
    accuracy = corrected_sample / len(data_loader.dataset)
    print("Accuracy : {}".format(accuracy))

data_loader_test = torch.utils.data.DataLoader(mnist_test, batch_size=1, shuffle=False)
mytest(model, data_loader_test)
with torch.no_grad():
    x_test = mnist_test.test_data.view(-1,28*28).float().to(device)
    y_test = mnist_test.test_labels.to(device)

    prediction = model(x_test)
    correct_prediction = torch.argmax(prediction,1) == y_test
    accuracy = correct_prediction.float().mean()
    print("Accuracy ", accuracy.item())
精度0.882699664306641


mnist\u test.test\u data的形状是什么?您的模型是否处于评估模式?mnist_test.test_数据的形状为[10000,28,28]。在尝试eval模式时,“model.eval()”并不重要。模型只是“nn.Linear(784,10,bias=True)”。你能给我们看一下完整的代码吗?(应该足够简短)我在这里没有发现任何错误。