CNN UnboundLocalError: local variable 'age_epoch_acc1' referenced before assignment

UnboundLocalError: local variable ‘age_epoch_acc1’ referenced before assignment, I received.
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.
I attempted to answer this mistake by reading other comparable queries and their solutions, but I was unable to do it.
Please provide any solutions to this problem.
This is my 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       #<----- * 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
'''

Thank you in advance.

The print statement uses age_epoch_acc1 before you are declaring it a few lines later, so initialize this variable beforehand or move the print statement down.

if i remove above print statement then also it shows error.
‘’’

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       #<----- * 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))    # <---- 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
'''


‘’’

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))   
'''

shows error.

You are now defining the variable in the test phase while printing it unconditionally.