Transfer Learning: Unknown bug

ahmedoumar: <p>Hey community,<br>
I have downloaded a resnet50 pretrained model (i tried different other architectures) for image classification, and i have changed the last layer(classifier) so it can classify my 5 image classes, but it suffers from overfitting and even though i tried a simple architecture and added dropout layer, it still not able to generalize on test data, it gives very low accuracy on the test data(around 10%).</p>
<p>so help please <img src="https://discuss.pytorch.org/images/emoji/apple/frowning.png?v=9" title=":frowning:" class="emoji" alt=":frowning:"></p>
<p>here is the code:</p>
<p>`data_transforms = {<br>
‘train’: transforms.Compose([<br>
transforms.RandomResizedCrop(size=500, scale=(0.8, 1.0)),<br>
transforms.RandomRotation(degrees=15),<br>
transforms.ColorJitter(),<br>
transforms.RandomHorizontalFlip(),<br>
transforms.CenterCrop(size=500),  # Image net standards<br>
transforms.ToTensor(),<br>
transforms.Normalize([0.485, 0.456, 0.406],<br>
[0.229, 0.224, 0.225])<br>
]),<br>
‘test’: transforms.Compose([<br>
transforms.Resize(size=500),<br>
transforms.CenterCrop(size=500),<br>
transforms.ToTensor(),<br>
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])<br>
]),<br>
}</p>
<p>data_dir = ‘cassava-disease’<br>
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),<br>
data_transforms[x])<br>
for x in [‘train’, ‘test’]}<br>
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=32,<br>
shuffle=True, num_workers=0)<br>
for x in [‘train’, ‘test’]}<br>
dataset_sizes = {x: len(image_datasets[x]) for x in [‘train’, ‘test’]}<br>
class_names = image_datasets[‘train’].classes</p>
<p>device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)</p>
<p>def train_model(model, criterion, optimizer, scheduler, num_epochs=25):<br>
since = time.time()</p>
<pre><code>best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0

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

    # Each epoch has a training and validation phase
    for phase in ['train', 'test']:
        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

        # 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]

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

        # deep copy the model
        if phase == 'test' and epoch_acc &gt; best_acc:
            best_acc = epoch_acc
            best_model_wts = copy.deepcopy(model.state_dict())
            torch.save(model, 'model.pth')
            print('***Model Saved!***')

    print()

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

# load best model weights
model.load_state_dict(best_model_wts)
return model
</code></pre>
<p>model_ft = models.resnet50(pretrained=True)</p>
<p>model_ft</p>
<p>import adabound<br>
<span class="hashtag">#model_ft</span> = models.vgg16(pretrained=True)<br>
<span class="hashtag">#model_ft</span>.aux_logits=False</p>
<p>num_ftrs = model_ft.fc.in_features<br>
for param in model_ft.parameters():<br>
param.requires_grad = False</p>
<h1>Here the size of each output sample is set to 5.</h1>
<p>model_ft.fc = nn.Sequential(nn.Linear(num_ftrs, 256),<br>
nn.ReLU(),<br>
nn.Dropout(0.4),<br>
nn.Linear(256, 128),<br>
nn.ReLU(),<br>
nn.Dropout(0.4),<br>
nn.Linear(128, 5),<br>
nn.LogSoftmax(dim=1))</p>
<p>criterion = nn.NLLLoss()</p>
<h1>Observe that all parameters are being optimized</h1>
<p>optimizer_ft = adabound.AdaBound(model_ft.fc.parameters(), lr=1e-3, final_lr=0.1)</p>
<p><span class="hashtag">#optimizer_ft</span> = optim.Adam(model_ft.classifier.parameters(), lr=0.003)<br>
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)<br>
model_ft = model_ft.to(device)</p>
<p>model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,<br>
num_epochs=100)<br>
`</p>

ahmedoumar: <p><span class="mention">@ptrblck_de</span> any idea please!</p>

ptrblck: <p>Overfitting can generally be reduced by adding regularization to the model (e.g. through dropout, weight decay, a more aggressive data augmentation etc.). Also, make sure the data is sampled from the same domains from the training, validation, and test splits.<br>
The used data augmentation also depends on the actual use case. E.g. while heavy rotations might be beneficial for images or galaxies, it might not be a good idea for landscape scenes.</p>