Advertisement
Guest User

Untitled

a guest
Nov 21st, 2017
626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 55.74 KB | None | 0 0
  1. ""Simple transfer learning with Inception v3 or Mobilenet models.
  2.  
  3. With support for TensorBoard.
  4.  
  5. This example shows how to take a Inception v3 or Mobilenet model trained on
  6. ImageNet images, and train a new top layer that can recognize other classes of
  7. images.
  8.  
  9. The top layer receives as input a 2048-dimensional vector (1001-dimensional for
  10. Mobilenet) for each image. We train a softmax layer on top of this
  11. representation. Assuming the softmax layer contains N labels, this corresponds
  12. to learning N + 2048*N (or 1001*N)  model parameters corresponding to the
  13. learned biases and weights.
  14.  
  15. Here's an example, which assumes you have a folder containing class-named
  16. subfolders, each full of images for each label. The example folder flower_photos
  17. should have a structure like this:
  18.  
  19. ~/flower_photos/daisy/photo1.jpg
  20. ~/flower_photos/daisy/photo2.jpg
  21. ...
  22. ~/flower_photos/rose/anotherphoto77.jpg
  23. ...
  24. ~/flower_photos/sunflower/somepicture.jpg
  25.  
  26. The subfolder names are important, since they define what label is applied to
  27. each image, but the filenames themselves don't matter. Once your images are
  28. prepared, you can run the training with a command like this:
  29.  
  30.  
  31. ```bash
  32. bazel build tensorflow/examples/image_retraining:retrain && \
  33. bazel-bin/tensorflow/examples/image_retraining/retrain \
  34.     --image_dir ~/flower_photos
  35. ```
  36.  
  37. Or, if you have a pip installation of tensorflow, `retrain.py` can be run
  38. without bazel:
  39.  
  40. ```bash
  41. python tensorflow/examples/image_retraining/retrain.py \
  42.     --image_dir ~/flower_photos
  43. ```
  44.  
  45. You can replace the image_dir argument with any folder containing subfolders of
  46. images. The label for each image is taken from the name of the subfolder it's
  47. in.
  48.  
  49. This produces a new model file that can be loaded and run by any TensorFlow
  50. program, for example the label_image sample code.
  51.  
  52. By default this script will use the high accuracy, but comparatively large and
  53. slow Inception v3 model architecture. It's recommended that you start with this
  54. to validate that you have gathered good training data, but if you want to deploy
  55. on resource-limited platforms, you can try the `--architecture` flag with a
  56. Mobilenet model. For example:
  57.  
  58. Run floating-point version of mobilenet:
  59. ```bash
  60. python tensorflow/examples/image_retraining/retrain.py \
  61.     --image_dir ~/flower_photos --architecture mobilenet_1.0_224
  62. ```
  63.  
  64. Run quantized version of mobilenet:
  65. ```bash
  66. python tensorflow/examples/image_retraining/retrain.py \
  67.     --image_dir ~/flower_photos/   --architecture mobilenet_1.0_224_quantized
  68. ```
  69.  
  70. There are 32 different Mobilenet models to choose from, with a variety of file
  71. size and latency options. The first number can be '1.0', '0.75', '0.50', or
  72. '0.25' to control the size, and the second controls the input image size, either
  73. '224', '192', '160', or '128', with smaller sizes running faster. See
  74. https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html
  75. for more information on Mobilenet.
  76.  
  77. To use with TensorBoard:
  78.  
  79. By default, this script will log summaries to /tmp/retrain_logs directory
  80.  
  81. Visualize the summaries with this command:
  82.  
  83. tensorboard --logdir /tmp/retrain_logs
  84.  
  85. """
  86. from __future__ import absolute_import
  87. from __future__ import division
  88. from __future__ import print_function
  89.  
  90. import argparse
  91. from datetime import datetime
  92. import hashlib
  93. import os.path
  94. import random
  95. import re
  96. import sys
  97. import tarfile
  98.  
  99. import numpy as np
  100. from six.moves import urllib
  101. import tensorflow as tf
  102.  
  103. from tensorflow.contrib.quantize.python import quant_ops
  104. from tensorflow.python.framework import graph_util
  105. from tensorflow.python.framework import tensor_shape
  106. from tensorflow.python.platform import gfile
  107. from tensorflow.python.util import compat
  108.  
  109. FLAGS = None
  110.  
  111. # These are all parameters that are tied to the particular model architecture
  112. # we're using for Inception v3. These include things like tensor names and their
  113. # sizes. If you want to adapt this script to work with another model, you will
  114. # need to update these to reflect the values in the network you're using.
  115. MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1  # ~134M
  116.  
  117.  
  118. def create_image_lists(image_dir, testing_percentage, validation_percentage):
  119.  """Builds a list of training images from the file system.
  120.  
  121.   Analyzes the sub folders in the image directory, splits them into stable
  122.   training, testing, and validation sets, and returns a data structure
  123.   describing the lists of images for each label and their paths.
  124.  
  125.   Args:
  126.     image_dir: String path to a folder containing subfolders of images.
  127.     testing_percentage: Integer percentage of the images to reserve for tests.
  128.     validation_percentage: Integer percentage of images reserved for validation.
  129.  
  130.   Returns:
  131.     A dictionary containing an entry for each label subfolder, with images split
  132.     into training, testing, and validation sets within each label.
  133.   """
  134.  if not gfile.Exists(image_dir):
  135.    tf.logging.error("Image directory '" + image_dir + "' not found.")
  136.    return None
  137.  result = {}
  138.  sub_dirs = [x[0] for x in gfile.Walk(image_dir)]
  139.  # The root directory comes first, so skip it.
  140.  is_root_dir = True
  141.  for sub_dir in sub_dirs:
  142.    if is_root_dir:
  143.      is_root_dir = False
  144.      continue
  145.    extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
  146.    file_list = []
  147.    dir_name = os.path.basename(sub_dir)
  148.    if dir_name == image_dir:
  149.      continue
  150.    tf.logging.info("Looking for images in '" + dir_name + "'")
  151.    for extension in extensions:
  152.      file_glob = os.path.join(image_dir, dir_name, '*.' + extension)
  153.      file_list.extend(gfile.Glob(file_glob))
  154.    if not file_list:
  155.      tf.logging.warning('No files found')
  156.      continue
  157.    if len(file_list) < 20:
  158.      tf.logging.warning(
  159.          'WARNING: Folder has less than 20 images, which may cause issues.')
  160.    elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS:
  161.      tf.logging.warning(
  162.          'WARNING: Folder {} has more than {} images. Some images will '
  163.          'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS))
  164.    label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower())
  165.    training_images = []
  166.    testing_images = []
  167.    validation_images = []
  168.    for file_name in file_list:
  169.      base_name = os.path.basename(file_name)
  170.      # We want to ignore anything after '_nohash_' in the file name when
  171.      # deciding which set to put an image in, the data set creator has a way of
  172.      # grouping photos that are close variations of each other. For example
  173.      # this is used in the plant disease data set to group multiple pictures of
  174.      # the same leaf.
  175.      hash_name = re.sub(r'_nohash_.*$', '', file_name)
  176.      # This looks a bit magical, but we need to decide whether this file should
  177.      # go into the training, testing, or validation sets, and we want to keep
  178.      # existing files in the same set even if more files are subsequently
  179.      # added.
  180.      # To do that, we need a stable way of deciding based on just the file name
  181.      # itself, so we do a hash of that and then use that to generate a
  182.      # probability value that we use to assign it.
  183.      hash_name_hashed = hashlib.sha1(compat.as_bytes(hash_name)).hexdigest()
  184.      percentage_hash = ((int(hash_name_hashed, 16) %
  185.                          (MAX_NUM_IMAGES_PER_CLASS + 1)) *
  186.                         (100.0 / MAX_NUM_IMAGES_PER_CLASS))
  187.      if percentage_hash < validation_percentage:
  188.        validation_images.append(base_name)
  189.      elif percentage_hash < (testing_percentage + validation_percentage):
  190.        testing_images.append(base_name)
  191.      else:
  192.        training_images.append(base_name)
  193.    result[label_name] = {
  194.        'dir': dir_name,
  195.        'training': training_images,
  196.        'testing': testing_images,
  197.        'validation': validation_images,
  198.    }
  199.  return result
  200.  
  201.  
  202. def get_image_path(image_lists, label_name, index, image_dir, category):
  203.  """"Returns a path to an image for a label at the given index.
  204.  
  205.  Args:
  206.    image_lists: Dictionary of training images for each label.
  207.    label_name: Label string we want to get an image for.
  208.    index: Int offset of the image we want. This will be moduloed by the
  209.    available number of images for the label, so it can be arbitrarily large.
  210.    image_dir: Root folder string of the subfolders containing the training
  211.    images.
  212.    category: Name string of set to pull images from - training, testing, or
  213.    validation.
  214.  
  215.  Returns:
  216.    File system path string to an image that meets the requested parameters.
  217.  
  218.  """
  219.   if label_name not in image_lists:
  220.     tf.logging.fatal('Label does not exist %s.', label_name)
  221.   label_lists = image_lists[label_name]
  222.   if category not in label_lists:
  223.     tf.logging.fatal('Category does not exist %s.', category)
  224.   category_list = label_lists[category]
  225.   if not category_list:
  226.     tf.logging.fatal('Label %s has no images in the category %s.',
  227.                      label_name, category)
  228.   mod_index = index % len(category_list)
  229.   base_name = category_list[mod_index]
  230.   sub_dir = label_lists['dir']
  231.   full_path = os.path.join(image_dir, sub_dir, base_name)
  232.   return full_path
  233.  
  234.  
  235. def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,
  236.                         category, architecture):
  237.   """"Returns a path to a bottleneck file for a label at the given index.
  238.  
  239.  Args:
  240.    image_lists: Dictionary of training images for each label.
  241.    label_name: Label string we want to get an image for.
  242.    index: Integer offset of the image we want. This will be moduloed by the
  243.    available number of images for the label, so it can be arbitrarily large.
  244.    bottleneck_dir: Folder string holding cached files of bottleneck values.
  245.    category: Name string of set to pull images from - training, testing, or
  246.    validation.
  247.    architecture: The name of the model architecture.
  248.  
  249.  Returns:
  250.    File system path string to an image that meets the requested parameters.
  251.  """
  252.   return get_image_path(image_lists, label_name, index, bottleneck_dir,
  253.                         category) + '_' + architecture + '.txt'
  254.  
  255.  
  256. def create_model_graph(model_info):
  257.   """"Creates a graph from saved GraphDef file and returns a Graph object.
  258.  
  259.  Args:
  260.    model_info: Dictionary containing information about the model architecture.
  261.  
  262.  Returns:
  263.    Graph holding the trained Inception network, and various tensors we'll be
  264.    manipulating.
  265.  """
  266.   with tf.Graph().as_default() as graph:
  267.     model_path = os.path.join(FLAGS.model_dir, model_info['model_file_name'])
  268.     print('Model path: ', model_path)
  269.     with gfile.FastGFile(model_path, 'rb') as f:
  270.       graph_def = tf.GraphDef()
  271.       graph_def.ParseFromString(f.read())
  272.       bottleneck_tensor, resized_input_tensor = (tf.import_graph_def(
  273.           graph_def,
  274.           name='',
  275.           return_elements=[
  276.               model_info['bottleneck_tensor_name'],
  277.               model_info['resized_input_tensor_name'],
  278.           ]))
  279.   return graph, bottleneck_tensor, resized_input_tensor
  280.  
  281.  
  282. def run_bottleneck_on_image(sess, image_data, image_data_tensor,
  283.                             decoded_image_tensor, resized_input_tensor,
  284.                             bottleneck_tensor):
  285.   """Runs inference on an image to extract the 'bottleneck' summary layer.
  286.  
  287.  Args:
  288.    sess: Current active TensorFlow Session.
  289.    image_data: String of raw JPEG data.
  290.    image_data_tensor: Input data layer in the graph.
  291.    decoded_image_tensor: Output of initial image resizing and preprocessing.
  292.    resized_input_tensor: The input node of the recognition graph.
  293.    bottleneck_tensor: Layer before the final softmax.
  294.  
  295.  Returns:
  296.    Numpy array of bottleneck values.
  297.  """
  298.   # First decode the JPEG image, resize it, and rescale the pixel values.
  299.   resized_input_values = sess.run(decoded_image_tensor,
  300.                                   {image_data_tensor: image_data})
  301.   # Then run it through the recognition network.
  302.   bottleneck_values = sess.run(bottleneck_tensor,
  303.                                {resized_input_tensor: resized_input_values})
  304.   bottleneck_values = np.squeeze(bottleneck_values)
  305.   return bottleneck_values
  306.  
  307.  
  308. def maybe_download_and_extract(data_url):
  309.   """Download and extract model tar file.
  310.  
  311.  If the pretrained model we're using doesn't already exist, this function
  312.  downloads it from the TensorFlow.org website and unpacks it into a directory.
  313.  
  314.  Args:
  315.    data_url: Web location of the tar file containing the pretrained model.
  316.  """
  317.   dest_directory = FLAGS.model_dir
  318.   if not os.path.exists(dest_directory):
  319.     os.makedirs(dest_directory)
  320.   filename = data_url.split('/')[-1]
  321.   filepath = os.path.join(dest_directory, filename)
  322.   if not os.path.exists(filepath):
  323.  
  324.     def _progress(count, block_size, total_size):
  325.       sys.stdout.write('\r>> Downloading %s %.1f%%' %
  326.                        (filename,
  327.                         float(count * block_size) / float(total_size) * 100.0))
  328.       sys.stdout.flush()
  329.  
  330.     filepath, _ = urllib.request.urlretrieve(data_url, filepath, _progress)
  331.     print()
  332.     statinfo = os.stat(filepath)
  333.     tf.logging.info('Successfully downloaded', filename, statinfo.st_size,
  334.                     'bytes.')
  335.     print('Extracting file from ', filepath)
  336.     tarfile.open(filepath, 'r:gz').extractall(dest_directory)
  337.   else:
  338.     print('Not extracting or downloading files, model already present in disk')
  339.  
  340.  
  341. def ensure_dir_exists(dir_name):
  342.   """Makes sure the folder exists on disk.
  343.  
  344.  Args:
  345.    dir_name: Path string to the folder we want to create.
  346.  """
  347.   if not os.path.exists(dir_name):
  348.     os.makedirs(dir_name)
  349.  
  350.  
  351. bottleneck_path_2_bottleneck_values = {}
  352.  
  353.  
  354. def create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
  355.                            image_dir, category, sess, jpeg_data_tensor,
  356.                            decoded_image_tensor, resized_input_tensor,
  357.                            bottleneck_tensor):
  358.   """Create a single bottleneck file."""
  359.   tf.logging.info('Creating bottleneck at ' + bottleneck_path)
  360.   image_path = get_image_path(image_lists, label_name, index,
  361.                               image_dir, category)
  362.   if not gfile.Exists(image_path):
  363.     tf.logging.fatal('File does not exist %s', image_path)
  364.   image_data = gfile.FastGFile(image_path, 'rb').read()
  365.   try:
  366.     bottleneck_values = run_bottleneck_on_image(
  367.         sess, image_data, jpeg_data_tensor, decoded_image_tensor,
  368.         resized_input_tensor, bottleneck_tensor)
  369.   except Exception as e:
  370.     raise RuntimeError('Error during processing file %s (%s)' % (image_path,
  371.                                                                  str(e)))
  372.   bottleneck_string = ','.join(str(x) for x in bottleneck_values)
  373.   with open(bottleneck_path, 'w') as bottleneck_file:
  374.     bottleneck_file.write(bottleneck_string)
  375.  
  376.  
  377. def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,
  378.                              category, bottleneck_dir, jpeg_data_tensor,
  379.                              decoded_image_tensor, resized_input_tensor,
  380.                              bottleneck_tensor, architecture):
  381.   """Retrieves or calculates bottleneck values for an image.
  382.  
  383.  If a cached version of the bottleneck data exists on-disk, return that,
  384.  otherwise calculate the data and save it to disk for future use.
  385.  
  386.  Args:
  387.    sess: The current active TensorFlow Session.
  388.    image_lists: Dictionary of training images for each label.
  389.    label_name: Label string we want to get an image for.
  390.    index: Integer offset of the image we want. This will be modulo-ed by the
  391.    available number of images for the label, so it can be arbitrarily large.
  392.    image_dir: Root folder string of the subfolders containing the training
  393.    images.
  394.    category: Name string of which set to pull images from - training, testing,
  395.    or validation.
  396.    bottleneck_dir: Folder string holding cached files of bottleneck values.
  397.    jpeg_data_tensor: The tensor to feed loaded jpeg data into.
  398.    decoded_image_tensor: The output of decoding and resizing the image.
  399.    resized_input_tensor: The input node of the recognition graph.
  400.    bottleneck_tensor: The output tensor for the bottleneck values.
  401.    architecture: The name of the model architecture.
  402.  
  403.  Returns:
  404.    Numpy array of values produced by the bottleneck layer for the image.
  405.  """
  406.   label_lists = image_lists[label_name]
  407.   sub_dir = label_lists['dir']
  408.   sub_dir_path = os.path.join(bottleneck_dir, sub_dir)
  409.   ensure_dir_exists(sub_dir_path)
  410.   bottleneck_path = get_bottleneck_path(image_lists, label_name, index,
  411.                                         bottleneck_dir, category, architecture)
  412.   if not os.path.exists(bottleneck_path):
  413.     create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
  414.                            image_dir, category, sess, jpeg_data_tensor,
  415.                            decoded_image_tensor, resized_input_tensor,
  416.                            bottleneck_tensor)
  417.   with open(bottleneck_path, 'r') as bottleneck_file:
  418.     bottleneck_string = bottleneck_file.read()
  419.   did_hit_error = False
  420.   try:
  421.     bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
  422.   except ValueError:
  423.     tf.logging.warning('Invalid float found, recreating bottleneck')
  424.     did_hit_error = True
  425.   if did_hit_error:
  426.     create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
  427.                            image_dir, category, sess, jpeg_data_tensor,
  428.                            decoded_image_tensor, resized_input_tensor,
  429.                            bottleneck_tensor)
  430.     with open(bottleneck_path, 'r') as bottleneck_file:
  431.       bottleneck_string = bottleneck_file.read()
  432.     # Allow exceptions to propagate here, since they shouldn't happen after a
  433.     # fresh creation
  434.     bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
  435.   return bottleneck_values
  436.  
  437.  
  438. def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
  439.                       jpeg_data_tensor, decoded_image_tensor,
  440.                       resized_input_tensor, bottleneck_tensor, architecture):
  441.   """Ensures all the training, testing, and validation bottlenecks are cached.
  442.  
  443.  Because we're likely to read the same image multiple times (if there are no
  444.  distortions applied during training) it can speed things up a lot if we
  445.  calculate the bottleneck layer values once for each image during
  446.  preprocessing, and then just read those cached values repeatedly during
  447.  training. Here we go through all the images we've found, calculate those
  448.  values, and save them off.
  449.  
  450.  Args:
  451.    sess: The current active TensorFlow Session.
  452.    image_lists: Dictionary of training images for each label.
  453.    image_dir: Root folder string of the subfolders containing the training
  454.    images.
  455.    bottleneck_dir: Folder string holding cached files of bottleneck values.
  456.    jpeg_data_tensor: Input tensor for jpeg data from file.
  457.    decoded_image_tensor: The output of decoding and resizing the image.
  458.    resized_input_tensor: The input node of the recognition graph.
  459.    bottleneck_tensor: The penultimate output layer of the graph.
  460.    architecture: The name of the model architecture.
  461.  
  462.  Returns:
  463.    Nothing.
  464.  """
  465.   how_many_bottlenecks = 0
  466.   ensure_dir_exists(bottleneck_dir)
  467.   for label_name, label_lists in image_lists.items():
  468.     for category in ['training', 'testing', 'validation']:
  469.       category_list = label_lists[category]
  470.       for index, unused_base_name in enumerate(category_list):
  471.         get_or_create_bottleneck(
  472.             sess, image_lists, label_name, index, image_dir, category,
  473.             bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
  474.             resized_input_tensor, bottleneck_tensor, architecture)
  475.  
  476.         how_many_bottlenecks += 1
  477.         if how_many_bottlenecks % 100 == 0:
  478.           tf.logging.info(
  479.               str(how_many_bottlenecks) + ' bottleneck files created.')
  480.  
  481.  
  482. def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
  483.                                   bottleneck_dir, image_dir, jpeg_data_tensor,
  484.                                   decoded_image_tensor, resized_input_tensor,
  485.                                   bottleneck_tensor, architecture):
  486.   """Retrieves bottleneck values for cached images.
  487.  
  488.  If no distortions are being applied, this function can retrieve the cached
  489.  bottleneck values directly from disk for images. It picks a random set of
  490.  images from the specified category.
  491.  
  492.  Args:
  493.    sess: Current TensorFlow Session.
  494.    image_lists: Dictionary of training images for each label.
  495.    how_many: If positive, a random sample of this size will be chosen.
  496.    If negative, all bottlenecks will be retrieved.
  497.    category: Name string of which set to pull from - training, testing, or
  498.    validation.
  499.    bottleneck_dir: Folder string holding cached files of bottleneck values.
  500.    image_dir: Root folder string of the subfolders containing the training
  501.    images.
  502.    jpeg_data_tensor: The layer to feed jpeg image data into.
  503.    decoded_image_tensor: The output of decoding and resizing the image.
  504.    resized_input_tensor: The input node of the recognition graph.
  505.    bottleneck_tensor: The bottleneck output layer of the CNN graph.
  506.    architecture: The name of the model architecture.
  507.  
  508.  Returns:
  509.    List of bottleneck arrays, their corresponding ground truths, and the
  510.    relevant filenames.
  511.  """
  512.   class_count = len(image_lists.keys())
  513.   bottlenecks = []
  514.   ground_truths = []
  515.   filenames = []
  516.   if how_many >= 0:
  517.     # Retrieve a random sample of bottlenecks.
  518.     for unused_i in range(how_many):
  519.       label_index = random.randrange(class_count)
  520.       label_name = list(image_lists.keys())[label_index]
  521.       image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
  522.       image_name = get_image_path(image_lists, label_name, image_index,
  523.                                   image_dir, category)
  524.       bottleneck = get_or_create_bottleneck(
  525.           sess, image_lists, label_name, image_index, image_dir, category,
  526.           bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
  527.           resized_input_tensor, bottleneck_tensor, architecture)
  528.       ground_truth = np.zeros(class_count, dtype=np.float32)
  529.       ground_truth[label_index] = 1.0
  530.       bottlenecks.append(bottleneck)
  531.       ground_truths.append(ground_truth)
  532.       filenames.append(image_name)
  533.   else:
  534.     # Retrieve all bottlenecks.
  535.     for label_index, label_name in enumerate(image_lists.keys()):
  536.       for image_index, image_name in enumerate(
  537.           image_lists[label_name][category]):
  538.         image_name = get_image_path(image_lists, label_name, image_index,
  539.                                     image_dir, category)
  540.         bottleneck = get_or_create_bottleneck(
  541.             sess, image_lists, label_name, image_index, image_dir, category,
  542.             bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
  543.             resized_input_tensor, bottleneck_tensor, architecture)
  544.         ground_truth = np.zeros(class_count, dtype=np.float32)
  545.         ground_truth[label_index] = 1.0
  546.         bottlenecks.append(bottleneck)
  547.         ground_truths.append(ground_truth)
  548.         filenames.append(image_name)
  549.   return bottlenecks, ground_truths, filenames
  550.  
  551.  
  552. def get_random_distorted_bottlenecks(
  553.     sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
  554.     distorted_image, resized_input_tensor, bottleneck_tensor):
  555.   """Retrieves bottleneck values for training images, after distortions.
  556.  
  557.  If we're training with distortions like crops, scales, or flips, we have to
  558.  recalculate the full model for every image, and so we can't use cached
  559.  bottleneck values. Instead we find random images for the requested category,
  560.  run them through the distortion graph, and then the full graph to get the
  561.  bottleneck results for each.
  562.  
  563.  Args:
  564.    sess: Current TensorFlow Session.
  565.    image_lists: Dictionary of training images for each label.
  566.    how_many: The integer number of bottleneck values to return.
  567.    category: Name string of which set of images to fetch - training, testing,
  568.    or validation.
  569.    image_dir: Root folder string of the subfolders containing the training
  570.    images.
  571.    input_jpeg_tensor: The input layer we feed the image data to.
  572.    distorted_image: The output node of the distortion graph.
  573.    resized_input_tensor: The input node of the recognition graph.
  574.    bottleneck_tensor: The bottleneck output layer of the CNN graph.
  575.  
  576.  Returns:
  577.    List of bottleneck arrays and their corresponding ground truths.
  578.  """
  579.   class_count = len(image_lists.keys())
  580.   bottlenecks = []
  581.   ground_truths = []
  582.   for unused_i in range(how_many):
  583.     label_index = random.randrange(class_count)
  584.     label_name = list(image_lists.keys())[label_index]
  585.     image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
  586.     image_path = get_image_path(image_lists, label_name, image_index, image_dir,
  587.                                 category)
  588.     if not gfile.Exists(image_path):
  589.       tf.logging.fatal('File does not exist %s', image_path)
  590.     jpeg_data = gfile.FastGFile(image_path, 'rb').read()
  591.     # Note that we materialize the distorted_image_data as a numpy array before
  592.     # sending running inference on the image. This involves 2 memory copies and
  593.     # might be optimized in other implementations.
  594.     distorted_image_data = sess.run(distorted_image,
  595.                                     {input_jpeg_tensor: jpeg_data})
  596.     bottleneck_values = sess.run(bottleneck_tensor,
  597.                                  {resized_input_tensor: distorted_image_data})
  598.     bottleneck_values = np.squeeze(bottleneck_values)
  599.     ground_truth = np.zeros(class_count, dtype=np.float32)
  600.     ground_truth[label_index] = 1.0
  601.     bottlenecks.append(bottleneck_values)
  602.     ground_truths.append(ground_truth)
  603.   return bottlenecks, ground_truths
  604.  
  605.  
  606. def should_distort_images(flip_left_right, random_crop, random_scale,
  607.                           random_brightness):
  608.   """Whether any distortions are enabled, from the input flags.
  609.  
  610.  Args:
  611.    flip_left_right: Boolean whether to randomly mirror images horizontally.
  612.    random_crop: Integer percentage setting the total margin used around the
  613.    crop box.
  614.    random_scale: Integer percentage of how much to vary the scale by.
  615.    random_brightness: Integer range to randomly multiply the pixel values by.
  616.  
  617.  Returns:
  618.    Boolean value indicating whether any distortions should be applied.
  619.  """
  620.   return (flip_left_right or (random_crop != 0) or (random_scale != 0) or
  621.           (random_brightness != 0))
  622.  
  623.  
  624. def add_input_distortions(flip_left_right, random_crop, random_scale,
  625.                           random_brightness, input_width, input_height,
  626.                           input_depth, input_mean, input_std):
  627.   """Creates the operations to apply the specified distortions.
  628.  
  629.  During training it can help to improve the results if we run the images
  630.  through simple distortions like crops, scales, and flips. These reflect the
  631.  kind of variations we expect in the real world, and so can help train the
  632.  model to cope with natural data more effectively. Here we take the supplied
  633.  parameters and construct a network of operations to apply them to an image.
  634.  
  635.  Cropping
  636.  ~~~~~~~~
  637.  
  638.  Cropping is done by placing a bounding box at a random position in the full
  639.  image. The cropping parameter controls the size of that box relative to the
  640.  input image. If it's zero, then the box is the same size as the input and no
  641.  cropping is performed. If the value is 50%, then the crop box will be half the
  642.  width and height of the input. In a diagram it looks like this:
  643.  
  644.  <       width         >
  645.  +---------------------+
  646.  |                     |
  647.  |   width - crop%     |
  648.  |    <      >         |
  649.  |    +------+         |
  650.  |    |      |         |
  651.  |    |      |         |
  652.  |    |      |         |
  653.  |    +------+         |
  654.  |                     |
  655.  |                     |
  656.  +---------------------+
  657.  
  658.  Scaling
  659.  ~~~~~~~
  660.  
  661.  Scaling is a lot like cropping, except that the bounding box is always
  662.  centered and its size varies randomly within the given range. For example if
  663.  the scale percentage is zero, then the bounding box is the same size as the
  664.  input and no scaling is applied. If it's 50%, then the bounding box will be in
  665.  a random range between half the width and height and full size.
  666.  
  667.  Args:
  668.    flip_left_right: Boolean whether to randomly mirror images horizontally.
  669.    random_crop: Integer percentage setting the total margin used around the
  670.    crop box.
  671.    random_scale: Integer percentage of how much to vary the scale by.
  672.    random_brightness: Integer range to randomly multiply the pixel values by.
  673.    graph.
  674.    input_width: Horizontal size of expected input image to model.
  675.    input_height: Vertical size of expected input image to model.
  676.    input_depth: How many channels the expected input image should have.
  677.    input_mean: Pixel value that should be zero in the image for the graph.
  678.    input_std: How much to divide the pixel values by before recognition.
  679.  
  680.  Returns:
  681.    The jpeg input layer and the distorted result tensor.
  682.  """
  683.  
  684.   jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput')
  685.   decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
  686.   decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)
  687.   decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
  688.   margin_scale = 1.0 + (random_crop / 100.0)
  689.   resize_scale = 1.0 + (random_scale / 100.0)
  690.   margin_scale_value = tf.constant(margin_scale)
  691.   resize_scale_value = tf.random_uniform(tensor_shape.scalar(),
  692.                                          minval=1.0,
  693.                                          maxval=resize_scale)
  694.   scale_value = tf.multiply(margin_scale_value, resize_scale_value)
  695.   precrop_width = tf.multiply(scale_value, input_width)
  696.   precrop_height = tf.multiply(scale_value, input_height)
  697.   precrop_shape = tf.stack([precrop_height, precrop_width])
  698.   precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32)
  699.   precropped_image = tf.image.resize_bilinear(decoded_image_4d,
  700.                                               precrop_shape_as_int)
  701.   precropped_image_3d = tf.squeeze(precropped_image, squeeze_dims=[0])
  702.   cropped_image = tf.random_crop(precropped_image_3d,
  703.                                  [input_height, input_width, input_depth])
  704.   if flip_left_right:
  705.     flipped_image = tf.image.random_flip_left_right(cropped_image)
  706.   else:
  707.     flipped_image = cropped_image
  708.   brightness_min = 1.0 - (random_brightness / 100.0)
  709.   brightness_max = 1.0 + (random_brightness / 100.0)
  710.   brightness_value = tf.random_uniform(tensor_shape.scalar(),
  711.                                        minval=brightness_min,
  712.                                        maxval=brightness_max)
  713.   brightened_image = tf.multiply(flipped_image, brightness_value)
  714.   offset_image = tf.subtract(brightened_image, input_mean)
  715.   mul_image = tf.multiply(offset_image, 1.0 / input_std)
  716.   distort_result = tf.expand_dims(mul_image, 0, name='DistortResult')
  717.   return jpeg_data, distort_result
  718.  
  719.  
  720. def variable_summaries(var):
  721.   """Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
  722.   with tf.name_scope('summaries'):
  723.     mean = tf.reduce_mean(var)
  724.     tf.summary.scalar('mean', mean)
  725.     with tf.name_scope('stddev'):
  726.       stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
  727.     tf.summary.scalar('stddev', stddev)
  728.     tf.summary.scalar('max', tf.reduce_max(var))
  729.     tf.summary.scalar('min', tf.reduce_min(var))
  730.     tf.summary.histogram('histogram', var)
  731.  
  732.  
  733. def add_final_training_ops(class_count, final_tensor_name, bottleneck_tensor,
  734.                            bottleneck_tensor_size, quantize_layer):
  735.   """Adds a new softmax and fully-connected layer for training.
  736.  
  737.  We need to retrain the top layer to identify our new classes, so this function
  738.  adds the right operations to the graph, along with some variables to hold the
  739.  weights, and then sets up all the gradients for the backward pass.
  740.  
  741.  The set up for the softmax and fully-connected layers is based on:
  742.  https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html
  743.  
  744.  Args:
  745.    class_count: Integer of how many categories of things we're trying to
  746.        recognize.
  747.    final_tensor_name: Name string for the new final node that produces results.
  748.    bottleneck_tensor: The output of the main CNN graph.
  749.    bottleneck_tensor_size: How many entries in the bottleneck vector.
  750.    quantize_layer: Boolean, specifying whether the newly added layer should be
  751.        quantized.
  752.  
  753.  Returns:
  754.    The tensors for the training and cross entropy results, and tensors for the
  755.    bottleneck input and ground truth input.
  756.  """
  757.   with tf.name_scope('input'):
  758.     bottleneck_input = tf.placeholder_with_default(
  759.         bottleneck_tensor,
  760.         shape=[None, bottleneck_tensor_size],
  761.         name='BottleneckInputPlaceholder')
  762.  
  763.     ground_truth_input = tf.placeholder(tf.float32,
  764.                                         [None, class_count],
  765.                                         name='GroundTruthInput')
  766.  
  767.   # Organizing the following ops as `final_training_ops` so they're easier
  768.   # to see in TensorBoard
  769.   layer_name = 'final_training_ops'
  770.   with tf.name_scope(layer_name):
  771.     with tf.name_scope('weights'):
  772.       initial_value = tf.truncated_normal(
  773.           [bottleneck_tensor_size, class_count], stddev=0.001)
  774.       layer_weights = tf.Variable(initial_value, name='final_weights')
  775.       if quantize_layer:
  776.         quantized_layer_weights = quant_ops.MovingAvgQuantize(
  777.             layer_weights, is_training=True)
  778.         variable_summaries(quantized_layer_weights)
  779.  
  780.       variable_summaries(layer_weights)
  781.     with tf.name_scope('biases'):
  782.       layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')
  783.       if quantize_layer:
  784.         quantized_layer_biases = quant_ops.MovingAvgQuantize(
  785.             layer_biases, is_training=True)
  786.         variable_summaries(quantized_layer_biases)
  787.  
  788.       variable_summaries(layer_biases)
  789.  
  790.     with tf.name_scope('Wx_plus_b'):
  791.       if quantize_layer:
  792.         logits = tf.matmul(bottleneck_input,
  793.                            quantized_layer_weights) + quantized_layer_biases
  794.         logits = quant_ops.MovingAvgQuantize(
  795.             logits,
  796.             init_min=-32.0,
  797.             init_max=32.0,
  798.             is_training=True,
  799.             num_bits=8,
  800.             narrow_range=False,
  801.             ema_decay=0.5)
  802.         tf.summary.histogram('pre_activations', logits)
  803.       else:
  804.         logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases
  805.         tf.summary.histogram('pre_activations', logits)
  806.  
  807.   final_tensor = tf.nn.softmax(logits, name=final_tensor_name)
  808.  
  809.   tf.summary.histogram('activations', final_tensor)
  810.  
  811.   with tf.name_scope('cross_entropy'):
  812.     cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
  813.         labels=ground_truth_input, logits=logits)
  814.     with tf.name_scope('total'):
  815.       cross_entropy_mean = tf.reduce_mean(cross_entropy)
  816.  
  817.   tf.summary.scalar('cross_entropy', cross_entropy_mean)
  818.  
  819.   with tf.name_scope('train'):
  820.     optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)
  821.     train_step = optimizer.minimize(cross_entropy_mean)
  822.  
  823.   return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input,
  824.           final_tensor)
  825.  
  826.  
  827. def add_evaluation_step(result_tensor, ground_truth_tensor):
  828.   """Inserts the operations we need to evaluate the accuracy of our results.
  829.  
  830.  Args:
  831.    result_tensor: The new final node that produces results.
  832.    ground_truth_tensor: The node we feed ground truth data
  833.    into.
  834.  
  835.  Returns:
  836.    Tuple of (evaluation step, prediction).
  837.  """
  838.   with tf.name_scope('accuracy'):
  839.     with tf.name_scope('correct_prediction'):
  840.       prediction = tf.argmax(result_tensor, 1)
  841.       correct_prediction = tf.equal(
  842.           prediction, tf.argmax(ground_truth_tensor, 1))
  843.     with tf.name_scope('accuracy'):
  844.       evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  845.   tf.summary.scalar('accuracy', evaluation_step)
  846.   return evaluation_step, prediction
  847.  
  848.  
  849. def save_graph_to_file(sess, graph, graph_file_name):
  850.   output_graph_def = graph_util.convert_variables_to_constants(
  851.       sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
  852.  
  853.   with gfile.FastGFile(graph_file_name, 'wb') as f:
  854.     f.write(output_graph_def.SerializeToString())
  855.   return
  856.  
  857.  
  858. def prepare_file_system():
  859.   # Setup the directory we'll write summaries to for TensorBoard
  860.   if tf.gfile.Exists(FLAGS.summaries_dir):
  861.     tf.gfile.DeleteRecursively(FLAGS.summaries_dir)
  862.   tf.gfile.MakeDirs(FLAGS.summaries_dir)
  863.   if FLAGS.intermediate_store_frequency > 0:
  864.     ensure_dir_exists(FLAGS.intermediate_output_graphs_dir)
  865.   return
  866.  
  867.  
  868. def create_model_info(architecture):
  869.   """Given the name of a model architecture, returns information about it.
  870.  
  871.  There are different base image recognition pretrained models that can be
  872.  retrained using transfer learning, and this function translates from the name
  873.  of a model to the attributes that are needed to download and train with it.
  874.  
  875.  Args:
  876.    architecture: Name of a model architecture.
  877.  
  878.  Returns:
  879.    Dictionary of information about the model, or None if the name isn't
  880.    recognized
  881.  
  882.  Raises:
  883.    ValueError: If architecture name is unknown.
  884.  """
  885.   architecture = architecture.lower()
  886.   is_quantized = False
  887.   if architecture == 'inception_v3':
  888.     # pylint: disable=line-too-long
  889.     data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
  890.     # pylint: enable=line-too-long
  891.     bottleneck_tensor_name = 'pool_3/_reshape:0'
  892.     bottleneck_tensor_size = 2048
  893.     input_width = 299
  894.     input_height = 299
  895.     input_depth = 3
  896.     resized_input_tensor_name = 'Mul:0'
  897.     model_file_name = 'classify_image_graph_def.pb'
  898.     input_mean = 128
  899.     input_std = 128
  900.   elif architecture.startswith('mobilenet_'):
  901.     parts = architecture.split('_')
  902.     if len(parts) != 3 and len(parts) != 4:
  903.       tf.logging.error("Couldn't understand architecture name '%s'",
  904.                        architecture)
  905.       return None
  906.     version_string = parts[1]
  907.     if (version_string != '1.0' and version_string != '0.75' and
  908.         version_string != '0.50' and version_string != '0.25'):
  909.       tf.logging.error(
  910.           """"The Mobilenet version should be '1.0', '0.75', '0.50', or '0.25',
  911.  but found '%s' for architecture '%s'""",
  912.           version_string, architecture)
  913.       return None
  914.     size_string = parts[2]
  915.     if (size_string != '224' and size_string != '192' and
  916.         size_string != '160' and size_string != '128'):
  917.       tf.logging.error(
  918.           """The Mobilenet input size should be '224', '192', '160', or '128',
  919. but found '%s' for architecture '%s'""",
  920.           size_string, architecture)
  921.       return None
  922.     if len(parts) == 3:
  923.       is_quantized = False
  924.     else:
  925.       if parts[3] != 'quantized':
  926.         tf.logging.error(
  927.             "Couldn't understand architecture suffix '%s' for '%s'", parts[3],
  928.             architecture)
  929.         return None
  930.       is_quantized = True
  931.  
  932.     if is_quantized:
  933.       data_url = 'http://download.tensorflow.org/models/mobilenet_v1_'
  934.       data_url += version_string + '_' + size_string + '_quantized_frozen.tgz'
  935.       bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0'
  936.       resized_input_tensor_name = 'Placeholder:0'
  937.       model_dir_name = ('mobilenet_v1_' + version_string + '_' + size_string +
  938.                         '_quantized_frozen')
  939.       model_base_name = 'quantized_frozen_graph.pb'
  940.  
  941.     else:
  942.       data_url = 'http://download.tensorflow.org/models/mobilenet_v1_'
  943.       data_url += version_string + '_' + size_string + '_frozen.tgz'
  944.       bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0'
  945.       resized_input_tensor_name = 'input:0'
  946.       model_dir_name = 'mobilenet_v1_' + version_string + '_' + size_string
  947.       model_base_name = 'frozen_graph.pb'
  948.  
  949.     bottleneck_tensor_size = 1001
  950.     input_width = int(size_string)
  951.     input_height = int(size_string)
  952.     input_depth = 3
  953.     model_file_name = os.path.join(model_dir_name, model_base_name)
  954.     input_mean = 127.5
  955.     input_std = 127.5
  956.   else:
  957.     tf.logging.error("Couldn't understand architecture name '%s'", architecture)
  958.     raise ValueError('Unknown architecture', architecture)
  959.  
  960.   return {
  961.       'data_url': data_url,
  962.       'bottleneck_tensor_name': bottleneck_tensor_name,
  963.       'bottleneck_tensor_size': bottleneck_tensor_size,
  964.       'input_width': input_width,
  965.       'input_height': input_height,
  966.       'input_depth': input_depth,
  967.       'resized_input_tensor_name': resized_input_tensor_name,
  968.       'model_file_name': model_file_name,
  969.       'input_mean': input_mean,
  970.       'input_std': input_std,
  971.       'quantize_layer': is_quantized,
  972.   }
  973.  
  974.  
  975. def add_jpeg_decoding(input_width, input_height, input_depth, input_mean,
  976.                       input_std):
  977.   """Adds operations that perform JPEG decoding and resizing to the graph..
  978.  
  979.  Args:
  980.    input_width: Desired width of the image fed into the recognizer graph.
  981.    input_height: Desired width of the image fed into the recognizer graph.
  982.    input_depth: Desired channels of the image fed into the recognizer graph.
  983.    input_mean: Pixel value that should be zero in the image for the graph.
  984.    input_std: How much to divide the pixel values by before recognition.
  985.  
  986.  Returns:
  987.    Tensors for the node to feed JPEG data into, and the output of the
  988.      preprocessing steps.
  989.  """
  990.   jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput')
  991.   decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
  992.   decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)
  993.   decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
  994.   resize_shape = tf.stack([input_height, input_width])
  995.   resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32)
  996.   resized_image = tf.image.resize_bilinear(decoded_image_4d,
  997.                                            resize_shape_as_int)
  998.   offset_image = tf.subtract(resized_image, input_mean)
  999.   mul_image = tf.multiply(offset_image, 1.0 / input_std)
  1000.   return jpeg_data, mul_image
  1001.  
  1002.  
  1003. def main(_):
  1004.   # Needed to make sure the logging output is visible.
  1005.   # See https://github.com/tensorflow/tensorflow/issues/3047
  1006.   tf.logging.set_verbosity(tf.logging.INFO)
  1007.  
  1008.   # Prepare necessary directories that can be used during training
  1009.   prepare_file_system()
  1010.  
  1011.   # Gather information about the model architecture we'll be using.
  1012.   model_info = create_model_info(FLAGS.architecture)
  1013.   if not model_info:
  1014.     tf.logging.error('Did not recognize architecture flag')
  1015.     return -1
  1016.  
  1017.   # Set up the pre-trained graph.
  1018.   maybe_download_and_extract(model_info['data_url'])
  1019.   graph, bottleneck_tensor, resized_image_tensor = (
  1020.       create_model_graph(model_info))
  1021.  
  1022.   # Look at the folder structure, and create lists of all the images.
  1023.   image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage,
  1024.                                    FLAGS.validation_percentage)
  1025.   class_count = len(image_lists.keys())
  1026.   if class_count == 0:
  1027.     tf.logging.error('No valid folders of images found at ' + FLAGS.image_dir)
  1028.     return -1
  1029.   if class_count == 1:
  1030.     tf.logging.error('Only one valid folder of images found at ' +
  1031.                      FLAGS.image_dir +
  1032.                      ' - multiple classes are needed for classification.')
  1033.     return -1
  1034.  
  1035.   # See if the command-line flags mean we're applying any distortions.
  1036.   do_distort_images = should_distort_images(
  1037.       FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,
  1038.       FLAGS.random_brightness)
  1039.  
  1040.   with tf.Session(graph=graph) as sess:
  1041.     # Set up the image decoding sub-graph.
  1042.     jpeg_data_tensor, decoded_image_tensor = add_jpeg_decoding(
  1043.         model_info['input_width'], model_info['input_height'],
  1044.         model_info['input_depth'], model_info['input_mean'],
  1045.         model_info['input_std'])
  1046.  
  1047.     if do_distort_images:
  1048.       # We will be applying distortions, so setup the operations we'll need.
  1049.       (distorted_jpeg_data_tensor,
  1050.        distorted_image_tensor) = add_input_distortions(
  1051.            FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,
  1052.            FLAGS.random_brightness, model_info['input_width'],
  1053.            model_info['input_height'], model_info['input_depth'],
  1054.            model_info['input_mean'], model_info['input_std'])
  1055.     else:
  1056.       # We'll make sure we've calculated the 'bottleneck' image summaries and
  1057.       # cached them on disk.
  1058.       cache_bottlenecks(sess, image_lists, FLAGS.image_dir,
  1059.                         FLAGS.bottleneck_dir, jpeg_data_tensor,
  1060.                         decoded_image_tensor, resized_image_tensor,
  1061.                         bottleneck_tensor, FLAGS.architecture)
  1062.  
  1063.     # Add the new layer that we'll be training.
  1064.     (train_step, cross_entropy, bottleneck_input, ground_truth_input,
  1065.      final_tensor) = add_final_training_ops(
  1066.          len(image_lists.keys()), FLAGS.final_tensor_name, bottleneck_tensor,
  1067.          model_info['bottleneck_tensor_size'], model_info['quantize_layer'])
  1068.  
  1069.     # Create the operations we need to evaluate the accuracy of our new layer.
  1070.     evaluation_step, prediction = add_evaluation_step(
  1071.         final_tensor, ground_truth_input)
  1072.  
  1073.     # Merge all the summaries and write them out to the summaries_dir
  1074.     merged = tf.summary.merge_all()
  1075.     train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',
  1076.                                          sess.graph)
  1077.  
  1078.     validation_writer = tf.summary.FileWriter(
  1079.         FLAGS.summaries_dir + '/validation')
  1080.  
  1081.     # Set up all our weights to their initial default values.
  1082.     init = tf.global_variables_initializer()
  1083.     sess.run(init)
  1084.  
  1085.     # Run the training for as many cycles as requested on the command line.
  1086.     for i in range(FLAGS.how_many_training_steps):
  1087.       # Get a batch of input bottleneck values, either calculated fresh every
  1088.       # time with distortions applied, or from the cache stored on disk.
  1089.       if do_distort_images:
  1090.         (train_bottlenecks,
  1091.          train_ground_truth) = get_random_distorted_bottlenecks(
  1092.              sess, image_lists, FLAGS.train_batch_size, 'training',
  1093.              FLAGS.image_dir, distorted_jpeg_data_tensor,
  1094.              distorted_image_tensor, resized_image_tensor, bottleneck_tensor)
  1095.       else:
  1096.         (train_bottlenecks,
  1097.          train_ground_truth, _) = get_random_cached_bottlenecks(
  1098.              sess, image_lists, FLAGS.train_batch_size, 'training',
  1099.              FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
  1100.              decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
  1101.              FLAGS.architecture)
  1102.       # Feed the bottlenecks and ground truth into the graph, and run a training
  1103.       # step. Capture training summaries for TensorBoard with the `merged` op.
  1104.       train_summary, _ = sess.run(
  1105.           [merged, train_step],
  1106.           feed_dict={bottleneck_input: train_bottlenecks,
  1107.                      ground_truth_input: train_ground_truth})
  1108.       train_writer.add_summary(train_summary, i)
  1109.  
  1110.       # Every so often, print out how well the graph is training.
  1111.       is_last_step = (i + 1 == FLAGS.how_many_training_steps)
  1112.       if (i % FLAGS.eval_step_interval) == 0 or is_last_step:
  1113.         train_accuracy, cross_entropy_value = sess.run(
  1114.             [evaluation_step, cross_entropy],
  1115.             feed_dict={bottleneck_input: train_bottlenecks,
  1116.                        ground_truth_input: train_ground_truth})
  1117.         tf.logging.info('%s: Step %d: Train accuracy = %.1f%%' %
  1118.                         (datetime.now(), i, train_accuracy * 100))
  1119.         tf.logging.info('%s: Step %d: Cross entropy = %f' %
  1120.                         (datetime.now(), i, cross_entropy_value))
  1121.         validation_bottlenecks, validation_ground_truth, _ = (
  1122.             get_random_cached_bottlenecks(
  1123.                 sess, image_lists, FLAGS.validation_batch_size, 'validation',
  1124.                 FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
  1125.                 decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
  1126.                 FLAGS.architecture))
  1127.         # Run a validation step and capture training summaries for TensorBoard
  1128.         # with the `merged` op.
  1129.         validation_summary, validation_accuracy = sess.run(
  1130.             [merged, evaluation_step],
  1131.             feed_dict={bottleneck_input: validation_bottlenecks,
  1132.                        ground_truth_input: validation_ground_truth})
  1133.         validation_writer.add_summary(validation_summary, i)
  1134.         tf.logging.info('%s: Step %d: Validation accuracy = %.1f%% (N=%d)' %
  1135.                         (datetime.now(), i, validation_accuracy * 100,
  1136.                          len(validation_bottlenecks)))
  1137.  
  1138.       # Store intermediate results
  1139.       intermediate_frequency = FLAGS.intermediate_store_frequency
  1140.  
  1141.       if (intermediate_frequency > 0 and (i % intermediate_frequency == 0)
  1142.           and i > 0):
  1143.         intermediate_file_name = (FLAGS.intermediate_output_graphs_dir +
  1144.                                   'intermediate_' + str(i) + '.pb')
  1145.         tf.logging.info('Save intermediate result to : ' +
  1146.                         intermediate_file_name)
  1147.         save_graph_to_file(sess, graph, intermediate_file_name)
  1148.  
  1149.     # We've completed all our training, so run a final test evaluation on
  1150.     # some new images we haven't used before.
  1151.     test_bottlenecks, test_ground_truth, test_filenames = (
  1152.         get_random_cached_bottlenecks(
  1153.             sess, image_lists, FLAGS.test_batch_size, 'testing',
  1154.             FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
  1155.             decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
  1156.             FLAGS.architecture))
  1157.     test_accuracy, predictions = sess.run(
  1158.         [evaluation_step, prediction],
  1159.         feed_dict={bottleneck_input: test_bottlenecks,
  1160.                    ground_truth_input: test_ground_truth})
  1161.     tf.logging.info('Final test accuracy = %.1f%% (N=%d)' %
  1162.                     (test_accuracy * 100, len(test_bottlenecks)))
  1163.  
  1164.     if FLAGS.print_misclassified_test_images:
  1165.       tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===')
  1166.       for i, test_filename in enumerate(test_filenames):
  1167.         if predictions[i] != test_ground_truth[i].argmax():
  1168.           tf.logging.info('%70s  %s' %
  1169.                           (test_filename,
  1170.                            list(image_lists.keys())[predictions[i]]))
  1171.  
  1172.     # Write out the trained graph and labels with the weights stored as
  1173.     # constants.
  1174.     save_graph_to_file(sess, graph, FLAGS.output_graph)
  1175.     with gfile.FastGFile(FLAGS.output_labels, 'w') as f:
  1176.       f.write('\n'.join(image_lists.keys()) + '\n')
  1177.  
  1178.  
  1179. if __name__ == '__main__':
  1180.   parser = argparse.ArgumentParser()
  1181.   parser.add_argument(
  1182.       '--image_dir',
  1183.       type=str,
  1184.       default='',
  1185.       help='Path to folders of labeled images.'
  1186.   )
  1187.   parser.add_argument(
  1188.       '--output_graph',
  1189.       type=str,
  1190.       default='/tmp/output_graph.pb',
  1191.       help='Where to save the trained graph.'
  1192.   )
  1193.   parser.add_argument(
  1194.       '--intermediate_output_graphs_dir',
  1195.       type=str,
  1196.       default='/tmp/intermediate_graph/',
  1197.       help='Where to save the intermediate graphs.'
  1198.   )
  1199.   parser.add_argument(
  1200.       '--intermediate_store_frequency',
  1201.       type=int,
  1202.       default=0,
  1203.       help="""\
  1204.         How many steps to store intermediate graph. If "0" then will not
  1205.         store.\
  1206.      """
  1207.   )
  1208.   parser.add_argument(
  1209.       '--output_labels',
  1210.       type=str,
  1211.       default='/tmp/output_labels.txt',
  1212.       help='Where to save the trained graph\'s labels.'
  1213.   )
  1214.   parser.add_argument(
  1215.       '--summaries_dir',
  1216.       type=str,
  1217.       default='/tmp/retrain_logs',
  1218.       help='Where to save summary logs for TensorBoard.'
  1219.   )
  1220.   parser.add_argument(
  1221.       '--how_many_training_steps',
  1222.       type=int,
  1223.       default=4000,
  1224.       help='How many training steps to run before ending.'
  1225.   )
  1226.   parser.add_argument(
  1227.       '--learning_rate',
  1228.       type=float,
  1229.       default=0.01,
  1230.       help='How large a learning rate to use when training.'
  1231.   )
  1232.   parser.add_argument(
  1233.       '--testing_percentage',
  1234.       type=int,
  1235.       default=10,
  1236.       help='What percentage of images to use as a test set.'
  1237.   )
  1238.   parser.add_argument(
  1239.       '--validation_percentage',
  1240.       type=int,
  1241.       default=10,
  1242.       help='What percentage of images to use as a validation set.'
  1243.   )
  1244.   parser.add_argument(
  1245.       '--eval_step_interval',
  1246.       type=int,
  1247.       default=10,
  1248.       help='How often to evaluate the training results.'
  1249.   )
  1250.   parser.add_argument(
  1251.       '--train_batch_size',
  1252.       type=int,
  1253.       default=100,
  1254.       help='How many images to train on at a time.'
  1255.   )
  1256.   parser.add_argument(
  1257.       '--test_batch_size',
  1258.       type=int,
  1259.       default=-1,
  1260.       help="""\
  1261.      How many images to test on. This test set is only used once, to evaluate
  1262.      the final accuracy of the model after training completes.
  1263.      A value of -1 causes the entire test set to be used, which leads to more
  1264.      stable results across runs.\
  1265.      """
  1266.   )
  1267.   parser.add_argument(
  1268.       '--validation_batch_size',
  1269.       type=int,
  1270.       default=100,
  1271.       help="""\
  1272.      How many images to use in an evaluation batch. This validation set is
  1273.      used much more often than the test set, and is an early indicator of how
  1274.      accurate the model is during training.
  1275.      A value of -1 causes the entire validation set to be used, which leads to
  1276.      more stable results across training iterations, but may be slower on large
  1277.      training sets.\
  1278.      """
  1279.   )
  1280.   parser.add_argument(
  1281.       '--print_misclassified_test_images',
  1282.       default=False,
  1283.       help="""\
  1284.      Whether to print out a list of all misclassified test images.\
  1285.      """,
  1286.       action='store_true'
  1287.   )
  1288.   parser.add_argument(
  1289.       '--model_dir',
  1290.       type=str,
  1291.       default='/tmp/imagenet',
  1292.       help="""\
  1293.      Path to classify_image_graph_def.pb,
  1294.      imagenet_synset_to_human_label_map.txt, and
  1295.      imagenet_2012_challenge_label_map_proto.pbtxt.\
  1296.      """
  1297.   )
  1298.   parser.add_argument(
  1299.       '--bottleneck_dir',
  1300.       type=str,
  1301.       default='/tmp/bottleneck',
  1302.       help='Path to cache bottleneck layer values as files.'
  1303.   )
  1304.   parser.add_argument(
  1305.       '--final_tensor_name',
  1306.       type=str,
  1307.       default='final_result',
  1308.       help="""\
  1309.      The name of the output classification layer in the retrained graph.\
  1310.      """
  1311.   )
  1312.   parser.add_argument(
  1313.       '--flip_left_right',
  1314.       default=False,
  1315.       help="""\
  1316.      Whether to randomly flip half of the training images horizontally.\
  1317.      """,
  1318.       action='store_true'
  1319.   )
  1320.   parser.add_argument(
  1321.       '--random_crop',
  1322.       type=int,
  1323.       default=0,
  1324.       help="""\
  1325.      A percentage determining how much of a margin to randomly crop off the
  1326.      training images.\
  1327.      """
  1328.   )
  1329.   parser.add_argument(
  1330.       '--random_scale',
  1331.       type=int,
  1332.       default=0,
  1333.       help="""\
  1334.      A percentage determining how much to randomly scale up the size of the
  1335.      training images by.\
  1336.      """
  1337.   )
  1338.   parser.add_argument(
  1339.       '--random_brightness',
  1340.       type=int,
  1341.       default=0,
  1342.       help="""\
  1343.      A percentage determining how much to randomly multiply the training image
  1344.      input pixels up or down by.\
  1345.      """
  1346.   )
  1347.   parser.add_argument(
  1348.       '--architecture',
  1349.       type=str,
  1350.       default='inception_v3',
  1351.       help="""\
  1352.      Which model architecture to use. 'inception_v3' is the most accurate, but
  1353.      also the slowest. For faster or smaller models, chose a MobileNet with the
  1354.      form 'mobilenet_<parameter size>_<input_size>[_quantized]'. For example,
  1355.      'mobilenet_1.0_224' will pick a model that is 17 MB in size and takes 224
  1356.      pixel input images, while 'mobilenet_0.25_128_quantized' will choose a much
  1357.      less accurate, but smaller and faster network that's 920 KB on disk and
  1358.      takes 128x128 images. See https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html
  1359.      for more information on Mobilenet.\
  1360.      """)
  1361.   FLAGS, unparsed = parser.parse_known_args()
  1362.   tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement