How can I convert Tensor to eagerTensor

Viewed 236

I got tensor class from Model.pred() that tensor class is <tf.python.framework.ops.Tensor> (not eager).

but I can't use them for custom loss function. So I tried convert 'that Tensor' to <tf.python.framework.ops.EagerTensor>.

If I convert them I can use .numpy() for a calculate in loss function.

Is there way to convert them? or Can I get numpy in <... ops.Tensor>?

I'm using Tensorflow 2.3.0

1 Answers

You can either:

  1. Try forcing eager execution with tf.config.run_functions_eagerly(True) or tf.compat.v1.enable_eager_execution() at the start of your code.

  2. Or using a session (documentation here) and calling .eval() on your Tensor instead of .numpy().

Example code of the second possibility:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()
# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b

# Launch the graph in a session.
sess = tf.compat.v1.Session()

with sess.as_default():
  print(c.eval())

sess.close()
Related