本地负载保存的tensorflow model.pb来自google云机器学习引擎

2024-10-02 22:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想采用我在网上培训过的tensorflow模型,用我发布的python程序在本地运行它。

经过培训,我得到了一个带有两个文件/saved_model.pb和一个文件夹/变量的目录/模型。在本地部署它最简单的方法是什么?

我在跟踪here以部署冻结模型,但我无法完全阅读.pb。我直接将saved_model.pb下载到我的工作中并尝试

with tf.gfile.GFile("saved_model.pb", "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

google.protobuf.message.DecodeError: Truncated message.

看着这样的here,他们提出了不同的路线。

with tf.gfile.GFile("saved_model.pb", "rb") as f:
    proto_b=f.read()
    graph_def = tf.GraphDef()
    text_format.Merge(proto_b, graph_def) 

builtins.TypeError: a bytes-like object is required, not 'str'

我觉得这很混乱

type(proto_b)
<class 'bytes'>
type(graph_def)
<class 'tensorflow.core.framework.graph_pb2.GraphDef'>

为什么会出错,字符串也是?

部署云训练模型的最佳方法是什么?

完整代码

import tensorflow as tf
import sys
from google.protobuf import text_format


# change this as you see fit
#image_path = sys.argv[1]
image_path="test.jpg"

# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()

# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line 
               in tf.gfile.GFile("dict.txt")]

# Unpersists graph from file
with tf.gfile.GFile("saved_model.pb", "rb") as f:
    proto_b=f.read()
    graph_def = tf.GraphDef()
    text_format.Merge(proto_b, graph_def) 

with tf.Session() as sess:
    # Feed the image_data as input to the graph and get first prediction
    softmax_tensor = sess.graph.get_tensor_by_name('conv1/weights:0')

    predictions = sess.run(softmax_tensor, \
                           {'DecodeJpeg/contents:0': image_data})

    # Sort to show labels of first prediction in order of confidence
    top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

    for node_id in top_k:
        human_string = label_lines[node_id]
        score = predictions[0][node_id]
        print('%s (score = %.5f)' % (human_string, score))

Tags: 模型imagemodeltfdefaswithgraph
1条回答
网友
1楼 · 发布于 2024-10-02 22:32:05

部署到CloudML引擎服务的模型的格式是^{}。使用^{}模块在Python中加载SavedModel相当简单:

import tensorflow as tf

with tf.Session(graph=tf.Graph()) as sess:
   tf.saved_model.loader.load(
       sess,
       [tf.saved_model.tag_constants.SERVING],
       path_to_model)

要执行推断,您的代码几乎是正确的;您需要确保正在将批处理馈送到session.run,所以只需将image_data包装在一个列表中:

# Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('conv1/weights:0')

predictions = sess.run(softmax_tensor, \
                       {'DecodeJpeg/contents:0': [image_data]})

# Sort to show labels of first prediction in order of confidence
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

for node_id in top_k:
    human_string = label_lines[node_id]
    score = predictions[0][node_id]
    print('%s (score = %.5f)' % (human_string, score))

(请注意,根据图表的不同,将输入的数据包装在列表中可能会增加预测张量的排名,您需要相应地调整代码)。

相关问题 更多 >