user7670579
user7670579

Reputation: 85

RuntimeError: Expected a Tensor of type torch.FloatTensor but found a type torch.IntTensor for sequence element

I wanna generate some random number with python and transform it to tensor with pytorch. Here is my code for generating the random number and transform it into tensor.

import numpy as np
import torch

P = np.random.uniform(0.5, 1, size=[20, 1])
k = np.random.randint(1, 20, size=[20, 1])
d_k = np.random.uniform(0, np.sqrt(80000), size=[20, 1])

P = torch.from_numpy(P).float()
k = torch.from_numpy(k).int()
d_k = torch.from_numpy(d_k).float()

torch.cat((P, k, d_k), dim=-1)

Afterward, I got some error which showed:

RuntimeError: Expected a Tensor of type torch.FloatTensor but found a type torch.IntTensor for sequence element 1 in sequence argument at position #1 'tensors'

Upvotes: 1

Views: 3086

Answers (1)

Harshit Kumar
Harshit Kumar

Reputation: 12827

The error is because k tensor is of dtype torch.int32 while other tensors P and d_k are of dtype torch.float32. But the cat operation requires all the input tensors to be of same type. From the documentation

torch.cat(tensors, dim=0, out=None) → Tensor

tensors (sequence of Tensors) – any python sequence of tensors of the same type.

One of the solutions is to convert k to float dtype as follows:

k = torch.from_numpy(k).float()

Upvotes: 1

Related Questions