如何将model.h5 转换为model.pb?

数据挖掘 神经网络 喀拉斯 张量流 数据科学模型
2022-03-04 16:34:17

我在 google-collab 中使用 keras 获取模型,但我必须使用 tensorflow 在 Visual Studio 中进行预测

我正在寻找一种将模型从 keras .h5 转换为 tensorflow .pb 的方法,但它们都没有按应有的方式工作。

3个回答

Keras 本身不包含任何将 TensorFlow 图导出为协议缓冲区文件的方法,但您可以使用常规 TensorFlow 实用程序来完成。是一篇博客文章,解释了如何使用freeze_graph.pyTensorFlow 中包含的实用程序脚本来执行此操作,这是它的“典型”方式。

但是,我个人觉得必须创建一个检查点然后运行外部脚本来获取模型很麻烦,我更喜欢从我自己的 Python 代码中执行此操作,所以我使用这样的函数:

def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    """
    Freezes the state of a session into a pruned computation graph.
 
    Creates a new computation graph where variable nodes are replaced by
    constants taking their current value in the session. The new graph will be
    pruned so subgraphs that are not necessary to compute the requested
    outputs are removed.
    @param session The TensorFlow session to be frozen.
    @param keep_var_names A list of variable names that should not be frozen,
                          or None to freeze all the variables in the graph.
    @param output_names Names of the relevant graph outputs.
    @param clear_devices Remove the device directives from the graph for better portability.
    @return The frozen graph definition.
    """
    graph = session.graph
    with graph.as_default():
        freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
        output_names = output_names or []
        output_names += [v.op.name for v in tf.global_variables()]
        input_graph_def = graph.as_graph_def()
        if clear_devices:
            for node in input_graph_def.node:
                node.device = ""
        frozen_graph = tf.graph_util.convert_variables_to_constants(
            session, input_graph_def, output_names, freeze_var_names)
        return frozen_graph

这在freeze_graph.py. 参数也与脚本类似。session是 TensorFlow 会话对象。keep_var_names仅当您想保持某些变量不被冻结时才需要(例如对于有状态模型),因此通常不需要。output_names是一个包含产生所需输出的操作名称的列表。clear_devices只需删除任何设备指令以使图形更便携。因此,对于具有一个输出的典型 Keras model,您可以执行以下操作:

from keras import backend as K

# Create, compile and train model...

frozen_graph = freeze_session(K.get_session(),
                              output_names=[out.op.name for out in model.outputs])

然后,您可以像往常一样将图形写入文件tf.train.write_graph

tf.train.write_graph(frozen_graph, "some_directory", "my_model.pb", as_text=False)

学分:jdehesa

您可以在以下位置找到更多信息:

将 hdf5 转换为 .bp 文件有不同的工具:

1 -将经过训练的 Keras 模型转换为单个 TensorFlow .pb 文件
2 - 或keras-to-tensorflow作为替代

对于张量流 2

import tensorflow as tf
model = tf.keras.models.load_model(keras_model_path)
tf.saved_model.save(model, "save/folder/path")

其他选择

import tensorflow as tf
model = tf.keras.models.load_model(keras_model_path)
model.save("save/folder/path")

这两种方法创建一个文件夹并将模型文件存储为 saved_model.pb。