Question

pytorch, how can I get the file name of the image which is false prediction from torch.utils.data.DataLoader while the model is evaluating. thank you

pytorch, how can I get the file name of the image which is false prediction from torch.utils.data.DataLoader while the model is evaluating. thank you
0 0
Add a comment Improve this question Transcribed image text
Answer #1
/*This will help to get the file name of the image which is false prediction, there a way to get the class and the original name of the transfrom image to forward torch.utils.data.DataLoader as an input */
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import torchvision
import torchvision.transforms as transforms
import os
import cv2

transform = transforms.Compose([
        transforms.ToPILImage(),
        ### other PyTorch transforms
        transforms.ToTensor()
])

class CDiscountDataset(torch.utils.data.Dataset):
        '''
                Custom Dataset object for the CDiscount competition
                Parameters:
                        root_dir - directory including category folders with images

                Example:
                images/
                        1000001859/
                                26_0.jpg
                                26_1.jpg
                                ...
                        1000004141/
                                ...
                        ...
        '''
        
        def __init__(self, root_dir, transform=None):
                self.root_dir = root_dir
                self.categories = sorted(os.listdir(root_dir))
                self.cat2idx = dict(zip(self.categories, range(len(self.categories))))
                self.idx2cat = dict(zip(self.cat2idx.values(), self.cat2idx.keys()))
                self.files = []
                for (dirpath, dirnames, filenames) in os.walk(self.root_dir):
                        for f in filenames:
                                if f.endswith('.jpg'):
                                        o = {}
                                        o['img_path'] = dirpath + '/' + f
                                        o['category'] = self.cat2idx[dirpath[dirpath.find('/')+1:]]
                                        self.files.append(o)
                self.transform = transform
        
        def __len__(self):
                return len(self.files)
        
        def __getitem__(self, idx):
                img_path = self.files[idx]['img_path']
                category = self.files[idx]['category']
                image = cv2.imread(img_path)
                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                if self.transform:
                        image = self.transform(image)
                        
                return {'image': image, 'category': category}

dset = CDiscountDataset('images', transform=transform)
print('######### Dataset class created #########')
print('Number of images: ', len(dset))
print('Number of categories: ', len(dset.categories))
print('Sample image shape: ', dset[0]['image'].shape, end='\n\n')


dataloader = torch.utils.data.DataLoader(dset, batch_size=4, shuffle=True, num_workers=4)

### Define your network below
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(180**2 * 3, 84)
        self.fc2 = nn.Linear(84, 36)

    def forward(self, x):
        x = x.view(-1, 180**2 * 3)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x


net = Net()
print('######### Network created #########')
print('Architecture:\n', net)

### Train
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

for epoch in range(2):

    running_loss = 0.0
    examples = 0
    for i, data in enumerate(dataloader, 0):
        # Get the inputs
        inputs, labels = data['image'], data['category']

        # Wrap them in Variable
        inputs, labels = Variable(inputs), Variable(labels)

        # Zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # Print statistics
        running_loss += loss.data[0]
        examples += 4
        print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / examples))

print('Finished Training')
Add a comment
Know the answer?
Add Answer to:
pytorch, how can I get the file name of the image which is false prediction from torch.utils.data.DataLoader while the model is evaluating. thank you
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can i get help with these questions? Thank you

    Can i get help with these questions? Thank you

  • Pick a gray-scale image, say cameraman.tif or any other file that you can get hold of,...

    Pick a gray-scale image, say cameraman.tif or any other file that you can get hold of, and using the imwrite function write it to files of types JPEG, PNG and GIF. What are the sizes of those files? using matlab

  • Can I get some help On a HW discussion please, Thank you in advance. How does...

    Can I get some help On a HW discussion please, Thank you in advance. How does a Punnett square help to determine the probability of specific genotypes or phenotypes in offspring of known parents? How are Mendel’s laws of segregation, and independent assortment reflected in Punnett squares made from two or more alleles?

  • Can i get help in this problem.Hopefully i can get help in this problem .Thank You....

    Can i get help in this problem.Hopefully i can get help in this problem .Thank You. A 10.00 L tank at 21.2 degree C is filled with 11.3 g of chlorine pentafluoride gas and 6.04 g of carbon dioxide gas. You can assume both gases behave as ideal gases under these conditions. Calculate the mole fraction of each gas. Round each of your answers to 3 significant digits.

  • can someone show me how to do this thank you please i inned inneeeed it In...

    can someone show me how to do this thank you please i inned inneeeed it In a group of 20 batteries, 3 are dead. You choose 2 batteries at random a) Create a probability model for the number of good batteries you get. b) What's the expected number of good ones you get? c) What's the standard deviation? a) Create a probability model. Number good 0 2 P(Number good) (Round to three decimal places as needed.)

  • please help in matlab!!! Thank you so much in advance! Modify fn = input('input file name:',...

    please help in matlab!!! Thank you so much in advance! Modify fn = input('input file name:', 's' ); ofn = input('output file name: ','s' ); ih = fopen( ifn,'r'); oh = fopen( ofn,'w' ); ln = ''; while ischar( ln ) ln = fgets( ih ); if ischar( ln )    fprintf( oh, ln ); end end fclose( ih ); fclose( oh ); % fprintf( oh, ln ) has a paramter oh of file %handle. Ln is written to the...

  • How can a constructor be identified in a class file? The name of the constructor is...

    How can a constructor be identified in a class file? The name of the constructor is the same as the name of the class. The name of the constructor is the same as the name of the file (without .java). The constructor looks like a method, but it has no return type (not even void). A. I only B. II only C. III only D. I and III only E. I, II, and III

  • How can I read a file and use the content to find the answer?

    How can I read a file and use the content to find the answer? 3. Write a MatLab program that reads in the set of values in the file "Values.txt" which is available from the d2l website. The values are stored as ASCII text separated by carriage returns, so you can open the file and look at the valucs yourself by double clicking on the file name in MatLab's Current Directory window. Your program should next calculate and print out:...

  • How can I read a file and use the content to find the answer?

    How can I read a file and use the content to find the answer? 3. Write a MatLab program that reads in the set of values in the file "Values.txt" which is available from the d2l website. The values are stored as ASCII text separated by carriage returns, so you can open the file and look at the valucs yourself by double clicking on the file name in MatLab's Current Directory window. Your program should next calculate and print out:...

  • How can I read a file and use the content to find the answer?

    How can I read a file and use the content to find the answer? 3. Write a MatLab program that reads in the set of values in the file "Values.txt" which is available from the d2l website. The values are stored as ASCII text separated by carriage returns, so you can open the file and look at the valucs yourself by double clicking on the file name in MatLab's Current Directory window. Your program should next calculate and print out:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT