import tensorflow as tf
import os
import tarfile
import requests
inception_predition_model_url = "http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz"
inception_model_path = "inception_model"
if not os.path.exists(inception_model_path):
os.makedirs(inception_model_path)
'''
os.mkdir()创建路径中的最后一级目录,而如果之前的目录不存在并且也需要创建的话,就会报错。
os.makedirs()创建多层目录
'''
filename = inception_predition_model_url.split("/")[-1]
filepath = os.path.join(inception_model_path, filename)
#下载模型
if not os.path.exists(filepath):
print("download:", filename)
r = requests.get(inception_predition_model_url, stream = True)
with open(filepath, "wb") as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
print("Finished:", filename)
#解压文件
tarfile.open(filepath, "r:gz").extractall(inception_model_path)
#模型结构存放文件
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_model_path, "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()
下载的模型并解压:
使用tensorboard查看结构图:
复制上图中的链接使用chorme打开,会提示没有写进文件,应该是文件太大还没加载好,我也一度以为是出错了,但是放在那里准备去查看原因的时候,图加载出来了,就是如下:
查看网络结构图:
如上,可以看出inception-v3的结构。