python 将模型从keras转换为tensorflow

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 将模型从keras转换为tensorflow相关的知识,希望对你有一定的参考价值。

# This file is to convert keras model in tensorflow
from keras import backend as K
import tensorflow as tf

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.
    """
    from tensorflow.python.framework.graph_util import convert_variables_to_constants
    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()]
        # Graph -> GraphDef ProtoBuf
        input_graph_def = graph.as_graph_def()
        if clear_devices:
            for node in input_graph_def.node:
                node.device = ""
        frozen_graph = convert_variables_to_constants(session, input_graph_def,
                                                      output_names, freeze_var_names)
        return frozen_graph

from keras.models import load_model
model = load_model('./resnet10.hdf5')
print(model.outputs)
# [<tf.Tensor 'dense_2/Softmax:0' shape=(?, 10) dtype=float32>]
print(model.inputs)
# [<tf.Tensor 'conv2d_1_input:0' shape=(?, 28, 28, 1) dtype=float32>]

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

# Save to ./model/tf_model.pb
tf.train.write_graph(frozen_graph, "model", "resnet10.pb", as_text=False)
print("model saved in pb file")

以上是关于python 将模型从keras转换为tensorflow的主要内容,如果未能解决你的问题,请参考以下文章

Tensor Flow V2:基于Tensor Flow Keras的摄氏度到华氏度温度转换的训练模型

Tensor Flow V2:基于Tensor Flow Keras的摄氏度到华氏度温度转换的训练模型

使用 tf.keras.estimator.model_to_estimator 将 keras 模型转换为估计器模型后使用 estimator.train() 的问题

如何将numpy数组转换为keras张量

将 CNN 模型代码从 Keras 转换为 Pytorch

将 UIImage 转换为 Keras 模型的 MLMultiArray