在使用pytorch测试神经网络模型时, 加载了使用gpu训练出的模型参数:xxx.pth, 即torch.load(“xxx.pth”),但是运行程序时却遇到这个类型不匹配的错误:
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为torch.FloatTensor(CPU数据类型),而weight type(即网络权重参数这些)为torch.cuda.FloatTensor(GPU数据类型)。这是由于你使用的是在GPU上训练出的模型参数,但是在cpu上测试时并没有将该模型参数映射到cpu上。
怎么解决呢?
解决方法:由于xxx.pth是在GPU上训练出来的,所以在使用cpu加载时就要从GPU映射到cpu上,即在torch.load(“xxx.pth”)中添加"map_location=torch.device(“cpu”)"即可,也就是最终改为:torch.load(“xxx.pth”,map_location=torch.device(“cpu”)),程序就可以正常运行了。