Expected object of type torch.LongTensor but found type torch.FloatTensor

Hi, I’ve done a simple neural network program with pytorch but gets this RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 ‘mat2’

Can anyone help me out with it please? here is my code:

import torch.nn as nn   
import torch   

class NeuralNet(nn.Module):

    def __init__(self, input_size, output_size):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, 30)
        self.activation_f1 = nn.ReLU()
        self.fc2 = nn.Linear(30, output_size)

    def forward(self, state):
        out1 = self.activation_f1(self.fc1(state))
        q_values = self.fc2(out1)
        return q_values

model = NeuralNet(5,3)
with torch.set_grad_enabled(True):
    state = torch.tensor([1, 4, 3, 6, 0])
output = model(state)
print(ouptut)

state is a torch.LongTensor, since you created it using integer values.
You could transform it to a FloatTensor, if you

  • pass float values (torch.tensor([1., 4., 3., 6., 0.])),
  • define a dtype, state = torch.tensor([1, 4, 3, 6, 0], dtype=torch.float32)
  • transform the tensor, state = torch.tensor([1, 4, 3, 6, 0]).float()

Thanks for the fast and detailed reply. Now it’s working :slightly_smiling_face: