Google Net Inception V3的上手報告
文章目錄
1.如何下載inception-2015-12-05.tgz文件?
下載地址爲:http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz
(需要注意的是,inception-2015-12-05.tgz在inception_model文件夾目錄下,img文件夾爲存放需要識別圖片的文件夾,img與inception_model,inception_log,Unzip.py,Load.py在同一文件目錄下!)
2.如何解壓inception-2015-12-05.tgz文件並保存網絡結構?
新建Unzip.py文件,添加以下代碼並運行:
import tensorflow as tf
import os
import tarfile
#模型存放地址
inception_pretrain_model_dir = "inception_model"
if not os.path.exists(inception_pretrain_model_dir):
os.makedirs(inception_pretrain_model_dir)
#獲取文件名,以及文件路徑
filename = "inception-2015-12-05.tgz"
filepath = os.path.join(inception_pretrain_model_dir, filename)
#解壓文件
tarfile.open(filepath, 'r:gz').extractall(inception_pretrain_model_dir)
#模型結構存放文件
log_dir = 'inception_log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
#classify_image_graph_def.pb爲google訓練好的模型
inception_graph_def_file = os.path.join(inception_pretrain_model_dir, 'classify_image_graph_def.pb')
with tf.Session() as sess:
#創建一個圖來存放google訓練好的模型
with tf.gfile.FastGFile(inception_graph_def_file, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
#保存圖的結構
writer = tf.summary.FileWriter(log_dir, sess.graph)
writer.close()
3.如何載入訓練好的Inception V3網絡模型?
新建Load.py文件,添加以下代碼並運行:(需要注意的是,把需要識別的圖片放在img文件夾目錄下,格式爲.jpg/.jepg)
import tensorflow as tf
import os
import numpy as np
import re
from PIL import Image
import matplotlib.pyplot as plt
class NodeLookup(object):
def __init__(self):
label_lookup_path = 'inception_model/imagenet_2012_challenge_label_map_proto.pbtxt'
uid_lookup_path = 'inception_model/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):
# 加載分類字符串n********對應分類名稱的文件
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
uid_to_human = {}
#一行一行讀取數據
for line in proto_as_ascii_lines :
#去掉換行符
line=line.strip('\n')
#按照'\t'分割
parsed_items = line.split('\t')
#獲取分類編號
uid = parsed_items[0]
#獲取分類名稱
human_string = parsed_items[1]
#保存編號字符串n********與分類名稱映射關係
uid_to_human[uid] = human_string
# 加載分類字符串n********對應分類編號1-1000的文件
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
node_id_to_uid = {}
for line in proto_as_ascii:
if line.startswith(' target_class:'):
#獲取分類編號1-1000
target_class = int(line.split(': ')[1])
if line.startswith(' target_class_string:'):
#獲取編號字符串n********
target_class_string = line.split(': ')[1]
#保存分類編號1-1000與編號字符串n********映射關係
node_id_to_uid[target_class] = target_class_string[1:-2]
#建立分類編號1-1000對應分類名稱的映射關係
node_id_to_name = {}
for key, val in node_id_to_uid.items():
#獲取分類名稱
name = uid_to_human[val]
#建立分類編號1-1000到分類名稱的映射關係
node_id_to_name[key] = name
return node_id_to_name
#傳入分類編號1-1000返回分類名稱
def id_to_string(self, node_id):
if node_id not in self.node_lookup:
return ''
return self.node_lookup[node_id]
#創建一個圖來存放google訓練好的模型
with tf.gfile.FastGFile('inception_model/classify_image_graph_def.pb', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
#遍歷目錄
for root, dirs, files in os.walk('img/'):
for file in files:
#載入圖片
image_data = tf.gfile.FastGFile(os.path.join(root, file), 'rb').read()
predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})#圖片格式是jpg格式
predictions = np.squeeze(predictions)#把結果轉爲1維數據
#打印圖片路徑及名稱
image_path = os.path.join(root, file)
print(image_path)
#顯示圖片
img = Image.open(image_path)
plt.imshow(img)
plt.axis('off')
plt.show()
#排序
top_k = predictions.argsort()[-5:][::-1]
node_lookup = NodeLookup()
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))
print()
4.樣例的測試情況?
圖片爲:
測試結果爲:
img/car.jpg
crane (score = 0.75562)
moving van (score = 0.03443)
tow truck, tow car, wrecker (score = 0.02511)
snowplow, snowplough (score = 0.02426)
garbage truck, dustcart (score = 0.01032)
img/flower.jpg
hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa (score = 0.64947)
earthstar (score = 0.20885)
coral fungus (score = 0.01842)
gyromitra (score = 0.01142)
yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum (score = 0.00741)
img/fruit.jpg
orange (score = 0.63299)
lemon (score = 0.22070)
hip, rose hip, rosehip (score = 0.07571)
pot, flowerpot (score = 0.00627)
grocery store, grocery, food market, market (score = 0.00320)
說實話,這精度也就還行吧,畢竟是以前的版本了。