/*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')
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
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, 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 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.
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 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.)
Hey, i was wondering how i get data from a .txt file and put it into an array? We have to create a structure to hold the information(firstname, lastname, and age) on some characters. That character info is stored on a .txt file. Any and all help is greatly appreciated. (We are using Visual studio 2017 if that makes a difference) txt file Bugs Bunny 1940 Elmer Fudd 1933 Porky Pig 1935 Daffy Duck 1937 Tweety Bird 1942 Taz Devil...
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...
I have a BST database that i have to export to a .CSV file. i can get it to export the first record. how can i get it to loop until the entire database is exported. void ActorBST::ExportToCSV(NodeActor *node) { string fileName; cout << "File Name(include .csv): "; cin >>fileName; ofstream myfile; myfile.open (fileName); myfile << "Year , Award, Winner, name, film"<< endl; myfile << node->year << "," << node->award << "," << node->winner << "," << node->name << ","...
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
If I compile an application for Windows I get a file with a .exe extension. What is the final build product for Android apps? How do you use a resource (an image, string, or other files you have added to your projects appropriate resource folder) in your Java code?