I am trying to perform a Logistic Regression in PyTorch on a simple 0,1 labelled dataset. The criterion or loss is defined as: criterion = nn.CrossEntropyLoss()
. The model is: model = LogisticRegression(1,2)
I have a data point which is a pair: dat = (-3.5, 0)
, the first element is the datapoint and the second is the corresponding label.
Then I convert the first element of the input to a tensor: tensor_input = torch.Tensor([dat[0]])
.
Then I apply the model to the tensor_input: outputs = model(tensor_input)
.
Then I convert the label to a tensor: tensor_label = torch.Tensor([dat[1]])
.
Now, when I try to do this, the thing breaks: loss = criterion(outputs, tensor_label)
. It gives and error: RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
import torch
import torch.nn as nn
class LogisticRegression(nn.Module):
def __init__(self, input_size, num_classes):
super(LogisticRegression, self).__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, x):
out = self.linear(x)
return out
model = LogisticRegression(1,2)
criterion = nn.CrossEntropyLoss()
dat = (-3.5,0)
tensor_input = torch.Tensor([dat[0]])
outputs = binary_model(tensor_input)
tensor_label = torch.Tensor([dat[1]])
loss = criterion(outputs, tensor_label)
I can't for the life of me figure it out.
model
in your sample code, but you are later usingbinary_model
for the forward pass. Might just be a typo, but I don't know your code. – dennlinger