1
num_samples = 10
def predict(x):
    sampled_models = [guide(None, None) for _ in range(num_samples)]
    yhats = [model(x).data for model in sampled_models]
    mean = torch.mean(torch.stack(yhats), 0)
    return np.argmax(mean.numpy(), axis=1)

print('Prediction when network is forced to predict')
correct = 0
total = 0
for j, data in enumerate(test_loader):
    images, labels = data
    predicted = predict(images.view(-1,28*28))
    total += labels.size(0)
    correct += (predicted == labels).sum().item()
print("accuracy: %d %%" % (100 * correct / total))

错误

correct += (predicted == labels).sum().item() TypeError: 
eq() received an invalid combination of arguments - got (numpy.ndarray), but expected one of:  
* (Tensor other)
  didn't match because some of the arguments have invalid types: (!numpy.ndarray!)
* (Number other)
  didn't match because some of the arguments have invalid types: (!numpy.ndarray!)

*

4

1 回答 1

2

您正在尝试比较predictedlabels。但是,您predicted的 is a np.arraywhile labelsis atorch.tensor因此eq()==操作员)无法在它们之间进行比较。
替换np.argmaxtorch.argmax

 return torch.argmax(mean, dim=1)

你应该没事。

于 2019-03-05T12:29:16.243 回答