简体   繁体   English

将冷冻的TensorFlow pb包装在tf.keras模型中

[英]Wrapping a frozen TensorFlow pb in a tf.keras Model

I am trying to use a frozen, pretrained, DeepLabv3 model in a larger tf.keras training pipeline, but have been having trouble figuring out how to use it as a tf.keras Model. 我正在尝试在更大的tf.keras培训管道中使用经过冻结的,经过预训练的DeepLabv3模型,但是一直难以弄清如何将其用作tf.keras模型。 I am trying to use tf.keras as I feel there would be a slowdown using a feed_dict (the only way I know of to use a frozen graph) in the middle of multiple forward passes. 我正在尝试使用tf.keras,因为在多个前向传递中间,使用feed_dict(我知道使用冻结图的唯一方法)会降低速度。 The deeplab model referenced in the code below is built in regular keras (as opposed to tf.contrib.keras) 以下代码中引用的deeplab模型是在常规keras中构建的(与tf.contrib.keras相对)

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 deeplab.outputs])
tf.train.write_graph(frozen_graph, "./", "my_model.pb", as_text=False)
graph = load_graph("my_model.pb")

# We can verify that we can access the list of operations in the graph
for op in graph.get_operations():
    print(op.name)
    # prefix/Placeholder/inputs_placeholder
    # ...
    # prefix/Accuracy/predictions

# We access the input and output nodes 
x = graph.get_tensor_by_name("prefix/input_1:0")
y = graph.get_tensor_by_name("prefix/bilinear_upsampling_2/ResizeBilinear:0")

# We launch a Session
with tf.Session(graph=graph) as sess:
    print(graph)
    model2 = models.Model(inputs=x,outputs=y)
    model2.summary()

and i get an error 我得到一个错误

ValueError: Input tensors to a Model must come from `tf.layers.Input`. Received: Tensor("prefix/input_1:0", shape=(?, 512, 512, 3), dtype=float32) (missing previous layer metadata).

I feel like I've seen others replace the input tensor with an Input Layer to trick tf.keras into building the graph, but after a few hours I am feeling stuck. 我觉得我已经看到其他人用输入层替换输入张量来欺骗tf.keras来构建图形,但是几个小时后,我感到卡住了。 Any help would be appreciated! 任何帮助,将不胜感激!

You can recreate the model object from its config . 您可以从其config重新创建模型对象。 See the from_config method here https://keras.io/models/about-keras-models/ . 请参阅https://keras.io/models/about-keras-models/上from_config方法。

The config is stored and loaded back by the save_model/load_model functions . 配置由save_model/load_model 函数存储和加载回去。 I am not familiar with freeze_session . 我不熟悉freeze_session

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM