model = nnet(4, 2, 1)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
trainloader = Dataloader(dataset=dataset, batch_size = 15)
val_loader = Dataloader(dataset=val_dataset, batch_size = 150)
LOSS = []
accuracy = []
N_test = len(val_dataset)
def my_trainer(epochs):
for epoch in range(epochs):
for x,y in trainloader:
z = model(x)
loss = criterion(z, y)
loss.backward()
optimizer.step()
optimizer.zero_grad()
LOSS.append(loss.item())
correct = 0
for x,y in val_loader:
z = model(x)
_, yhat = z.max(1)
correct += (yhat == y).sum().item()
acc = correct/N_test
accuracy.append(acc)
my_trainer(5000)
Updated code- I should have been using CrossEntropyLoss instead of BCE as its a multiclass problem. This might have added to my error. Now I'm gettng the error
1D target tensor expected, multi-target not supported"
for the line loss=criterion(z,y)
even though y is a 1dimensional tensor for the target. Oh well, at least the accuracy problem is solved