Phase III using trained neural networks for image recognition "video card is Development Board"

Source: Internet
Author: User
Tags join readable split jupyter notebook

In a better presentation, before reforming or training a neural network, let's first feel what a trained neural network looks like, using the Image recognition case in TensorFlow tutorials to use ImageNet provides a small demonstration of the neural network of the INCEPTIONV3 model that is trained in the 1000 classified data.
This demo is very simple, first use the search engine to download a picture of a common species, such as I search for ' wolf ' by Goolge and then download a picture and save it as demo.jpg, and then open Jupyter notebook in the same directory as the image, Create a new notebook, and then paste the following code, Ctrl + Enter to run.
The following code is transformed from the code in this link:
https://github.com/tensorflow/models/blob/master/tutorials/image/imagenet/ classify_image.py

%matplotlib inline from __future__ import absolute_import from __future__ Import division from __future__ import Print_fu Nction Import argparse Import os.path import re import sys import tarfile import numpy as NP from six.moves import Urlli B import TensorFlow as TF from PIL import Image from matplotlib import pyplot as plt FLAGS = None data_url = '/http ' Download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz ' Model_dir = './inception ' class NodeLookup (

  Object): "" "Converts integer node ID ' s to human 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 (Model_dir, ' imagenet_2012_challenge_label_map_proto.pbtxt ') if n
    OT Uid_lookup_path:uid_lookup_path = Os.path.join (Model_dir, ' imagenet_synset_to_human_label_map.txt ') Self.node_lookup = Self.load (Label_lookup_path, uid_lookup_path) def load(Self, Label_lookup_path, Uid_lookup_path): 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 exis T%s ', Label_lookup_path) # Loads mapping from string UID to human-readable string proto_as_ascii_lines = Tf.gfil E.gfile (Uid_lookup_path). ReadLines () Uid_to_human = {} p = re.compile (R ' [n\d]*[\s,]* ') for line in Proto_as_a Scii_lines:parsed_items = P.findall (line) uid = parsed_items[0] human_string = parsed_items[2] UI
    D_to_human[uid] = human_string # Loads mapping from the 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 key, Val in Node_id_to_uid.items (): If Val not 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, node_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 Retu
  RNs a saver. "" "
  # creates graph from saved GRAPH_DEF.PB. With Tf.gfile.FastGFile (Os.path.join (Model_dir, ' CLASSIFY_IMAGE_GRAPH_DEF.PB '), ' RB ') as F:graph_def = tf. Graphdef () graph_def. Parsefromstring (F.read ()) _ = Tf.import_graph_def (Graph_def, name= ") def run_inference_on_image (image): 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:softmax_tensor = Sess.graph.get_tensor_by_name (' softmax:0 ') predictions = Sess.run (softmax_tens Or, {' decodejpeg/contents:0 ': image_data}) predictions = Np.squeeze (predictions) # Cre
    Ates node ID--English string lookup. Node_lookup = Nodelookup () Top_k = Predictions.argsort () [ -1:][::-1] for node_id in top_k:human_string = no De_lookup.id_to_string (node_id) score = predictions[node_id] Print ('%s (score =%.5f) '% (human_string, score) ) img = image.open (Image) FIG = plt.figure () ax = Fig.add_subplot (111) Ax.set_title (label=human_str  ing, fontdict={' fontsize ': () Ax.imshow (IMG) def maybe_download_and_extract (): "" "Download and extract model tar
  File. "" " Dest_directory = Model_dir If not os.path.exists (dest_directory): OS.MAkedirs (dest_directory) filename = data_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>> downloading %s%.1f%% '% (filename, float (count * block_size)/float (total_size) * 100.0)) Sys.stdout.flush () F Ilepath, _ = Urllib.request.urlretrieve (Data_url, filepath, _progress) print () Statinfo = Os.stat (filepath) PR
  Int (' successfully downloaded ', filename, statinfo.st_size, ' bytes. ') Tarfile.open (filepath, ' R:gz '). Extractall (Dest_directory) def Main (_): Maybe_download_and_extract () image = (Os.path. Join (' demo.jpg ')) run_inference_on_image (image) Tf.app.run (Main=main)

The results of the operation will be displayed as a picture, and the classification of the image as the title, as shown in the figure below, this neural network will accurately identify the wolf.

In this case, we end this demonstration, is not very intuitive, you can change several species to verify the accuracy of this network.

Reference Documentation:
[1] Https://www.tensorflow.org/tutorials/image_recognition

Remark: Please conduct this experiment in a scientific network environment.

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.