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

  • Post author:
  • Post category:其他


【PyTorch】常见错误



错误:


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()



版权声明:本文为qq_40520596原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。