In [1]:
from retrain import *
import tensorflow as tf
import numpy as np
import time
In [2]:
#test on google's image laerning using imagenet input file structure
IMGDIR = "/Users/zhouyu/Documents/Zhou_Yu/DS/Galvanize/Capstone_data/test_data_stan"
class Helper_FLAGS(object):
def __init__(self):
self.model_dir = "./temp"
self.image_dir = IMGDIR
self.testing_percentage = 10
self.validation_percentage = 10
self.flip_left_right = False
self.random_crop = False
self.random_scale = False
self.random_brightness = False
self.bottleneck_dir = './temp/bottleneck'
self.architecture = 'inception_v3'
self.final_tensor_name = 'final_result'
self.summaries_dir = './temp/retrain_logs'
self.how_many_training_steps = 10
self.train_batch_size = 32
self.eval_step_interval = 10
self.validation_batch_size = 32
self.intermediate_store_frequency = 0
self.intermediate_output_graphs_dir = "./temp/intermediate_graph"
self.print_misclassified_test_images = False
self.output_graph = './temp/output_graph.pb'
self.output_labels = './temp/output_labels.txt'
self.test_batch_size = -1
zFLAGS = Helper_FLAGS()
In [3]:
def create_transfermodel_info():
return {'bottleneck_tensor_name':"pool_3/_reshape:0",
'bottleneck_tensor_size':2048,
'input_width':299,
'input_height':299,
'input_depth':3,
'resized_input_tensor_name':'Mul:0',
'model_file_name':'output_graph.pb',
'input_mean':128,
'input_std':128,
'tmodel_weights':'final_training_ops/weights/final_weights:0',
'tmodel_bias':'final_training_ops/biases/final_biases:0'
}
In [10]:
def create_transfermodel_graph(tfmodel_info):
dest_directory = './temp'
with tf.Graph().as_default() as graph:
tfmodel_path = os.path.join(dest_directory, tfmodel_info['model_file_name'])
with gfile.FastGFile(tfmodel_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
bottleneck_tensor, resized_input_tensor,final_weights_tensor, final_biases_tensor = (tf.import_graph_def(
graph_def,
name='',
return_elements=[
tfmodel_info['bottleneck_tensor_name'],
tfmodel_info['resized_input_tensor_name'],
tfmodel_info['tmodel_weights'],
tfmodel_info['tmodel_bias'],
]))
return graph, bottleneck_tensor, resized_input_tensor,final_weights_tensor, final_biases_tensor
In [11]:
def get_predict_image_bottleneck(image_path, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
if not gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
image_data = gfile.FastGFile(image_path, 'rb').read()
try:
#bottleneck_value = run_bottleneck_on_image(
# sess, image_data, jpeg_data_tensor, decoded_image_tensor,
# resized_input_tensor, bottleneck_tensor)
# First decode the JPEG image, resize it, and rescale the pixel values.
resized_input_values = sess.run(decoded_image_tensor,
{jpeg_data_tensor: image_data})
# Then run it through the recognition network.
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: resized_input_values})
bottleneck_values = np.squeeze(bottleneck_values)
except Exception as e:
raise RuntimeError('Error during processing file %s (%s)' % (image_path,
str(e)))
return bottleneck_values
In [20]:
# not in use
def get_one_prediction(pred_tensor,final_W, final_b, bottleneck_tensor_size):
bottleneck_input = tf.placeholder_with_default(
pred_tensor,
shape=[bottleneck_tensor_size],
name='BottleneckInputPlaceholder')
logits = tf.matmul(bottleneck_input, final_W) + final_b
final_tensor = tf.nn.softmax(logits)
return final_tensor
In [21]:
transfer_model_info = create_transfermodel_info()
graph, bottleneck_tensor, resized_image_tensor, final_weights_tensor, final_biases_tensor = (create_transfermodel_graph(transfer_model_info))
In [32]:
test_image_path = "/Users/zhouyu/Documents/Zhou_Yu/DS/Galvanize/Capstone_data/test_of_test/n02085620_11258.jpg"
In [33]:
with tf.Session(graph=graph) as sess:
jpeg_data_tensor, decoded_image_tensor = add_jpeg_decoding(
transfer_model_info['input_width'], transfer_model_info['input_height'],
transfer_model_info['input_depth'], transfer_model_info['input_mean'],
transfer_model_info['input_std'])
bo_value = get_predict_image_bottleneck(test_image_path, sess, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor, bottleneck_tensor)
bo_value = bo_value.reshape((1, bo_value.shape[0]))
logits = tf.matmul(bo_value, final_weights_tensor) + final_biases_tensor
pred_prob = tf.nn.softmax(logits)
prob_res = sess.run(pred_prob)
print prob_res
In [44]:
# get label lists
def getLabelList(label_file):
labels = []
with open(label_file, 'r') as f:
labels = f.read().splitlines()
return labels
def getPredLabel(probs, labels):
pred_labels = []
for prob in probs:
pred_labels.append(labels[np.argmax(prob)])
return pred_labels
In [45]:
labels = getLabelList("./temp/output_labels.txt")
In [47]:
getPredLabel(prob_res, labels)
Out[47]:
In [ ]: