tensorflow 1.0 学习:用别人训练好的模型来进行图像分类

谷歌在大型图像数据库ImageNet上训练好了一个Inception-v3模型,这个模型我们可以直接用来进来图像分类。

下载地址:https://storage.googleapis.com/download.tensorflow.org/models/inception_dec_2015.zip

下载完解压后,得到几个文件:

其中的classify_image_graph_def.pb 文件就是训练好的Inception-v3模型。

imagenet_synset_to_human_label_map.txt是类别文件。

随机找一张图片:如

对这张图片进行识别,看它属于什么类?

代码如下:先创建一个类NodeLookup来将softmax概率值映射到标签上。

然后创建一个函数create_graph()来读取模型。

最后读取图片进行分类识别:

# -*- coding: utf-8 -*-

import tensorflow as tf
import numpy as np
import re
import os

model_dir=‘D:/tf/model/‘
image=‘d:/cat.jpg‘

#将类别ID转换为人类易读的标签
class NodeLookup(object):
  def __init__(self,
               label_lookup_path=None,
               uid_lookup_path=None):
    if not label_lookup_path:
      label_lookup_path = os.path.join(
          model_dir, ‘imagenet_2012_challenge_label_map_proto.pbtxt‘)
    if not 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 exist %s‘, label_lookup_path)

    # Loads mapping 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(‘  target_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]

#读取训练好的Inception-v3模型来创建graph
def create_graph():
  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=‘‘)

#读取图片
image_data = tf.gfile.FastGFile(image, ‘rb‘).read()

#创建graph
create_graph()

sess=tf.Session()
#Inception-v3模型的最后一层softmax的输出
softmax_tensor= sess.graph.get_tensor_by_name(‘softmax:0‘)
#输入图像数据,得到softmax概率值(一个shape=(1,1008)的向量)
predictions = sess.run(softmax_tensor,{‘DecodeJpeg/contents:0‘: image_data})
#(1,1008)->(1008,)
predictions = np.squeeze(predictions)

# ID --> English string label.
node_lookup = NodeLookup()
#取出前5个概率最大的值(top-5)
top_5 = predictions.argsort()[-5:][::-1]
for node_id in top_5:
  human_string = node_lookup.id_to_string(node_id)
  score = predictions[node_id]
  print(‘%s (score = %.5f)‘ % (human_string, score))

sess.close()

最后输出:

tiger cat (score = 0.40316)
Egyptian cat (score = 0.21686)
tabby, tabby cat (score = 0.21348)
lynx, catamount (score = 0.01403)
Persian cat (score = 0.00394)

时间: 2024-08-27 15:54:51

tensorflow 1.0 学习:用别人训练好的模型来进行图像分类的相关文章

tensorflow 1.0 学习:用CNN进行图像分类

tensorflow升级到1.0之后,增加了一些高级模块: 如tf.layers, tf.metrics, 和tf.losses,使得代码稍微有些简化. 任务:花卉分类 版本:tensorflow 1.0 数据:http://download.tensorflow.org/example_images/flower_photos.tgz 花总共有五类,分别放在5个文件夹下. 闲话不多说,直接上代码,希望大家能看懂:) # -*- coding: utf-8 -*- from skimage im

tensorflow 1.0 学习:模型的保存与恢复(Saver)

将训练好的模型参数保存起来,以便以后进行验证或测试,这是我们经常要做的事情.tf里面提供模型保存的是tf.train.Saver()模块. 模型保存,先要创建一个Saver对象:如 saver=tf.train.Saver() 在创建这个Saver对象的时候,有一个参数我们经常会用到,就是 max_to_keep 参数,这个是用来设置保存模型的个数,默认为5,即 max_to_keep=5,保存最近的5个模型.如果你想每训练一代(epoch)就想保存一次模型,则可以将 max_to_keep设置

tensorflow 2.0 学习 (十一)卷积神经网络 (一)MNIST数据集训练与预测 LeNet-5网络

网络结构如下: 代码如下: 1 # encoding: utf-8 2 3 import tensorflow as tf 4 from tensorflow import keras 5 from tensorflow.keras import layers, Sequential, losses, optimizers, datasets 6 import matplotlib.pyplot as plt 7 8 Epoch = 30 9 path = r'G:\2019\python\mn

tensorflow 2.0 学习 (七) 反向传播代码逐步实现

数据集为: 代码为: 1 # encoding: utf-8 2 3 import tensorflow as tf 4 import numpy as np 5 import seaborn as sns 6 import matplotlib.pyplot as plt 7 from sklearn.datasets import make_moons 8 # from sklearn.datasets import make_circles 9 from sklearn.model_sel

tensorflow 1.0 学习:参数初始化(initializer)

CNN中最重要的就是参数了,包括W,b. 我们训练CNN的最终目的就是得到最好的参数,使得目标函数取得最小值.参数的初始化也同样重要,因此微调受到很多人的重视,那么tf提供了哪些初始化参数的方法呢,我们能不能自己进行初始化呢? 所有的初始化方法都定义在tensorflow/python/ops/init_ops.py 1.tf.constant_initializer() 也可以简写为tf.Constant() 初始化为常数,这个非常有用,通常偏置项就是用它初始化的. 由它衍生出的两个初始化方法

tensorflow源码学习之五 -- 同步训练和异步训练

同步和异步训练是由optimizer来决定的. 1. 同步训练 同步训练需要使用SyncReplicasOptimizer,参考https://www.tensorflow.org/api_docs/python/tf/train/SyncReplicasOptimizer .其他optimizer都属于异步训练方式. 同步训练实现在sync_replicas_optimizer.py文件中的def apply_gradient()方法中.假设有n个参数: 对于PS,需要创建n个参数收集器(每个

tensorflow 2.0 学习 (九) tensorboard可视化功能认识

代码如下: # encoding :utf-8 import io # 文件数据流 import datetime import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras # 导入常见网络层, sequential容器, 优化器, 损失函数 from tensorflow.keras import layers, Sequential, optimizers, losses, met

tensorflow 2.0 学习 (六) Himmelblua函数求极值

Himmelblua函数在(-6,6),(-6,6)的二维平面上求极值 函数的数学表达式:f(x, y) = (x**2 + y -11)**2 + (x + y**2 -7)**2: 如下图所示 等高线如下图所示: 代码如下: # encoding: utf-8 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits

奉献pytorch 搭建 CNN 卷积神经网络训练图像识别的模型,配合numpy 和matplotlib 一起使用调用 cuda GPU进行加速训练

1.Torch构建简单的模型 # coding:utf-8 import torch class Net(torch.nn.Module): def __init__(self,img_rgb=3,img_size=32,img_class=13): super(Net, self).__init__() self.conv1 = torch.nn.Sequential( torch.nn.Conv2d(in_channels=img_rgb, out_channels=img_size, ke