温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Replacing feed_dict in TF2.0 for tensor inputs to tensors in a function
keras machine-learning python tensorflow tensorflow2.0

python - 将TF2.0中的feed_dict替换为函数中张量的张量输入

发布于 2020-04-11 23:16:00

我有一个Keras回调,它可以从特定的Keras图层中检索值,如下所示:

def run(self, fetches, next_batch):
    """Run fetches using the validation data passed in during initialization."""
    input_data, target_data = self.sess.run(next_batch)
    feed_dict = {self.model.inputs[0]: input_data,
                 self.model._targets[0]: target_data}
    result = self.sess.run(fetches=fetches, feed_dict=feed_dict)
    return result

next_batch是tf1中的Dataset.make_one_shot_iterator.get_next()调用。我已将其替换为next(iter(ds))。那部分工作正常。

但是我不知道如何重写sess.run()调用。我想从“获取”张量中获取输出,但它们的输入是模型中更高的其他张量。我知道哪些张量是我的输入张量,但是如何将数据传递到它们中并从后面的张量中获得所需的输出?

我阅读了有关此主题转换文档,但它确实非常简洁且无济于事。我无法找到有关stackoverflow的更多信息。

查看更多

提问者
markemus
被浏览
28
Shubham Shaswat 2020-02-04 16:47

特定层的输出可以通过这种方式从模型中获取


#get the output from the layer1
out1 = model.get_layer(layer1_name).output

#get the output from the layer2 
out2 = model.get_layer(layer2_name).output

#a new model with outputs of the layers
MyModel = Model(inputs=model.input,outputs=[out1,out2])

现在您可以传递类似的值

#call the model
mymodel = MyModel()

#pass your inputs
outputs = mymodel(inputs)

请记住,outputs是两个输出的数组,可以通过

output1 = outputs[0]
output2 = outputs[1]