Search code examples
arrayscastingpytorchtensorautoencoder

Casting Pytorch's tensor elements the type "float" instead of "double"


I had a matrix saved as a numpy type, call it "X_before" (for example, its shape is 100*30).

Since I want to feed it to an AutoEncoder using Pytorch library, I converted it to torch.tensor like this:

X_tensor = torch.from_numpy(X_before, dtype=torch)

Then, I got the following error:

expected scalar type Float but found Double

Next, I tried to make elements as "float" and then convert them torch.tensor:

X_before = X_before.astype(float)
X_tensor = torch.from_numpy(X_before)

Again, the same error happens. How should I solve this issue? How can I convert the type of elements in a torch.tensor object to another type?

Thanks in advance


Solution

  • The easiest way:

    X_tensor = torch.tensor(X_before, dtype=torch.float32)
    

    You can see the list of types here: https://pytorch.org/docs/stable/tensors.html

    You can change the type:

    X_tensor=X_tensor.type(torch.float64)
    

    (Note that float64 is double, while float32 is the standardd float)