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/", 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/", 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/", 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/", 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/", 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/", 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?


You can use tf.stack.

import tensorflow as tf

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

Answered By – I'mahdi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published