TensorFlow from entry to Mastery (iii): Analysis of routines Code of Imagenet cases

Source: Internet
Author: User
Tags readable
# Copyright 2015 Google Inc.
All Rights Reserved.
# # Licensed under the Apache License, Version 2.0 (the "License");
# You could not use this file, except in compliance with the License. # You may obtain a copy of the License in # # http://www.apache.org/licenses/LICENSE-2.0 # unless required by applic Able or agreed to in writing, software # Distributed under the License be distributed on ' as is ' basis, # without W
Arranties or CONDITIONS of any KIND, either express OR implied.
# The License for the specific language governing permissions and # Limitations under the License. # ============================================================================== "" "Simple Image classification With Inception.
Simple use of Inception image classification routines Run classification with Inception trained on imagenet the data set. Run the image classification task, using the Inception model <span style= "font-family:arial, Helvetica, Sans-serif," which was trained on the Imagenet 2012 game data set. >this program creates a graph from saved GraphdefProtocol buffer,</span> 
and runs inference on a input JPEG image.

IT outputs human readable strings of the top 5 predictions along with their probabilities. The program creates a graph from a saved graphdef Protobuffer file, and then predicts a single input JPEG image.
It will give the highest probability of 5 predictions, provided in a readable string form.

Change the--image_file argument to any JPG to compute a classification of that image.

Please do not have the tutorial and website for a detailed description the ' how ' to ' use ' script to perform image recognition. https://tensorflow.org/tutorials/image_recognition/"" "__future__ import Absolute_import from __future__ Import Division from __FUTURE__ Import print_function import os.path import re import sys import tarfile import numpy as NP fro M six.moves import urllib import tensorflow as tf FLAGS = Tf.app.flags.FLAGS # classify_image_graph_def.pb: # Binary R
Epresentation of the GRAPHDEF protocol buffer.
# Imagenet_synset_to_human_label_map.txt: # map from Synset ID to a human readable string. # Imagenet_2012_challenge_label_map_proto.pbtxt: # Text Representation of a protocol buffer mapping a label to Synset ID. Tf.app.flags.DEFINE_string (' Model_dir ', '/tmp/imagenet ', "" "" Path to Classify_image_graph_def.pb, "" "" "" image
Net_synset_to_human_label_map.txt, and "" "" "" Imagenet_2012_challenge_label_map_proto.pbtxt. "" "" Tf.app.flags.DEFINE_string (' image_file ', ', ' "" "absolute path to image file." ") TF.APP.FLAGS.D

Efine_integer (' Num_top_predictions ', 5, "" "" Display this many predictions. "") # Pylint:disable=line-too-long Data_url = ' http://download.tensorflow.org/models/image/imagenet/ Inception-2015-12-05.tgz ' # Pylint:enable=line-too-long class Nodelookup (object): "" "Converts integer node ID ' s to Hu

  Man readable labels. "" " def __init__ (self, Label_lookup_path=none, Uid_lookup_path=none): If not LABEL_LOOKUP_PA Th:label_lookup_path = Os.path.join (Flags.model_dir, ' IMAGENET_2012_CHALLENGE_LABEL_MAP_PROTO.PBtxt ') if not Uid_lookup_path:uid_lookup_path = Os.path.join (Flags.model_dir, ' Imagenet_synset_to_hu Man_label_map.txt ') Self.node_lookup = Self.load (Label_lookup_path, Uid_lookup_path) def load (self, LABEL_LOOKUP_PA

    Th, Uid_lookup_path): "" "loads a human readable 中文版 name for each softmax node.
      Args:label_lookup_path:string UID to Integer node ID.

    Uid_lookup_path:string UID to human-readable string.
    Returns:dict from the integer node ID to human-readable string. ' "' If not Tf.gfile.Exists (Uid_lookup_path): Tf.logging.fatal (' File does not exist%s ', Uid_lookup_path) if Not Tf.gfile.Exists (Label_lookup_path): Tf.logging.fatal (' File does not exist%s ', Label_lookup_path) # loads M
    Apping from string UID to human-readable string proto_as_ascii_lines = Tf.gfile.GFile (Uid_lookup_path). ReadLines ()
     Uid_to_human = {} p = re.compile (R ' [n\d]*[\s,]* ') for line in Proto_as_ascii_lines: Parsed_items = P.findall (line) uid = parsed_items[0] human_string = parsed_items[2] uid_to_human[uid] =
    Human_string # Loads mapping from string UID to Integer node ID.
      Node_id_to_uid = {} Proto_as_ascii = Tf.gfile.GFile (Label_lookup_path). ReadLines () for line in Proto_as_ascii: If Line.startswith (' Target_class: '): target_class = Int (line.split (': ') [1]) If Line.startswith (' Targ Et_class_string: '): target_class_string = Line.split (': ') [1] node_id_to_uid[target_class] = Target_class_ STRING[1:-2] # Loads the final mapping of integer node ID to human-readable string node_id_to_name = {} for K 
      EY, Val in Node_id_to_uid.items (): If Val isn't in Uid_to_human:tf.logging.fatal (' Failed to locate:%s ', Val) Name = Uid_to_human[val] Node_id_to_name[key] = name return node_id_to_name def id_to_string (self, no DE_ID): If node_id not in Self.node_lookup:return ' retUrn self.node_lookup[node_id] def create_graph (): "" "creates a graph from saved Graphdef file and returns a saver." "
  # creates graph from saved GRAPH_DEF.PB. With Tf.gfile.FastGFile (Os.path.join (Flags.model_dir, ' CLASSIFY_IMAGE_GRAPH_DEF.PB '), ' RB ') as F:graph_def = t F.graphdef () graph_def. Parsefromstring (F.read ()) _ = Tf.import_graph_def (Graph_def, Name= ') def run_inference_on_image (image): "" "Runs I

  Nference on a image.

  Args:image:Image file name. Returns:nothing "" "If not tf.gfile.Exists (image): Tf.logging.fatal (' File does not exist%s ', image) Image_
  data = Tf.gfile.FastGFile (image, ' RB '). Read () # creates graph from saved Graphdef. Create_graph () with TF.
    Session () as Sess: # Some useful tensors: # ' softmax:0 ': A tensor containing the normalized prediction
    # 1000 labels.
    # ' pool_3:0 ': A tensor containing the next-to-last layer containing # float 2048 of the image. # ' Decodejpeg/contents:0 ': A tensor containing a string providing JPEG # encoding of the image.
    # runs the Softmax tensor by feeding the image_data as input to the graph.
                           Softmax_tensor = Sess.graph.get_tensor_by_name (' softmax:0 ') predictions = Sess.run (Softmax_tensor,
    {' decodejpeg/contents:0 ': Image_data})
    predictions = Np.squeeze (predictions) # creates node ID--> 中文版 string lookup. 
      Node_lookup = Nodelookup () Top_k = Predictions.argsort () [-flags.num_top_predictions:][::-1] for node_id in Top_k:  human_string = node_lookup.id_to_string (node_id) score = predictions[node_id] Print ('%s (score =%.5f) '
  % (human_string, score)) def maybe_download_and_extract (): "" "Download and extract model tar file." " Dest_directory = Flags.model_dir If not os.path.exists (dest_directory): os.makedirs (dest_directory) filename = DAT A_url.split ('/') [-1] filepath = os.path.join (dest_directory, filename) iF not os.path.exists (filepath): def _progress (count, Block_size, total_size): Sys.stdout.write (' \r>> downl 
    Oading%s%.1f%% '% (filename, float (count * block_size)/float (total_size) * 100.0)) Sys.stdout.flush ()
    filepath, _ = Urllib.request.urlretrieve (Data_url, filepath, _progress) print () Statinfo = Os.stat (filepath)
  Print (' succesfully downloaded ', filename, statinfo.st_size, ' bytes. ') Tarfile.open (filepath, ' R:gz '). Extractall (Dest_directory) def Main (_): Maybe_download_and_extract () image = (flags.i Mage_file if flags.image_file else Os.path.join (flags.model_dir, ' cropped_panda.jpg ')) run_inference_on_image
 (image) If __name__ = = ' __main__ ': Tf.app.run ()



Sorry

To apply for a blog column, you need to get 5 pieces. Occupy the pit first, then update.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.