【PyTorch】常见错误: RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor)

错误:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

问题原因:

错误内容就在类型不匹配,根据报错内容可以看出Input type为torch.FloatTensor(CPU数据类型),而weight type(即网络权重参数这些)为torch.cuda.FloatTensor(GPU数据类型)。

解决办法:

既然网络参数是GPU类型,那解决方法就是将输入类型转变为GPU类型,需要使用到cuda,没有cuda就解决不了。实现方法有两种:

1,

device = torch.device('cuda:0')
inputs = inputs.to(device)

2,

inputs = inputs.cuda()

总结:

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(torch.cuda.is_available())

inputs = inputs.to(device)        	# 方法一:将input这个tensor转换成了CUDA 类型
inputs = inputs.cuda()				# 方法二:将input这个tensor转换成了CUDA 类型

类似错误:

若与上面错误是反的,即
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same

那就同理,对net进行转换。

1,

device = torch.device('cuda:0')
net= net.to(device)

2,

net = net.cuda()

猜你喜欢

转载自blog.csdn.net/Alexa_/article/details/134444021