I am trying to implement basic logistic regression using pytorch. For loss function I am using nn.BCEWithLogitLoss().
I am getting an error of “result type Double can’t be cast to the desired output type Long” I tried many ways, but I am unable to overcome this.
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(input_size, num_classes)
criterion =nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# Training the Model
for epoch in range(num_epochs):
for i, (dataX, labels) in enumerate(trainloader1):
dataX = Variable(dataX.view(-1, 34))
labels = Variable(labels)
dataX=torch.tensor(dataX, dtype=torch.float64)
labels=torch.tensor(labels, dtype=torch.long)
print(labels.squeeze(1).size())
# Forward + Backward + Optimize
optimizer.zero_grad()
outputs = model(dataX)
#loss = criterion(outputs, labels.squeeze(1))
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print ('Epoch: [%d/%d], Step: [%d/%d], Loss: %.4f'
% (epoch+1, num_epochs, i+1, len(X_1)//batch_size, loss.data.item())) # a//b
means integer(a/b)
# Test the Model
correct = 0
total = 0
for dataX2, labels in validloader1:
dataX2 = Variable(dataX2.view(-1, 34))
outputs = model(dataX2)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Accuracy of the model on the 10000 test images: %d %%' % (100 * correct / total))
Any Help is highly appreciated