35

In Tensorflow, I'd like to convert a scalar tensor to an integer. Is it possible to do?

I need to create a loop and the index of the loop is a scalar tensor, and inside the loop body, I want to use the index to access an entry in a tensor array.

For example:

idx = tf.constant(0)
c = lambda i : tf.less(i, 10)
def body(idx) :
  i = # convert idx to int 
  b = weights[i]  # access an entry in a tensor array, tensor cannot be used directly
  ....
  return idx+1
tf.while_loop(c, body, [idx])
0

7 Answers 7

20

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

my_tensor.numpy()
Sign up to request clarification or add additional context in comments.

4 Comments

AttributeError: 'Tensor' object has no attribute 'numpy'
@iirekm: Perhaps you don't have eager execution enabled? You can see the method is defined here: github.com/tensorflow/tensorflow/blob/…
What can we do if eager execution is not enabled?
If eager execution is not enabled, you wouldn't convert idx to a scalar i and you wouldn't index weights as weights[i]. Instead, you would use tf.gather(weights, idx).
13

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

1 Comment

Though you should probably have a look at gather if you are trying to do things with tensors and indexes.
3

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()

Comments

2

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.

2 Comments

AttributeError: 'Tensor' object has no attribute 'numpy'
In tensorflow version 2.2.0 or even 2.3.0 , AttributeError as above exists. It works only in 2.0.0. Could anyone help on how to convert to numpy array in versions >= 2.2
-2

Try to use tf.reshape()

# tensor 't' is [7]
# shape `[]` reshapes to a scalar
reshape(t, []) ==> 7

This comes from the https://www.tensorflow.org/api_docs/python/tf/reshape

1 Comment

The documentation is wrong, it doesn't actually convert a 0D tensor to a python scalar.
-2

Maybe this help. Just simple use:

idx2np = int(idx)

You could test whether it is a number now:

test_sum = idx2np + 1
print(str(test_sum))

Comments

-7

You need to evaluate a tensor to get a value.

If you want to do this:

i = # convert idx to int

you can do sess.run() or idx.eval():

i = sess.run(idx)

2 Comments

I need to do it during graph construction, not in a session. The while loop would construct the graph. Is that possible?
@Fei it's not possible without sess.run()/eva(). Then, you may want to use numpy array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.