Tensorflow: How to convert scalar tensor to scalar variable in python?

It should be as simple as calling int() on your tensor.

int(tf.random.uniform((), minval=0, maxval=32, dtype=tf.dtypes.int32))
>> 4

I've checked this in TF 2.2 and 2.4


You need to create a tf.Session() in order to cast a tensor to scalar

with tf.Session() as sess:
    scalar = tensor_scalar.eval()

If you are using IPython Notebooks, you can use Interactive Session:

sess = tf.InteractiveSession()
scalar = tensor_scalar.eval()
# Other ops
sess.close()

2.0 Compatible Answer: Below code will convert a Tensor to a Scalar.

!pip install tensorflow==2.0
import tensorflow as tf
tf.__version__ #'2.0.0'
x = tf.constant([[1, 1, 1], [1, 1, 1]])
Reduce_Sum_Tensor = tf.reduce_sum(x)
print(Reduce_Sum_Tensor) #<tf.Tensor: id=11, shape=(), dtype=int32, numpy=6>
print(Reduce_Sum_Tensor.numpy()) # 6, which is a Scalar

This is the Link of the Google Colab, in which the above code is executed.


In Tensorflow 2.0+, it's as simple as:

my_tensor.numpy()

Tags:

Tensorflow