Tensorflow:如何将标量张量转换为 python 中的标量变量?

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

在 Tensorflow 中,我想将标量张量转换为整数。有可能吗?

我需要创建一个循环,循环的索引是一个标量张量,在循环体内,我想使用索引访问张量数组中的一个条目。

例如:

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

您需要计算一个张量以获得一个值。

如果你想这样做:

i = # convert idx to int

你可以做 sess.run() 或 idx.eval():

i = sess.run(idx)

您需要创建一个 tf.Session() 才能将张量转换为标量

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

如果您使用的是 IPython 笔记本,您可以使用 Interactive Session:

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

尝试使用tf.reshape()

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

这来自https://www.tensorflow.org/api_docs/python/tf/reshape

2.0 兼容答案:下面的代码会将张量转换为标量。

!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是Google Colab的Link,执行上面的代码

在 Tensorflow 2.0+ 中,它很简单:

my_tensor.numpy()

也许这有帮助。简单使用:

idx2np = int(idx)

你现在可以测试它是否是一个数字:

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

它应该像在张量上调用 int() 一样简单。

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

我已经在 TF 2.2 和 2.4 中检查过了