Description
I am trying to validate the ResNet50 model which is supposed to give 92.9% Top5 Accuracy and 75.9% Top1 Accuracy (as mentioned: https://keras.io/applications/)
But I am getting only 88.3% Top5 Accuracy and 68.094% Top1 Accuracy.
I have no clue where I am going wrong. Can somebody please help?
The code is as following:
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
import glob
#Functions for top1 and top5 accuracies
def gettop1acc(predictions,truth):
counter=0
for i in range(len(predictions)):
if truth[i] == predictions[i]:
counter = counter+1
return counter*100/(np.size(predictions,axis=0))
def gettop5acc(predictions5,truth):
counter=0
for i in range(np.size(predictions5,axis=0)):
if truth[i] in predictions5[i][:]:
counter = counter+1
return counter*100/(np.size(predictions5,axis=0))
#model
rn = ResNet50(weights='imagenet')
#%%
#Read Data
path = '/hdd/rmk6217/ImageNet/ILSVRC2015/Data/CLS-LOC/val/' #path to imagenet validation set images
X_names = np.array(glob.glob(path + "*.JPEG"))
X_names.sort()
noofinstances = len(X_names)
batchsize=500
#Batch sized X
X = np.zeros((batchsize,224,224,3),dtype=np.float32)
#Prediction for all images in the validation set
preds = np.zeros((noofinstances,1000),dtype=np.float32)
for i in range(0,int(noofinstances/batchsize)):
for j in range(0,batchsize):
img_path = X_names[j+(ibatchsize)]
img = image.load_img(img_path, target_size=(224, 224))
X[j] = image.img_to_array(img)
X = preprocess_input(X)
preds[ibatchsize:i*batchsize+batchsize,:] = rn.predict(X)
del X
#decode to get class, description and probability
p1all = decode_predictions(preds, top=1)
p5all = decode_predictions(preds, top=5)
#Get class for top 1
p1d =[]
for i in range(noofinstances):
p1d.append(p1all[i][0][0])
#Get class for top 5
p5d =[]
for i in range(noofinstances):
temp = []
for j in range(5):
temp.append(p5all[i][j][0])
p5d.append(temp)
#%%
path = '/hdd/rmk6217/ImageNet/ILSVRC2015/devkit/data/' #path to dev-kit
#Load Ground Truth Labels
load = open(path+'ILSVRC2015_clsloc_validation_ground_truth.txt','r')
full = load.readlines()
gt = []
for i in range(len(full)):
temp = full[i].split()
gt.append(int(temp[0]))
#Load Mapping of Labels and Class
mapload = open(path+'map_clsloc.txt','r')
mapfull = mapload.readlines()
mapped = []
for i in range(len(mapfull)):
temp = mapfull[i].split()
mapped.append(temp[0])
#Map out the groundtruth in terms of classes
gtactual = []
for i in range(len(gt)):
temp = mapped[gt[i]-1]
gtactual.append(temp)
#Get top1 and top5 accuracy
print(gettop1acc(p1d,gtactual))
print(gettop5acc(p5d,gtactual))