The accuracy of the test results of the trained model is zero.

Ahmet58: <p>Hi i am a beginner and i trained an image classification model with resnet18, but when i test the trained model with test files, none of the results are correct, i am writing the code here so you can help</p>
<p>import torch<br>
import torch.nn as nn<br>
import torch.optim as optim<br>
from torch.optim import lr_scheduler<br>
import torchvision<br>
from torchvision import datasets, models, transforms<br>
import time<br>
import os<br>
import copy<br>
import tqdm</p>
<p>data_dir = ‘./dataset’</p>
<p>data_transforms = {<br>
‘train’: transforms.Compose([<br>
transforms.RandomResizedCrop(224),<br>
transforms.RandomHorizontalFlip(),<br>
transforms.ToTensor(),<br>
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])<br>
]),</p>
<pre><code>'validation': transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),

'test': transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
</code></pre>
<p>}</p>
<p>image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),<br>
data_transforms[x])<br>
for x in [‘train’, ‘validation’, ‘test’]}</p>
<p>dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,<br>
shuffle=True, num_workers=0)<br>
for x in [‘train’, ‘validation’, ‘test’]}</p>
<p>dataset_sizes = {x: len(image_datasets[x]) for x in [‘train’, ‘saglama’, ‘test’]}<br>
class_names = image_datasets[‘train’].classes</p>
<p>device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)</p>
<h1><a name="get-a-batch-of-training-data-1" class="anchor" href="#get-a-batch-of-training-data-1"></a>Get a batch of training data</h1>
<p>inputs, classes = next(iter(dataloaders[‘train’]))</p>
<h1><a name="make-a-grid-from-batch-2" class="anchor" href="#make-a-grid-from-batch-2"></a>Make a grid from batch</h1>
<p>out = torchvision.utils.make_grid(inputs)</p>
<p>def train_model(model, criterion, optimizer, scheduler, num_epochs=10):<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, 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

        # Iterate over data.
        for inputs, labels in tqdm.tqdm(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 == 'validation' and epoch_acc &gt; best_acc:
            best_acc = epoch_acc
            best_model_wts = copy.deepcopy(model.state_dict())

    print()

time_elapsed = time.time() - since
print('Egitim Tamamlandı {:.0f}m {:.0f}s'.format(
    time_elapsed // 60, time_elapsed % 60))
print('En Doğru Sağlama  : {:4f}'.format(best_acc))

# load best model weights
model.load_state_dict(best_model_wts)
return model
</code></pre>
<p>model_ft = models.resnet18(pretrained=True)<br>
num_ftrs = model_ft.fc.in_features</p>
<h1><a name="here-the-size-of-each-output-sample-is-set-to-2-3" class="anchor" href="#here-the-size-of-each-output-sample-is-set-to-2-3"></a>Here the size of each output sample is set to 2.</h1>
<h1><a name="alternatively-it-can-be-generalized-to-nnlinearnum_ftrs-lenclass_names-4" class="anchor" href="#alternatively-it-can-be-generalized-to-nnlinearnum_ftrs-lenclass_names-4"></a>Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).</h1>
<p>model_ft.fc = nn.Linear(num_ftrs, len(class_names))</p>
<p>model_ft = model_ft.to(device)</p>
<p>criterion = nn.CrossEntropyLoss()</p>
<h1><a name="observe-that-all-parameters-are-being-optimized-5" class="anchor" href="#observe-that-all-parameters-are-being-optimized-5"></a>Observe that all parameters are being optimized</h1>
<p>optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)</p>
<h1><a name="decay-lr-by-a-factor-of-01-every-7-epochs-6" class="anchor" href="#decay-lr-by-a-factor-of-01-every-7-epochs-6"></a>Decay LR by a factor of 0.1 every 7 epochs</h1>
<p>exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)</p>
<p>model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,<br>
num_epochs=300)</p>
<p>torch.save(model_ft, “model.pt”)</p>
<p>class_labels = [“Powdery_mildew”, “Healthy”, “YellowLeaf_Curl_Virus”, “Bacterial_Spot”]</p>
<p>total = 0  # total değişkenini tanımla ve sıfıra ayarla<br>
correct = 0</p>
<h1><a name="since-were-not-training-we-dont-need-to-calculate-the-gradients-for-our-outputs-7" class="anchor" href="#since-were-not-training-we-dont-need-to-calculate-the-gradients-for-our-outputs-7"></a>since we’re not training, we don’t need to calculate the gradients for our outputs</h1>
<p>with torch.no_grad():<br>
for data in tqdm.tqdm(dataloaders[“test”]):<br>
images, labels = data<br>
# calculate outputs by running images through the network<br>
outputs = model_ft(images)<br>
# the class with the highest energy is what we choose as prediction<br>
_, predicted = torch.max(outputs.data, 1)<br>
total += labels.size(0)<br>
correct += (predicted == labels).sum().item()</p>
<pre><code>    # Print the predicted labels
    for i in range(len(predicted)):
        print('Predicted class: {}'.format(class_labels[predicted[i]]))
</code></pre>
<p>print(‘Accuracy of the network on the %d test images: %d %%’ % (<br>
dataset_sizes[“test”], 100 * correct / total))</p>