RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor 报错
报错环境
在使用pytorch训练好的模型,进行测试时,报错
部分代码为
model = torch.load("../save_model/mynn_30.pth")
model.eval()
with torch.no_grad():
output = model(image)
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor
分析原因
分析一下报错信息,Input type 和 weight type不同,其中 weight type是cuda.FloatTensor,而 input type是FloatTensor。一个是cuda,一个不是,仔细想了一下,模型使用gpu训练的,而现在使用的input没有加gpu.
修改报错
方法一:对input进行加gpu
model.eval()
with torch.no_grad():
image = image.cuda()
output = model(image)
方法二:导入模型时,加入map_location参数,使得device指向cpu
model = torch.load("../save_model/mynn_30.pth", map_location=torch.device('cpu'))
两种方法都可以解决这个问题