谷歌在大型图像数据库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)

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

  1. 三分钟快速上手TensorFlow 2.0 (中)——常用模块和模型的部署

    本文学习笔记参照来源:https://tf.wiki/zh/basic/basic.html 前文:三分钟快速上手TensorFlow 2.0 (上)——前置基础.模型建立与可视化 tf.train. ...

  2. 三分钟快速上手TensorFlow 2.0 (上)——前置基础、模型建立与可视化

    本文学习笔记参照来源:https://tf.wiki/zh/basic/basic.html 学习笔记类似提纲,具体细节参照上文链接 一些前置的基础 随机数 tf.random uniform(sha ...

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

    将训练好的模型参数保存起来,以便以后进行验证或测试,这是我们经常要做的事情.tf里面提供模型保存的是tf.train.Saver()模块. 模型保存,先要创建一个Saver对象:如 saver=tf. ...

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

    tensorflow升级到1.0之后,增加了一些高级模块: 如tf.layers, tf.metrics, 和tf.losses,使得代码稍微有些简化. 任务:花卉分类 版本:tensorflow 1 ...

  5. tensorflow 1.0 学习:模型的保存与恢复

    将训练好的模型参数保存起来,以便以后进行验证或测试,这是我们经常要做的事情.tf里面提供模型保存的是tf.train.Saver()模块. 模型保存,先要创建一个Saver对象:如 saver=tf. ...

  6. TensorFlow 同时调用多个预训练好的模型

    在某些任务中,我们需要针对不同的情况训练多个不同的神经网络模型,这时候,在测试阶段,我们就需要调用多个预训练好的模型分别来进行预测. 调用单个预训练好的模型请点击此处 弄明白了如何调用单个模型,其实调 ...

  7. tensorflow 2.0 学习(四)

    这次的mnist学习加入了测试集,看看学习的准确率,代码如下 # encoding: utf-8 import tensorflow as tf import matplotlib.pyplot as ...

  8. Tensorflow 2.0 学习资源

    我从换了新工作才开始学习使用Tensorflow,感觉实在太难用了,sess和graph对 新手很不友好,各种API混乱不堪,这些在tf2.0都有了重大改变,2.0大量使用keras的 api,初步使 ...

  9. tensorflow 1.0 学习:十图详解tensorflow数据读取机制

    本文转自:https://zhuanlan.zhihu.com/p/27238630 在学习tensorflow的过程中,有很多小伙伴反映读取数据这一块很难理解.确实这一块官方的教程比较简略,网上也找 ...

随机推荐

  1. 大数据ssh疑点跟踪

    相信运维的对ssh免密登陆应该是对这个再清楚不过的吧,由于我们大数据对于安全这方便管控的很严格,单独找一台物理机作为跳板机,其他的机器都必须要从这个跳板机免密登陆,由于机器比较的多,其中dn30这个域 ...

  2. base加密解密工具类

    public class MLDUtil { public static Key DEFAULT_KEY = null; public static final String DEFAULT_SECR ...

  3. Nessus更新到8.3.0

    Nessus更新到8.3.0 更新内容包括: (1)专业版的报告功能更为灵活,允许用户选择包含的信息. (2)提升Nessus Manager的性能. (3)允许扫描模版多次更新. (4)生成报告时, ...

  4. 巨坑npm run dev 报错 终于找到正确答案 Error: EPERM: operation not permitted, open '/data/public/build/css/add.p

    Windows10环境 npm run dev 报错  终于找到正确答案 Error: EPERM: operation not permitted, open '/data/public/build ...

  5. 数据库SQLServr安装时出现--"需要更新以前的Visual Studio 2010实例"--状态失败

    在电脑中安装过Visual Studio比较低版本的软件的时候 将原本的Microsoft Visual Studio 2010 Service Pack 1进行了更改 导致sql比较高版本的不能很好 ...

  6. DW1000 用户手册中文版 第5章 媒体访问控制(帧过滤)

    由于已经在wode中排版无法直接复制到博客中,故本节博客发布使用了图片. PDF下载 http://bphero.com.cn/forum.php?mod=viewthread&tid=68

  7. php 记录日志时 基础的日志格式

     2019-02-19 11:29:56  /api/shop/shopManagements?shopId=undefined REQUEST:HTTP://mutest.drcloud.cn/mo ...

  8. VMware ESXi 6.5 安装

    1.1下载esxi镜像 此处我使用的版本是:VMware-VMvisor-Installer-6.5.0-4564106.x86_64 1.2新建一个虚拟机,硬件兼容性处选择ESXI6.5 硬盘40g ...

  9. Catalan 数列的性质及其应用(转载)

    转自:http://lanqi.org/skills/10939/ 卡特兰数 — 计数的映射方法的伟大胜利 发表于2015年11月8日由意琦行 卡特兰(Catalan)数来源于卡特兰解决凸$n+2$边 ...

  10. Hadoop-HA机制工作原理

    一.Hadoop 系统架构 1.1 Hadoop1.x和Hadoop2.x 架构 在介绍HA之前,我们先来看下Hadoop的系统架构,这对于理解HA是至关重要的.Hadoop 1.x之前,其官方架构如 ...