slim-transfer-learning

Transfer learning on TensorFlow-Slim image classification model library

Download ZIP
import numpy as npimport osimport sys# Relative importsimport syssys.path.append("..")from glob import globfrom datasets import naturalfrom datasets import dataset_utilsfrom nets import inception_v1from preprocessing import inception_preprocessingcheckpoint_folder="../model"import tensorflow.compat.v1 as tfimport tf_slim as slimimages = glob("images/*.jpg")with open("result.txt", "w") as output:    for image in images:        with tf.Graph().as_default():            # Open specified url and load image as a string            image_string = open(image, "rb").read()            # Decode string into matrix with intensity values            image_decoded = tf.image.decode_jpeg(image_string, channels=3)            # Resize the input image, preserving the aspect ratio            # and make a central crop of the resulted image.            # The crop will be of the size of the default image size of            # the network.            processed_image = inception_preprocessing.preprocess_for_eval(image_decoded, 200, 200, central_fraction=1)            # Networks accept images in batches.            # The first dimension usually represents the batch size.            # In our case the batch size is one.            processed_images  = tf.expand_dims(processed_image, 0)            #processed_images = tf.argmax(processed_images)            # Create the model, use the default arg scope to configure            # the batch norm parameters. arg_scope is a very conveniet            # feature of slim library -- you can define default            # parameters for layers -- like stride, padding etc.            with slim.arg_scope(inception_v1.inception_v1_arg_scope()):                logits, _ = inception_v1.inception_v1(processed_images, num_classes=6, is_training=False)            # In order to get probabilities we apply softmax on the output.            probabilities = tf.nn.softmax(logits)            with tf.Session() as sess:                # Restore checkpoint file                saver = tf.train.Saver()                saver.restore(sess = sess, save_path = tf.train.latest_checkpoint(checkpoint_folder))                # We want to get predictions, image as numpy matrix                # and resized and cropped piece that is actually                # being fed to the network.                np_image, network_input, probabilities = sess.run([image_decoded, processed_image, probabilities])                probabilities = probabilities[0, 0:]                sorted_inds = [i[0] for i in sorted(enumerate(-probabilities), key=lambda x:x[1])]    # Show the downloaded image    #plt.figure()    #plt.imshow(np_image.astype(np.uint8))    #plt.suptitle("Downloaded image", fontsize=14, fontweight='bold')    #plt.axis('off')    #plt.show()    # Show the image that is actually being fed to the network    # The image was resized while preserving aspect ratio and then    # cropped. After that, the mean pixel value was subtracted from    # each pixel of that crop. We normalize the image to be between [-1, 1]    # to show the image.    #plt.imshow( network_input / (network_input.max() - network_input.min()) )    #plt.suptitle("Resized, Cropped and Mean-Centered input", fontsize=14, fontweight='bold')    #plt.axis('off')    #plt.show()    #names = imagenet.create_readable_names_for_imagenet_labels()            names = dataset_utils.read_label_file("../datasets/natural/seg_train")            output.write(str(image) + ":\n")            for i in range(6):                index = sorted_inds[i]                output.write("%0.5f%%: (%s)\n" % (probabilities[index]*100, names[index]))            res = slim.get_model_variables()            output.write("____________________\n")