Plot training and validation accuracy and losses

Hello @ptrblck

I got following error when i plot train and validation acc. Could yu please help me to solve this error?

Thank you

#save the losses for further visualization

losses = {‘train’:, ‘validation’:}

accuracies = {‘train’:, ‘validation’:}

def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
since = time.time()

best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0

for epoch in range(num_epochs):
    print(f'Epoch {epoch}/{num_epochs - 1}')
    print('-' * 10)

    # Each epoch has a training and validation phase
    for phase in ['train', 'validation']:
        if phase == 'train':
            model.train()  # Set model to training mode
        else:
            model.eval()   # Set model to evaluate mode

        running_loss = 0.0
        running_corrects = 0.0

        # Iterate over data.
        for inputs, labels in dataloaders[phase]:
            inputs = inputs.to(device)
            labels = labels.to(device)

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward
            # track history if only in train
            with torch.set_grad_enabled(phase == 'train'):
                outputs = model(inputs)
                _, preds = torch.max(outputs, 1)
                loss = criterion(outputs, labels)

                # backward + optimize only if in training phase
                if phase == 'train':
                    loss.backward()
                    optimizer.step()

            # statistics
            running_loss += loss.item() * inputs.size(0)
            running_corrects += torch.sum(preds == labels.data)
        if phase == 'train':
            scheduler.step()

        epoch_loss = running_loss / dataset_sizes[phase]
        epoch_acc = running_corrects.double() / dataset_sizes[phase]
        losses[phase].append(epoch_loss)
        accuracies[phase].append(epoch_acc)

        print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')

        # deep copy the model
        if phase == 'validation' and epoch_acc > best_acc:
            best_acc = epoch_acc
            best_model_wts = copy.deepcopy(model.state_dict())

    print()

time_elapsed = time.time() - since
print(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
print(f'Best val Acc: {best_acc:4f}')

# load best model weights
model.load_state_dict(best_model_wts)
return model

num_epochs=12

f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))

t = f.suptitle(‘Performance’, fontsize=12)

f.subplots_adjust(top=0.85, wspace=0.3)

epoch_list = list(range(1,num_epochs*2+1))

ax1.plot(epoch_list, accuracies[‘train’], label=‘Train Accuracy’)

ax1.plot(epoch_list, accuracies[‘validation’], label=‘Validation Accuracy’)

ax1.set_xticks(np.arange(0, num_epochs*2+1, 5))

ax1.set_ylabel(‘Accuracy Value’)

ax1.set_xlabel(‘Epoch’)

ax1.set_title(‘Accuracy’)

l1 = ax1.legend(loc=“best”)

ax2.plot(epoch_list, losses[‘train’], label=‘Train Loss’)

ax2.plot(epoch_list, losses[‘validation’], label=‘Validation Loss’)

ax2.set_xticks(np.arange(0, epochs*2+1, 5))

ax2.set_ylabel(‘Loss Value’)

ax2.set_xlabel(‘Epoch’)

ax2.set_title(‘Loss’)

l2 = ax2.legend(loc=“best”)

Based on the error message it seems the inputs to plot don’t have the same shape.
In particular it seems accuracies['train'] should have num_epochs entries while epoch_list is created via: epoch_list = list(range(1,num_epochs*2+1)). Could you check the shape and see how long each array/list is?