PyTorch报”RuntimeError: Expected tensor for argument #1 ‘indices’ to have scalar type Long; but got torch.cuda.FloatTensor instead “的原因以及解决办法

  • Post category:Python

“RuntimeError: Expected tensor for argument #1 ‘indices’ to have scalar type Long; but got torch.cuda.FloatTensor instead “这个报错的原因是因为在PyTorch中,有些函数需要使用整数类型(Long)的张量作为输入,但是当我们传递一个浮点类型的张量时,就会发生这个错误。

这个错误通常是在使用PyTorch的CUDA版本的时候出现的,因为PyTorch的GPU版本默认使用FloatTensor类型。而一些函数,比如torch.nn.functional.embedding()需要的是LongTensor类型作为输入。

解决这个问题的方法:

1.将输入类型转化为LongTensor类型:

indices = indices.long()
result = torch.nn.functional.embedding(indices, embedding, padding_idx=0)

2.使用.cuda()方法将张量传递到GPU上时,使用.cuda().long()方法将其转化为LongTensor类型:

indices = indices.cuda().long()
result = torch.nn.functional.embedding(indices, embedding, padding_idx=0)

上面两种方法在使用torch.nn.functional.embedding()函数时都能解决这个问题。重要的是确保输入张量的类型正确,以避免这个报错的出现。

除了以上方法,还有其他的在PyTorch中使用CUDA时出现这个问题的场景,比如使用torch.arange()生成整数张量时需要指定dtype为long,将嵌套的列表转化为张量时也需要将类型转化为LongTensor类型。因此,在使用CUDA时,正确的数据类型非常重要。