Skip to content
Advertisement

How to create a tensor from another tensor like tf.constant and number?

I want to use the value in a tensor to create another tensor, but I got the following error:

>>> a = tf.constant(3)
>>> a
Out[51]: <tf.Tensor: shape=(), dtype=int32, numpy=3>
>>> tf.constant([a, 2])
Traceback (most recent call last):
  File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3369, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-53-7af9a5175a59>", line 1, in <cell line: 1>
    tf.constant([a, 2])
  File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 267, in constant
    return _constant_impl(value, dtype, shape, name, verify_shape=False,
  File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 279, in _constant_impl
    return _constant_eager_impl(ctx, value, dtype, shape, verify_shape)
  File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 304, in _constant_eager_impl
    t = convert_to_eager_tensor(value, ctx, dtype)
  File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 102, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)
ValueError: TypeError: Scalar tensor has no `len()`
Traceback (most recent call last):
  File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/ops.py", line 1170, in __len__
    raise TypeError("Scalar tensor has no `len()`")
TypeError: Scalar tensor has no `len()`

How can I use the value in tensor a?

Advertisement

Answer

You can use tf.stack.

import tensorflow as tf

@tf.function
def join_tns_num(tensor, num):
    return tf.stack([tensor, tf.constant(num)], axis=0)

Check function:

>>> join_tns_num(tf.constant(3), 2)
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([3, 2], dtype=int32)>

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement