Python深度神经网络TensorFlow练习——图像分类实例详细说明
我是本际云服务器推荐网的小编小本本,今天给大家介绍Python深度神经网络TensorFlow练习的图像分类实例。Google在ImageNet图象数据库系统上练习好了一个Inception-v3实体模型,我们可以用来进行图像分类。

下载实体模型和文档
你可以从以下链接中免费下载实体模型和相关文档:
https://pan.baidu.com/s/1XGfwYer5pIEDkpM3nM6o2A
提取码:hu66
下载完毕后,解压缩,你将获得多个文档。其中,classify_image_graph_def.pb文件是练习好的Inception-v3实体模型,imagenet_synset_to_human_label_map.txt是类型文档。
使用实体模型进行图像分类
我们使用以下代码对一张图片进行分类识别:
import tensorflow as tf
import numpy as np
import re
import os
model_dir = 'D:/tf/model/'
image = 'd:/cat.jpg'
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)
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
uid_to_human = {}
p = re.compile(r'[nd]*[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
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]
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():
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='')
#读取训练好的Inception-v3模型来创建graph
def classify_image():
#读取图片
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文本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()
最终输出结果为:
tigercat (score=0.40316)
Egyptiancat (score=0.21686)
tabby,tabbycat (score=0.21348)
lynx, catamount (score=0.01403)
Persiancat (score=0.00394)
这些结果显示了图片属于哪些类别及其相应的概率值。
希望这篇文章能够为大家提供一些有用的信息,让大家的TensorFlow练习有所进步,更好地进行图像分类。祝大家工作顺利,早日涨薪!
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/6893.html
