Hello,
I am quite new to this topic and I have the following question. This is the code for network. I would like to use this code to make prediction just for one picture. This picture will undertaken some preprocessing and than directly past through the network. I don’t know how to change the code, so that it is possible just to load one picture and the data_loader isn’t necessary. Any suggestion ?
# -*- coding: utf-8 -*-
import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import densenet as dn
import timeit
import numpy as np
img_dir = 'pictures'
checkpoint = torch.load('modelbest.pth.tar')
model = dn.DenseNet3()
model.load_state_dict(checkpoint['state_dict'])
batchSize = 1
positive_class = 0
negative_class = 1-positive_class
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform_test = transforms.Compose([
transforms.ToTensor(), normalize
])
data = datasets.ImageFolder(root=img_dir, transform=transform_test)
data_loader = torch.utils.data.DataLoader(
data,
batch_size=batchSize, shuffle=False)
model.eval()
start = timeit.default_timer()
correct = 0.0
total = 0
TP = 0
TN = 0
FP = 0
FN = 0
fp_index = []
fn_index = []
lenData = len(data)
for i, (input, target) in enumerate(data_loader):
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
output = model(input_var)
_, predicted = torch.max(output.data, 1)
correct += (predicted.cpu() == target.cpu()).sum()
predicted = predicted.cpu().numpy()
target = target.cpu().numpy()
for i in range(predicted.size):
if predicted[i][0]==positive_class and target[i]==positive_class: # True Positive.
TP +=1
if predicted[i][0]==negative_class and target[i]==negative_class: # True Negative.
TN +=1
if predicted[i][0]==positive_class and target[i]==negative_class: # False Positive.
FP +=1
fp_index.append(total+i)
if predicted[i][0]==negative_class and target[i]==positive_class: # False Negative.
FN +=1
fn_index.append(total+i)
total += len(target)
print ('\nAccuracy %.2f %%' % (100 * correct/total))
print('Calculation Time: %.2fs' % (timeit.default_timer() - start))
print('Data: %d' % total)
print('True Positive: %d' % TP)
print('True Negativ: %d' % TN)
print('False Positive: %d' % FP)
print('False Negativ: %d' % FN)
print('\nFalse Positives')
for i in fp_index:
print data.imgs[i]
print('\nFalse Negatives')
for i in fn_index:
print data.imgs[i]