RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0

问题描述:

device = "cuda:0"   

y_hat,hidden = my_LSTM(test_x)#这里加to(device)的原因在于为在GPU上,test_x是在CPU上的,所以需要统一到GPU上面
y_hat = y_hat[:, -1, :].squeeze(-1)

# print(len(predict_result))
print("--------------------------")
print(y_hat.device)
visualize(len(test_x)-1, y_hat.cpu().detach(), test_y,y_label='Loss')#y_hat.cpu()是因为经过核查,这个结果是在GPU上,为了保证统一在一起,需要
# 将其换到CPU

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0_第1张图片

解决方案:

用print查各个变量是在GPU还是CPU上面,然后将不一致的转化为一致。

device = "cuda:0"   

print("--------------------------")
print(test_x.device)
y_hat,hidden = my_LSTM(test_x.to(device))#这里加to(device)的原因在于为在GPU上,test_x是在CPU上的,所以需要统一到GPU上面
y_hat = y_hat[:, -1, :].squeeze(-1)

# print(len(predict_result))

visualize(len(test_x)-1, y_hat.cpu().detach(), test_y,y_label='Loss')#y_hat.cpu()是因为经过核查,这个结果是在GPU上,为了保证统一在一起,需要
# 将其换到CPU
  • 详细说明:

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0_第2张图片
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0_第3张图片

你可能感兴趣的:(python,深度学习)