How to conver a FloatTensor to LongTensor?

i have try tensor.long() but can not conver it
thanks

5 Likes

.type(torch.LongTensor)

6 Likes

What error occurs if trying to convert it with tensor.long()? This should usually work.

3 Likes

Yes, I also wonder when it does not work…

Capture

3 Likes

I use X_train_torch = torch.from_numpy(X_train).long() and it’s not working.
I tried to use also .type(torch.LongTensor) but it doesn’t work anyway.
RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 ‘mat2’
What’s the problem?

I am broke or PyTorch broke. Whatever I do error is the same. The problem with type. Whatever I cast no result, the same error. What ever I do the same. I tried to close and open Jupyter Notebook, copied it. Error is the same. I have dying Li problem.

From looking at the actual message, I think the problem is not your X_train_torch but the tensor you try add/subtract/… to/from/with it since they need to have the same type. Can you post a small snippet to reproduce the error?

1 Like

Thank you very much for help.

loss_fn = torch.nn.CrossEntropyLoss()
learning_rate = 0.01
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(5000):
    y_pred = model(X_train_torch)
    loss = loss_fn(y_pred, y_train_torch)
    print(t, loss.item())
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()```
1 Like

I moved forward. But thank you justusschock for your response. I changed the structure on my neural network and the problem disappeared.

tensor.long() doesn’t change the type of tensor permanently. Instead try: out = tensor.long() then use out as it’s type is LongTensor.

4 Likes