pytorch使用GPU计算报错:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same
原因是,还必须将每一步的输入和目标也发送到GPU。
示例:
原始错误代码:
...
net = Net()
net.to(device) # GPU版本,递归遍历所有模块,并将其参数和缓冲区转换为CUDA张量
...
dataiter = iter(trainloader) # 数据迭代器
images = dataiter.next()[0]
labels = dataiter.next()[1]
...
改进代码:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
...
net = Net()
net.to(device) # GPU版本,递归遍历所有模块,并将其参数和缓冲区转换为CUDA张量
...
dataiter = iter(trainloader) # 数据迭代器
images = dataiter.next()[0].to(device)
labels = dataiter.next()[1].to(device)
...