models icon indicating copy to clipboard operation
models copied to clipboard

How to extract accuracy from eval_image_classifier.py ?

Open ghost opened this issue 10 years ago • 9 comments

I am fine tuning Inception-v3 on my own dataset, consisting of two different classes. So far without errors or problems. To keep track of the process, I want to store the Accuracy value produced by eval_image_classifier.py. The output once I run the script looks like this:

I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:83:00.0) I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Creating TensorFlow device (/gpu:1) -> (device: 1, name: Tesla K80, pci bus id: 0000:84:00.0) INFO:tensorflow:Executing eval ops INFO:tensorflow:Executing eval_op 1/15 INFO:tensorflow:Executing eval_op 2/15 INFO:tensorflow:Executing eval_op 3/15 INFO:tensorflow:Executing eval_op 4/15 INFO:tensorflow:Executing eval_op 5/15 INFO:tensorflow:Executing eval_op 6/15 INFO:tensorflow:Executing eval_op 7/15 INFO:tensorflow:Executing eval_op 8/15 INFO:tensorflow:Executing eval_op 9/15 INFO:tensorflow:Executing eval_op 10/15 INFO:tensorflow:Executing eval_op 11/15 INFO:tensorflow:Executing eval_op 12/15 INFO:tensorflow:Executing eval_op 13/15 INFO:tensorflow:Executing eval_op 14/15 INFO:tensorflow:Executing eval_op 15/15 INFO:tensorflow:Executing summary op I tensorflow/core/kernels/logging_ops.cc:79] eval/Accuracy[0.734] I tensorflow/core/kernels/logging_ops.cc:79] eval/Recall@5[1]

The value I am trying to obtain is, in this particular example [0.734]. It is generated by the function evaluate_once(), which calls evaluation(). Though knowing where the value comes from, I haven't been able to access it directly.

Could someone give me a hint? Thank you in advance!

Here you can take a look at the code: eval_image_classifier.py evaluation.py

ghost avatar Nov 11 '16 10:11 ghost

@fplacardona Hi, I just finished training inceptionv3 from scratch on my custom dataset(1675 train images, 400 validation images, 2 classes).

1) I don't know how to make predictions on my test images using my newly trained model.(where to point label_image.py for model) 2) Where did my newly trained model got saved?

Following some meta data about my setup/run:---

I got these files generated in train_dir:- checkpoint (537bytes) events.out.tfevents.1481980070.airig-Inspiron-7559(4.9GB) graph.pbtxt(18.5MB) and a bunch of model.ckpt-.meta and model.ckpt-.index files

After running train script I got:-

....
INFO:tensorflow:Stopping Training.
INFO:tensorflow:Finished training! Saving model to disk.

After running eval script I got:--

...
INFO:tensorflow:Evaluation [0/25]
INFO:tensorflow:Evaluation [1/25]
INFO:tensorflow:Evaluation [2/25]
INFO:tensorflow:Evaluation [3/25]
INFO:tensorflow:Evaluation [5/25]
INFO:tensorflow:Evaluation [5/25]
INFO:tensorflow:Evaluation [6/25]
INFO:tensorflow:Evaluation [7/25]
INFO:tensorflow:Evaluation [8/25]
INFO:tensorflow:Evaluation [9/25]
INFO:tensorflow:Evaluation [10/25]
INFO:tensorflow:Evaluation [11/25]
INFO:tensorflow:Evaluation [13/25]
INFO:tensorflow:Evaluation [13/25]
INFO:tensorflow:Evaluation [14/25]
INFO:tensorflow:Evaluation [15/25]
INFO:tensorflow:Evaluation [16/25]
INFO:tensorflow:Evaluation [17/25]
INFO:tensorflow:Evaluation [18/25]
INFO:tensorflow:Evaluation [19/25]
INFO:tensorflow:Evaluation [20/25]
INFO:tensorflow:Evaluation [21/25]
INFO:tensorflow:Evaluation [22/25]
INFO:tensorflow:Evaluation [23/25]
INFO:tensorflow:Evaluation [25/25]
I tensorflow/core/kernels/logging_ops.cc:79] eval/Recall@5[1]
I tensorflow/core/kernels/logging_ops.cc:79] eval/Accuracy[1]
INFO:tensorflow:Finished evaluation at 2016-12-19-03:59:04

Can you please help out here.

anuj2rock avatar Dec 19 '16 04:12 anuj2rock

@anuj2rock You can do something like this:

import tensorflow as tf
from nets import inception_v3
from preprocessing import inception_preprocessing
from scipy.misc import imshow, imread

slim = tf.contrib.slim


batch_size = 3
image_size = 299

with tf.Graph().as_default():
    with slim.arg_scope(inception_v3.inception_v3_arg_scope()):

        imgPath = 'cat.jpeg'
        testImage_string = tf.gfile.FastGFile(imgPath, 'rb').read()
        testImage = tf.image.decode_jpeg(testImage_string, channels=3)
        processed_image = inception_preprocessing.preprocess_image(testImage, image_size, image_size, is_training=False)
        processed_images = tf.expand_dims(processed_image, 0)

        logits, _ = inception_v3.inception_v3(processed_images, num_classes=2, is_training=False)
        probabilities = tf.nn.softmax(logits)
        checkpoint_path = tf.train.latest_checkpoint('/tmp/checkpoint')
        init_fn = slim.assign_from_checkpoint_fn(
        checkpoint_path, slim.get_model_variables('InceptionV3'))

        with tf.Session() as sess:
            init_fn(sess)

            np_image, probabilities = sess.run([processed_images, probabilities])
            probabilities = probabilities[0, 0:]
            sorted_inds = [i[0] for i in sorted(enumerate(-probabilities), key=lambda x: x[1])]

            names = ['class1', 'class2']
            for i in range(2):
                index = sorted_inds[i]
                print((probabilities[index], names[index]))
        imshow(imread(imgPath))

Just replace with your checkpoint file, image path and class names.

bentocg avatar Mar 01 '17 19:03 bentocg

@bentocg Thanks alot for reply. I will try this today and let you know. I quick question though.. while naming "names = ['class1', 'class2'] " what order should I follow for class names.. just to be sure.

Thanks a lot.

anuj2rock avatar Mar 02 '17 01:03 anuj2rock

@anuj2rock Whatever order you had on your labels.txt when you created the .tfrecords files.

bentocg avatar Mar 02 '17 01:03 bentocg

@bentocg Thanks for this solution. It works very well for a single image. I also tried to extend it for multiple images, but the speed is really slow. This is due to the opening and closing of session in each loop. Is there a faster way to output the probabilities in a file while evaluating the tfrecords? Any possible modification to eval_image_classifier.py would be reall helpful in the learning process.

Thanks

tchugh avatar Mar 15 '17 20:03 tchugh

@tchugh I am running into the same problem. It also eats up memory, it gets progressively slower as it classifies more images. I played with eval_image_classifier.py for a while but could not figure it out... I'll try some more later.

bentocg avatar Mar 16 '17 19:03 bentocg

@bentocg can't we use the same "eval_image_classifier.py" code for testing new images(my own dataset) instead of "label_image.py" that you mentioned. I was trying to freeze the graph but is it necessary?

anne1994 avatar Jul 12 '17 23:07 anne1994

@anne1994 hello, have you freeze the graph successefully? i counter some questions

Jilliansea avatar Jul 24 '18 03:07 Jilliansea

@bentocg @anne1994 The following code can be used to evaluate your own dataset using a trained checkpoint. I use it to classify live vs spoof fingerprint images.

` import tensorflow as tf import os import glob import csv from nets import inception_v3 from preprocessing import inception_preprocessing

os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" slim = tf.contrib.slim

batch_size = 100 image_size = 299

sensor='Biometrika' year='2011' iters='120'

folderClasses = ['Live', 'Spoof'] folderPath = '/user/ExperimentalData/'+sensor+year+'/Test/' chkptPath = '/user/chughtar/AntiSpoofing/CNN_CHKPTS/CNN_chkpt_'+sensor+year+'_Scratch/'

f_live = open('scores/'+sensor+'/result_'+sensor+year+'Inceptionv3_Live'+iters+'.csv','w') f_spoof = open('scores/'+sensor+'/result_'+sensor+year+'Inceptionv3_Spoof'+iters+'.csv','w')

scores = {}

with tf.Graph().as_default(): with slim.arg_scope(inception_v3.inception_v3_arg_scope()):

    image_filename_placeholder = tf.placeholder(tf.string)
    image_tensor = tf.read_file(image_filename_placeholder)
    
    image_tensor = tf.image.decode_png(image_tensor, channels=3)
    image_tensor = tf.image.encode_jpeg(image_tensor, format='rgb', quality=100)
    image_tensor = tf.image.decode_jpeg(image_tensor, channels=3)
    
    image_tensor = inception_preprocessing.preprocess_image(image_tensor, image_size, image_size, is_training=False)
    image_batch_tensor = tf.expand_dims(image_tensor, axis=0)
    
    logits, _ = inception_v3.inception_v3(image_batch_tensor, num_classes=3, is_training=False)
    
    probabilities = tf.nn.softmax(logits)
    checkpoint_path = tf.train.latest_checkpoint(chkptPath)
    init_fn = slim.assign_from_checkpoint_fn(
    checkpoint_path, slim.get_model_variables('InceptionV3'))
    
    with tf.Session() as sess:
		init_fn(sess)
		
		for c in folderClasses:
			count=1
			scores[c]={};
			imgPaths = sorted(glob.glob(folderPath+c+'/*.png'))
			
			print("Evaluating class = " + c)
			
			for imgPath in imgPaths:
					
				if(count%2000==0):
					print(count)
			
				np_image, pr = sess.run([image_tensor, probabilities],
				feed_dict={image_filename_placeholder:imgPath})
				
				fname = imgPath.split('/')
				fname = fname[-1]
				fname = fname.split('_p')
				fname = fname[0]
				
				if(fname not in scores[c]):
					scores[c][fname]=[]

				scores[c][fname].append(pr[0,2])
				count=count+1

fw_live = csv.writer(f_live)

for fname in scores['Live']: scores['Live'][fname] = sum(scores['Live'][fname])/len(scores['Live'][fname]) #print("File = "+ fname + " score = " + str(scores[c][fname])) fw_live.writerow([fname,scores['Live'][fname]])

f_live.close()

fw_spoof = csv.writer(f_spoof)

for fname in scores['Spoof']: scores['Spoof'][fname] = sum(scores['Spoof'][fname])/len(scores['Spoof'][fname]) #print("File = "+ fname + " score = " + str(scores[c][fname])) fw_spoof.writerow([fname,scores['Spoof'][fname]])

f_spoof.close()`

tchugh avatar Jul 24 '18 15:07 tchugh