I was training a deep learning model but i am encountering the error like The size of tensor a (3) must match the size of tensor b (32) at non-singleton dimension 1.And also while training the data the accuracy is above 1 that means i am getting the accuracy like 1.04,1.06 like that. The Below is the Training Code
def train(model,criterion,optimizer,iters):
epoch = iters
train_loss = []
validaion_loss = []
train_acc = []
validation_acc = []
states = ['Train','Valid']
for epoch in range(epochs):
print("epoch : {}/{}".format(epoch+1,epochs))
for phase in states:
if phase == 'Train':
model.train()
dataload = train_data_loader
else:
model.eval()
dataload = valid_data_loader
run_loss,run_acc = 0,0
for data in dataload:
inputs,labels = data
#print("Inputs:",inputs.shape)
#print("Labels:",labels.shape)
inputs = inputs.to(device)
labels = labels.to(device)
labels = labels.byte()
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'Train'):
outputs = model(inputs)
print("Outputs",outputs.shape)
loss = criterion(outputs,labels)
predict = outputs>=0.5
#print("Predict",predict.shape)
if phase == 'Train':
loss.backward()
optimizer.step()
acc = torch.sum(predict == labels.data)
run_loss+=loss.item()
#print("Running_Loss",run_loss)
run_acc+=acc.item()/len(labels)
#print("Running_Acc",run_acc)
if phase == 'Train':
epoch_loss = run_loss/len(train_data_loader)
train_loss.append(epoch_loss)
epoch_acc = run_acc/len(train_data_loader)
train_acc.append(epoch_acc)
else:
epoch_loss = run_loss/len(valid_data_loader)
validaion_loss.append(epoch_loss)
epoch_acc = run_acc/len(valid_data_loader)
validation_acc.append(epoch_acc)
print("{}, loss :{},accuracy:{}".format(phase,epoch_loss,epoch_acc))
history = {'Train_loss':train_loss,'Train_accuracy':train_acc,
'Validation_loss':validaion_loss,'Validation_Accuracy':validation_acc}
return model,history
Below is the code of the base model
model = models.resnet34(pretrained = True)
for param in model.parameters():
param.requires_grad = False
model.fc = nn.Sequential(nn.Linear(model.fc.in_features,out_features = 1024),nn.ReLU(),
nn.Linear(in_features = 1024,out_features = 512),nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(in_features=512,out_features=256),nn.ReLU(),
nn.Linear(in_features = 256,out_features = 3),nn.LogSoftmax(dim = 1))
device = torch.device("cuda" if cuda.is_available() else "cpu")
print(device)
model.to(device)
optimizer = optim.Adam(model.parameters(),lr = 0.00001)
criterion = nn.CrossEntropyLoss()
I tried with predict == labels.unsqueeze(1) it didn't raise any error but the accuracy is going over 1. May I know where i had to change the code.
