ValueError: Expected target size (1, 18), got torch.Size([1])

Hello All,
I’m new to pytorch and i’m facing a problem with NLLLoss function
this is my target wrapper tensor with one vlaue which is the index of the right class
category_tensor = torch.tensor([d.all_categories.index(category)], dtype=torch.long)
when i pass it to the lose function it get me this error ValueError: Expected target size (1, 18), got torch.Size([1])
in this line: loss = criterion(output, category_tensor)
while i used it the same and no problems in another model
my model is as follow

class Names(CudaModule):

def __init__(self, input_size, hidden_size, output_size, device_id):
    super(Names, self).__init__(device_id)
    self.input_size = input_size
    self.hidden_size = hidden_size
    self.encoder = nn.LSTM(
        hidden_size = hidden_size,
        num_layers = 1
    self.lin = nn.Linear(hidden_size,output_size)
    #self.mid = nn.ReLU()
    self.out = nn.LogSoftmax(dim=1)

def forward(self, inpt, h):
    output, h = self.encoder(inpt.view(1,1,-1), h)
    output = self.lin(output)    
    #output = self.mid(output)
    output = self.out(output)
    return output ,h

any help understand the issue is appreciated

1 Like