CNN UnboundLocalError: local variable 'age_epoch_acc1' referenced before assignment

Niraja: <p>UnboundLocalError: local variable ‘age_epoch_acc1’ referenced before assignment, I received.<br>
I attempted to resolve this mistake by ensuring that a local variable is defined before assigning a value to it; I declared ‘age_epoch_acc1’, but it still displays the error.<br>
I attempted to answer this mistake by reading other comparable queries and their solutions, but I was unable to do it.<br>
Please provide any solutions to this problem.<br>
This is my code.<br>
‘’’</p>
<pre><code>def train_model(model, dataloaders, optimizer, criterion1, criterion2, num_epochs):
since = time.time()
history = {
    #'train_acc': [],
    'train_loss': [],
    'val_loss': [],
    'age_accuracy': [],
    'gender_accuracy': [] 
}

for epoch in range(num_epochs):
    print("Epoch {}/{}".format(epoch, num_epochs-1))
    print("-" * 10)
    
    for phase in ["train", "test"]:
        running_loss = 0.0
        running_acc1 = 0.0
        running_acc2 = 0.0
        if phase == "train":
            model.train()
        else:
            model.eval()
            running_acc1 = 0
            running_acc2 = 0
            total_1 = 0
            total_2 = 0
        
        for inputs, label1, label2 in tqdm(dataloaders[phase]):
            inputs = inputs.to(device)
            label1 = label1.long()
            label2 = label2.long()
            label1 = label1.to(device)
            label2 = label2.to(device)
            optimizer.zero_grad()
            
            with torch.autograd.set_grad_enabled(phase=="train"):
                outputs = model(inputs)
                loss1 = nn.functional.cross_entropy(outputs[0], label1, reduction='mean')
                loss2 = nn.functional.cross_entropy(outputs[1], label2, reduction='mean')
                loss = loss1 + loss2

                if phase == "train":
                    loss.backward()
                    optimizer.step()
            
            running_loss += loss.item() * inputs.size(0) #
        epoch_loss = running_loss / len(dataloaders[phase].dataset)
        
        print("{} Loss: {:.4f} Acc: {:.4f} Acc: {:.4f}".format(phase, epoch_loss, age_epoch_acc1, gender_epoch_acc2))

        if phase == 'test':
          _, preds1 = torch.max(outputs[0], 1)
          _, preds2 = torch.max(outputs[1], 1)

          running_acc1 += torch.sum(preds1 == label1.data)
          running_acc2 += torch.sum(preds2 == label2.data)

          total1 += label1.size(0)
          total2 += label2.size(0)

          age_epoch_acc1 = 100 * running_acc1 // total1       #&lt;----- * Declare age_epoch_acc1 here*
          gender_epoch_acc2 = 100 * running_acc2 // total2

          history['age_accuracy'].append(age_epoch_acc1)
          history['gender_accuracy'].append(gender_epoch_acc2)
          history['val_loss'].append(epoch_loss)

        if phase == 'train':
            #history['train_acc'].append(epoch_acc)
            history['train_loss'].append(epoch_loss)

        print("{} {:.4f} Age_Acc: {:.4f} Gender_Acc: {:.4f}".format(phase, age_epoch_acc1, gender_epoch_acc2))
    
    print()

time_elapsed = time.time() - since
print("Training compete in {:.0f}m {:.0f}s".format(time_elapsed // 60, time_elapsed % 60))
#print("Best val Acc: {:4f}".format(best_acc))

return model, history
'''
</code></pre>
<p>Thank you in advance.</p>

ptrblck: <p>The <code>print</code> statement uses <code>age_epoch_acc1</code> before you are declaring it a few lines later, so initialize this variable beforehand or move the <code>print</code> statement down.</p>

Niraja: <p>if i remove above print statement then also it shows error.<br>
‘’’</p>
<pre><code>def train_model(model, dataloaders, optimizer, criterion1, criterion2, num_epochs):
since = time.time()
history = {
    #'train_acc': [],
    'train_loss': [],
    'val_loss': [],
    'age_accuracy': [],
    'gender_accuracy': [] 
}

for epoch in range(num_epochs):
    print("Epoch {}/{}".format(epoch, num_epochs-1))
    print("-" * 10)

for phase in ["train", "test"]:
    running_loss = 0.0
    running_acc1 = 0.0
    running_acc2 = 0.0
    if phase == "train":
        model.train()
    else:
        model.eval()
        running_acc1 = 0
        running_acc2 = 0
        total_1 = 0
        total_2 = 0
    
    for inputs, label1, label2 in tqdm(dataloaders[phase]):
        inputs = inputs.to(device)
        label1 = label1.long()
        label2 = label2.long()
        label1 = label1.to(device)
        label2 = label2.to(device)
        optimizer.zero_grad()
        
        with torch.autograd.set_grad_enabled(phase=="train"):
            outputs = model(inputs)
            loss1 = nn.functional.cross_entropy(outputs[0], label1, reduction='mean')
            loss2 = nn.functional.cross_entropy(outputs[1], label2, reduction='mean')
            loss = loss1 + loss2

            if phase == "train":
                loss.backward()
                optimizer.step()
        
        running_loss += loss.item() * inputs.size(0) #
    epoch_loss = running_loss / len(dataloaders[phase].dataset)
    
    #print("{} Loss: {:.4f} Acc: {:.4f} Acc: {:.4f}".format(phase, epoch_loss, age_epoch_acc1, gender_epoch_acc2))

    if phase == 'test':
      _, preds1 = torch.max(outputs[0], 1)
      _, preds2 = torch.max(outputs[1], 1)

      running_acc1 += torch.sum(preds1 == label1.data)
      running_acc2 += torch.sum(preds2 == label2.data)

      total1 += label1.size(0)
      total2 += label2.size(0)

      age_epoch_acc1 = 100 * running_acc1 // total1       #&lt;----- * Declare age_epoch_acc1 here*
      gender_epoch_acc2 = 100 * running_acc2 // total2

      history['age_accuracy'].append(age_epoch_acc1)
      history['gender_accuracy'].append(gender_epoch_acc2)
      history['val_loss'].append(epoch_loss)

    if phase == 'train':
        #history['train_acc'].append(epoch_acc)
        history['train_loss'].append(epoch_loss)

    print("{} {:.4f} Age_Acc: {:.4f} Gender_Acc: {:.4f}".format(phase, age_epoch_acc1, gender_epoch_acc2))    # &lt;---- through this it still shows the error.

print()

time_elapsed = time.time() - since
print("Training compete in {:.0f}m {:.0f}s".format(time_elapsed // 60, time_elapsed % 60))
#print("Best val Acc: {:4f}".format(best_acc))

return model, history
'''
</code></pre>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/3/c/3c27a4a5e69a4cb4a3cf3a19412fed104249c8f4.png" data-download-href="https://discuss.pytorch.org/uploads/default/3c27a4a5e69a4cb4a3cf3a19412fed104249c8f4" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/3/c/3c27a4a5e69a4cb4a3cf3a19412fed104249c8f4.png" alt="image" data-base62-sha1="8A9AacdUMmb2mWFMbufiqsVqq3i" width="690" height="219" data-dominant-color="F5F7F6"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1295×412 17 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div><br>
‘’’</p>
<pre><code>if phase == 'train':
   history['train_loss'].append(epoch_loss)
print("{} {:.4f} Age_Acc: {:.4f} Gender_Acc: {:.4f}".format(phase, age_epoch_acc1, gender_epoch_acc2))   
'''
</code></pre>
<p>shows error.</p>

ptrblck: <p>You are now defining the variable in the test phase while printing it unconditionally.</p>