session.run() equivalent in tensorflow 2.x

Viewed 82

This function takes the pre-trained imagenet-vgg-verydeep-19.mat model and using its weights and input returns the graph(model)

def load_vgg_model(path):
    ...
    ...
    ...
    # Constructs the graph model.
    graph = {}
    graph['input']   = tf.Variable(np.zeros((1, 400, 300, 3)), dtype = 'float32')
    graph['conv1_1']  = _conv2d_relu(graph['input'], 0, 'conv1_1')      # returns tf.nn.relu
    graph['conv1_2']  = _conv2d_relu(graph['conv1_1'], 2, 'conv1_2')
    graph['avgpool1'] = _avgpool(graph['conv1_2'])                    # returns tf.nn.avg_pool
    graph['conv2_1']  = _conv2d_relu(graph['avgpool1'], 5, 'conv2_1')
    ....
    ....
    graph['conv5_4']  = _conv2d_relu(graph['conv5_3'], 34, 'conv5_4')
    graph['avgpool5'] = _avgpool(graph['conv5_4'])
    
    return graph

Here is the implementation of the same in TensorFlow 1

model = load_vgg_model("imagenet-vgg-verydeep-19.mat")
sess = tf.compat.v1.InteractiveSession()
content_image = imread("images/louvre_small.jpg")

sess.run(model['input'].assign(content_image))
out = model['conv4_2']
a_C = sess.run(out)
a_G = out

But I wanted to know the implementation in TensorFlow 2.x

I have read these documents https://www.tensorflow.org/guide/effective_tf2

https://www.tensorflow.org/guide/migrate

1 Answers

As mentioned in this doc, Tensorflow 2 has default eager execution. The code executes with building intermediate graphs.

In Tensorflow 2, creation of session is not required.You can use Autograph function to to create graph instead of session.

Document says,

TensorFlow 1.x requires users to manually stitch together an abstract syntax tree (the graph) by making tf.* API calls. It then requires users to manually compile the abstract syntax tree by passing a set of output tensors and input tensors to a session.run call. TensorFlow 2.0 executes eagerly (like Python normally does) and in 2.0, graphs and sessions should feel like implementation details.

One notable byproduct of eager execution is that tf.control_dependencies is no longer required, as all lines of code execute in order (within a tf.function, code with side effects executes in the order written).
Related