Warm tip: This article is reproduced from stackoverflow.com, please click
keras machine-learning python tensorflow tensorflow2.0

Replacing feed_dict in TF2.0 for tensor inputs to tensors in a function

发布于 2020-04-11 22:04:06

I have a Keras Callback that retrieves values from particular Keras layers like so:

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 was a Dataset.make_one_shot_iterator.get_next() call in tf1. I've replaced it with next(iter(ds)). That part works fine.

However I cannot figure out how to rewrite the sess.run() call. I want to get output from the 'fetches' tensors, but their inputs are other tensors higher up in the Model. I know which tensors are my input tensors, but how do I pass data into them and get the outputs I want from the tensors in later layers?

I read the conversion documentation on this subject but it is REALLY terse and unhelpful. I was not able to find much more information on stackoverflow.

Questioner
markemus
Viewed
28
Shubham Shaswat 2020-02-04 16:47

The output from the specific layer could be fetched from the model in this way


#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])

Now you can pass the values like

#call the model
mymodel = MyModel()

#pass your inputs
outputs = mymodel(inputs)

Remember the outputs is the array of the both the outputs which can be fetched by

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