Wednesday, 30 October 2019

TensorFlow 1 Nostalgia: Create a Graph and Run in a Session

TensorFlow 2 runs by default in Eager mode in which functions return value-tensors instead of op-tensors. To build an Autograph, put @tf.function annotation in the line right before 'def'. However, there's another way to use Ops as really ops, that is making op chain inside graph as_default(), and run with tf.compat.v1.Session, see the code below.

Source code:
%tensorflow_version 2.x
%reset -f

#libs
import tensorflow as tf;

#create new graph, inside default graph, TF functions return op-tensors.
#outside of default graph, TF functions return value-tensors, as Eager mode is default on TF2
G = tf.Graph();  
with G.as_default():

  #G is now the default graph
  print("Is default graph:",tf.compat.v1.get_default_graph() is G);

  #no operations
  print("Operations:",G.get_operations());

  #add some operations
  print("\nAdding operations...");
  Inp    = tf.compat.v1.placeholder(tf.float32, [2], name="Inp");
  Times2 = tf.multiply(Inp, 2, name="Mul");

  #now having 1 placeholder, 1 operation
  print("Operations:",G.get_operations());

#feed to graph
print("\nRun graph in session, result:");
S = tf.compat.v1.Session(graph=G);
R = S.run(Times2, feed_dict={Inp:[1,2]});
print(R);
#eof

No comments:

Post a Comment