Home > Enterprise >  Get the integer value inside a tensor tensorflow
Get the integer value inside a tensor tensorflow

Time:11-04

I have a list of tensors, but i need to use the integer value that is saved inside each one. Is there a way to retrieve it without need to change eager mode?

Example test:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
if __name__ == '__main__':
    test = tf.constant([1,4,5])
    np_array = test.numpy()
    integer_value = np_array[0]
    print(type(integer_value))

result: AttributeError: 'Tensor' object has no attribute 'numpy'

I need to get value 1,4,5 as integer

CodePudding user response:

You can use Tensor.numpy() method to convert tensorflow.Tensor to numpy array or if you don't want to work with numpy representation Tensor.numpy().tolist() converts your variable to python list.

test = tf.constant([1,4,5])
np_array = test.numpy()
python_list = np_array.tolist()
integer_value = np_array[0] # or python_list[0]

EDIT:

if you turn off the eager execution you are left off with TF 1.0 behaviour so you have to make a tensorflow.Session to evaluate any tensorflow.Tensor

tf.compat.v1.disable_eager_execution()

test = tf.constant([4, 5, 6])
sess = tf.compat.v1.Session()
sess.run(tf.compat.v1.global_variables_initializer())
np_array = test.eval(session=sess))
  • Related