Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.45 KB | None | 0 0
  1. import glob
  2. import os
  3. import random
  4. import numpy as np
  5. import tensorflow as tf
  6. from tensorflow.python.platform import gfile
  7.  
  8. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
  9.  
  10. BOTTLENECK_TENSOR_SIZE = 2048
  11. BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'
  12. JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'
  13.  
  14.  
  15. MODEL_DIR = 'F:/pythonWS/imageClassifier/datasets/inception_dec_2015'#'./datasets/inception_dec_2015'
  16. MODEL_FILE= 'tensorflow_inception_graph.pb'
  17.  
  18. CACHE_DIR = 'F:/pythonWS/imageClassifier/datasets/bottleneck'
  19. INPUT_DATA = 'F:/pythonWS/imageClassifier/datasets/flower_photos'
  20.  
  21. VALIDATION_PERCENTAGE = 10
  22. TEST_PERCENTAGE = 10
  23.  
  24. LEARNING_RATE = 0.01
  25. STEPS = 4000
  26. BATCH = 100
  27.  
  28.  
  29. def create_image_lists(testing_percentage, validation_percentage):
  30. result = {}
  31. sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]
  32. is_root_dir = True
  33. for sub_dir in sub_dirs:
  34. if is_root_dir:
  35. is_root_dir = False
  36. continue
  37.  
  38. extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
  39.  
  40. file_list = []
  41. dir_name = os.path.basename(sub_dir)
  42. for extension in extensions:
  43. file_glob = os.path.join(INPUT_DATA, dir_name, '*.' + extension)
  44. file_list.extend(glob.glob(file_glob))
  45. if not file_list: continue
  46.  
  47. #中文名问题解决方法?
  48. label_name = dir_name
  49. #label_name = dir_name.lower()
  50.  
  51. # 初始化
  52. training_images = []
  53. testing_images = []
  54. validation_images = []
  55. for file_name in file_list:
  56. base_name = os.path.basename(file_name)
  57.  
  58. # 随机划分数据
  59. chance = np.random.randint(100)
  60. if chance < validation_percentage:
  61. validation_images.append(base_name)
  62. elif chance < (testing_percentage + validation_percentage):
  63. testing_images.append(base_name)
  64. else:
  65. training_images.append(base_name)
  66.  
  67. result[label_name] = {
  68. 'dir': dir_name,
  69. 'training': training_images,
  70. 'testing': testing_images,
  71. 'validation': validation_images,
  72. }
  73. # print('training image:%d'%len(training_images))
  74. # print('testing image:%d' % len(testing_images))
  75. # print('validation image:%d' % len(validation_images))
  76. return result
  77. def get_image_path(image_lists, image_dir, label_name, index, category):
  78. label_lists = image_lists[label_name]
  79. category_list = label_lists[category]
  80. mod_index = index % len(category_list)
  81. base_name = category_list[mod_index]
  82. sub_dir = label_lists['dir']
  83. full_path = os.path.join(image_dir, sub_dir, base_name)
  84. return full_path
  85. def get_tst_image_path(image_lists, image_dir, label_name, index, category):
  86. label_lists = image_lists[label_name]
  87. category_list = label_lists[category]
  88. mod_index = index % len(category_list)
  89. base_name = category_list[mod_index]
  90. sub_dir = label_lists['dir']
  91. # full_path = os.path.join(image_dir, sub_dir, base_name)
  92. full_path = os.path.join(image_dir, sub_dir)
  93. os.chdir(full_path)
  94. return base_name
  95. def get_bottleneck_path(image_lists, label_name, index, category):
  96. return get_image_path(image_lists, CACHE_DIR, label_name, index, category) + '.txt'
  97. def run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor):
  98.  
  99. bottleneck_values = sess.run(bottleneck_tensor, {image_data_tensor: image_data})
  100.  
  101. bottleneck_values = np.squeeze(bottleneck_values)
  102. return bottleneck_values
  103. def get_or_create_bottleneck(sess, image_lists, label_name, index, category, jpeg_data_tensor, bottleneck_tensor):
  104. label_lists = image_lists[label_name]
  105. sub_dir = label_lists['dir']
  106. sub_dir_path = os.path.join(CACHE_DIR, sub_dir)
  107. if not os.path.exists(sub_dir_path): os.makedirs(sub_dir_path)
  108. bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category)
  109. if not os.path.exists(bottleneck_path):
  110.  
  111. image_path = get_tst_image_path(image_lists, INPUT_DATA, label_name, index, category)
  112.  
  113. image_data = gfile.FastGFile('./%s'%image_path, 'rb').read()
  114.  
  115. bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor)
  116.  
  117. bottleneck_string = ','.join(str(x) for x in bottleneck_values)
  118. with open(bottleneck_path, 'w') as bottleneck_file:
  119. bottleneck_file.write(bottleneck_string)
  120. else:
  121.  
  122. with open(bottleneck_path, 'r') as bottleneck_file:
  123. bottleneck_string = bottleneck_file.read()
  124. bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
  125.  
  126. return bottleneck_values
  127. def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category, jpeg_data_tensor, bottleneck_tensor):
  128. bottlenecks = []
  129. ground_truths = []
  130. for _ in range(how_many):
  131. label_index = random.randrange(n_classes)
  132. label_name = list(image_lists.keys())[label_index]
  133. image_index = random.randrange(65536)
  134. bottleneck = get_or_create_bottleneck(
  135. sess, image_lists, label_name, image_index, category, jpeg_data_tensor, bottleneck_tensor)
  136. ground_truth = np.zeros(n_classes, dtype=np.float32)
  137. ground_truth[label_index] = 1.0
  138. bottlenecks.append(bottleneck)
  139. ground_truths.append(ground_truth)
  140.  
  141. return bottlenecks, ground_truths
  142. def get_tst_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):
  143. bottlenecks = []
  144. ground_truths = []
  145. label_name_list = list(image_lists.keys())
  146. for label_index, label_name in enumerate(label_name_list):
  147. category = 'testing'
  148. for index, unused_base_name in enumerate(image_lists[label_name][category]):
  149. bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,jpeg_data_tensor, bottleneck_tensor)
  150. ground_truth = np.zeros(n_classes, dtype=np.float32)
  151. ground_truth[label_index] = 1.0
  152. bottlenecks.append(bottleneck)
  153. ground_truths.append(ground_truth)
  154. return bottlenecks, ground_truths
  155. def last_layer(n_classes,bottleneck_input):
  156. # 定义一层全链接层
  157. with tf.name_scope('final_training_ops'):
  158. weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001))
  159. biases = tf.Variable(tf.zeros([n_classes]))
  160. logits = tf.matmul(bottleneck_input, weights) + biases
  161. return logits
  162. def load_inception_v3():
  163. # 读取已经训练好的Inception-v3模型。
  164. with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:
  165. graph_def = tf.GraphDef()
  166. graph_def.ParseFromString(f.read())
  167. return graph_def
  168. def train(bottleneck_tensor, jpeg_data_tensor):
  169. image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)
  170. n_classes = len(image_lists.keys())
  171.  
  172. # 定义新的神经网络输入
  173. bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE],
  174. name='BottleneckInputPlaceholder')
  175. ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput')
  176.  
  177. logits=last_layer(n_classes,bottleneck_input)
  178. final_tensor = tf.nn.softmax(logits)
  179.  
  180. # 定义交叉熵损失函数。
  181. cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=ground_truth_input)
  182. cross_entropy_mean = tf.reduce_mean(cross_entropy)
  183. train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean)
  184.  
  185. # 计算正确率。
  186. with tf.name_scope('evaluation'):
  187. correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))
  188. evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  189.  
  190. saver = tf.train.Saver(tf.global_variables(), write_version=tf.train.SaverDef.V1)
  191.  
  192. with tf.Session() as sess:
  193. init = tf.global_variables_initializer()
  194. sess.run(init)
  195. print("重新训练模型")
  196. for i in range(STEPS):
  197. train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks(
  198. sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor)
  199. sess.run(train_step,
  200. feed_dict={bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth})
  201. # 在验证数据上测试正确率
  202. if i % 100 == 0 or i + 1 == STEPS:
  203. validation_bottlenecks, validation_ground_truth = get_random_cached_bottlenecks(
  204. sess, n_classes, image_lists, BATCH, 'validation', jpeg_data_tensor, bottleneck_tensor)
  205. validation_accuracy = sess.run(evaluation_step, feed_dict={
  206. bottleneck_input: validation_bottlenecks, ground_truth_input: validation_ground_truth})
  207. print('Step %d: Validation accuracy on random sampled %d examples = %.1f%%' %(i, BATCH, validation_accuracy * 100))
  208. print('Beginning Test')
  209. # 在最后的测试数据上测试正确率。
  210. test_bottlenecks, test_ground_truth = get_tst_bottlenecks(
  211. sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor)
  212. test_accuracy = sess.run(evaluation_step, feed_dict={
  213. bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth})
  214. print('Final test accuracy = %.1f%%' % (test_accuracy * 100))
  215.  
  216. saver.save(sess, 'F:/pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt')
  217.  
  218. def image_Classfier(bottleneck_tensor, jpeg_data_tensor):
  219.  
  220. image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)
  221. n_classes = len(image_lists.keys())
  222.  
  223. # 定义新的神经网络输入
  224. bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE],
  225. name='BottleneckInputPlaceholder')
  226. ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput')
  227.  
  228. logits=last_layer(n_classes,bottleneck_input)
  229. final_tensor = tf.nn.softmax(logits)
  230.  
  231. # 计算正确率。
  232. with tf.name_scope('evaluation'):
  233. correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))
  234. evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  235.  
  236. saver = tf.train.Saver(write_version=tf.train.SaverDef.V1)
  237. with tf.Session() as sess:
  238. init = tf.global_variables_initializer()
  239. sess.run(init)
  240. if os.path.exists('F:/pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt'):
  241. saver.restore(sess, 'F:/pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt')
  242. print("ckpt file already exist!")
  243.  
  244. # 在最后的测试数据上测试正确率。
  245. test_bottlenecks, test_ground_truth = get_tst_bottlenecks(
  246. sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor)
  247. test_accuracy = sess.run(evaluation_step, feed_dict={
  248. bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth})
  249. print('Final test accuracy = %.1f%%' % (test_accuracy * 100))
  250.  
  251. with tf.name_scope('kind'):
  252. # image_kind=image_lists.keys()[tf.arg_max(final_tensor,1)]
  253. image_order_step = tf.arg_max(final_tensor, 1)
  254. label_name_list = list(image_lists.keys())
  255. for label_index, label_name in enumerate(label_name_list):
  256. category = 'testing'
  257. for index, unused_base_name in enumerate(image_lists[label_name][category]):
  258. bottlenecks = []
  259. ground_truths = []
  260. print("真实值%s:" % label_name)
  261. # print(unused_base_name)
  262. bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,
  263. jpeg_data_tensor, bottleneck_tensor)
  264. ground_truth = np.zeros(n_classes, dtype=np.float32)
  265. ground_truth[label_index] = 1.0
  266. bottlenecks.append(bottleneck)
  267. ground_truths.append(ground_truth)
  268. image_kind = sess.run(image_order_step, feed_dict={
  269. bottleneck_input: bottlenecks, ground_truth_input: ground_truths})
  270. image_kind_order = int(image_kind[0])
  271. print("预测值%s:" % label_name_list[image_kind_order])
  272.  
  273. def main():
  274. graph_def = load_inception_v3()
  275. bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(
  276. graph_def, return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])
  277. train(bottleneck_tensor, jpeg_data_tensor)
  278. # image_Classfier(bottleneck_tensor, jpeg_data_tensor)
  279.  
  280. if __name__ == '__main__':
  281. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement