Fei
Fei

Reputation: 829

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

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

Upvotes: 35

Views: 97424

Answers (7)

grofte
grofte

Reputation: 2129

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

Upvotes: 12

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

Upvotes: -2

Eric McLachlan
Eric McLachlan

Reputation: 3530

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

my_tensor.numpy()

Upvotes: 20

user11530462
user11530462

Reputation:

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.

Upvotes: 2

liaoming999
liaoming999

Reputation: 809

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

Upvotes: -2

Dat
Dat

Reputation: 5843

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

Upvotes: 3

Sung Kim
Sung Kim

Reputation: 8536

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)

Upvotes: -7

Related Questions