python - 加载图形然后用它来构建 tflite?

标签 python tensorflow deep-learning tensorflow-lite

我是 tensorflow 的新手,我正在尝试将我的 .pb(原型(prototype)缓冲区)文件转换为精简版。但我面临一些问题。 import time,sys,warnings,glob,random,cv2,base64,json,csv,os

import numpy as np
import tensorflow as tf
from collections import OrderedDict
def load_graph(frozen_graph_filename):
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(
            graph_def, 
            input_map=None, 
            return_elements=None, 
            name="prefix", 
            op_dict=None, 
            producer_op_list=None
        )
    return graph

此函数为我加载一个图表,现​​在我想将此图表转换为我使用以下脚本的 tflite。

CD_graph = load_graph("CD_Check_k.pb")
CD_input = CD_graph.get_tensor_by_name('prefix/input_node:0')
CD_output = CD_graph.get_tensor_by_name('prefix/output_node:0')
x_single = tf.placeholder(tf.float32, [1, 256 , 256, 3],
                              name="input_node")
with tf.Session() as sess:
  tflite_model = tf.contrib.lite.toco_convert(CD_graph, input_tensors=[x_single ], output_tensors=[CD_output])
  with open('./mnist.tflite', "wb") as f:
      f.write(tflite_model)

错误信息:

'Graph' object has no attribute 'SerializeToString'          

最佳答案

您可以使用 TocoConverter.from_frozen_graph() API 来简化您的代码,这样您就不再需要读取卡住的图表。来自 documentation 的示例复制如下。

从文件导出 GraphDef

以下示例展示了当 GraphDef 存储在文件中时如何将 TensorFlow GraphDef 转换为 TensorFlow Lite FlatBuffer。 .pb.pbtxt 文件都被接受。

示例使用 Mobilenet_1.0_224 .该函数仅支持通过 freeze_graph.py 卡住的 GraphDefs .

import tensorflow as tf

graph_def_file = "/path/to/Downloads/mobilenet_v1_1.0_224/frozen_graph.pb"
input_arrays = ["input"]
output_arrays = ["MobilenetV1/Predictions/Softmax"]

converter = tf.contrib.lite.TocoConverter.from_frozen_graph(
  graph_def_file, input_arrays, output_arrays)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

关于python - 加载图形然后用它来构建 tflite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410799/

相关文章:

python - Django 2.1.7 如何在包 View 上使用装饰器

python - 下载 OPENSSL 后 pip 显示错误

python-3.x - TPU分类器InvalidArgumentError : No OpKernel was registered to support Op 'CrossReplicaSum' with these attrs

deep-learning - 为拥抱脸 (HF) ViT 模型创建特征提取器的正确方法是什么?

python - scikit-learn 的 DecisionTreeRegressor 是否进行真正的多输出回归?

python - Tensorflow,try and except 不处理异常

python - 将 Matlab 连接到 TensorFlow

python - Tensorboard:OSError:[Errno 22] 尝试从命令提示符运行 tensorflow 时参数无效

keras - LSTM 时间序列产生偏移预测?

python - 使用每月的第一个交易日将每日 Pandas 股票数据转换为每月数据