Hi All,
I am trying to use a custom loss function when training. Please see the code below.
#Custom function
def pfbeta_fast(labels, predictions, beta=1.3):
pTP = np.sum(labels * predictions)
pFP = np.sum((1-labels) * predictions)
num_positives = np.sum(labels) # = pTP+pFN
pPrecision = pTP/(pTP+pFP)
pRecall = pTP/num_positives
beta_squared = beta**2
if (pPrecision > 0 and pRecall > 0):
pF1 = (1+beta_squared) * pPrecision * pRecall/(beta_squared*pPrecision + pRecall)
return pF1
else:
return 0
model_conv = torchvision.models.regnet_y_32gf(weights = 'RegNet_Y_32GF_Weights.IMAGENET1K_SWAG_E2E_V1')
#model_conv = torchvision.models.efficientnet_b7(weights = 'EfficientNet_B7_Weights.IMAGENET1K_V1')
for param in model_conv.parameters():
param.requires_grad = False
# Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)
model_conv = model_conv.to(device)
criterion = pfbeta_fast #set model criterion
# Observe that only parameters of final layer are being optimized as
# opposed to before.
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)
model_conv = train_model(model_conv, criterion, optimizer_conv,
exp_lr_scheduler, num_epochs=1)
For the above code I get the error below:
Epoch 0/0
----------
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/tmp/ipykernel_23/3648721085.py in <module>
1 model_conv = train_model(model_conv, criterion, optimizer_conv,
----> 2 exp_lr_scheduler, num_epochs=1)
/tmp/ipykernel_23/3892717004.py in train_model(model, criterion, optimizer, scheduler, num_epochs)
32 outputs = model(inputs)
33 _, preds = torch.max(outputs, 1)
---> 34 loss = criterion(outputs, labels)
35
36 # backward + optimize only if in training phase
/tmp/ipykernel_23/3685174594.py in pfbeta_fast(labels, predictions, beta)
1 def pfbeta_fast(labels, predictions, beta=1.3):
2
----> 3 pTP = np.sum(labels * predictions)
4 pFP = np.sum((1-labels) * predictions)
5 num_positives = np.sum(labels) # = pTP+pFN
RuntimeError: The size of tensor a (2) must match the size of tensor b (16) at non-singleton dimension 1
Would anyone be able to help me in this regards? Also is there a specific procedure that needed to be followed as in convert the loss function to pytorch commands for usage? Please
Thanks & Best Regards
AMJS