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

2

5

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

Ullrich answered 18/2, 2021 at 12:49 Comment(0)
P
6

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)

Pauiie answered 18/2, 2021 at 12:59 Comment(0)
F
1

The other simple way to do it is:

X_tensor = torch.from_numpy(X_before).type(torch.float)
Fishtail answered 6/11, 2022 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.