I want to use the value in a tensor to create another tensor, but I got the following error:
JavaScript
x
23
23
1
>>> a = tf.constant(3)
2
>>> a
3
Out[51]: <tf.Tensor: shape=(), dtype=int32, numpy=3>
4
>>> tf.constant([a, 2])
5
Traceback (most recent call last):
6
File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3369, in run_code
7
exec(code_obj, self.user_global_ns, self.user_ns)
8
File "<ipython-input-53-7af9a5175a59>", line 1, in <cell line: 1>
9
tf.constant([a, 2])
10
File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 267, in constant
11
return _constant_impl(value, dtype, shape, name, verify_shape=False,
12
File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 279, in _constant_impl
13
return _constant_eager_impl(ctx, value, dtype, shape, verify_shape)
14
File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 304, in _constant_eager_impl
15
t = convert_to_eager_tensor(value, ctx, dtype)
16
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
17
return ops.EagerTensor(value, ctx.device_name, dtype)
18
ValueError: TypeError: Scalar tensor has no `len()`
19
Traceback (most recent call last):
20
File "/Users/belter/miniconda3/envs/deside_obj/lib/python3.8/site-packages/tensorflow/python/framework/ops.py", line 1170, in __len__
21
raise TypeError("Scalar tensor has no `len()`")
22
TypeError: Scalar tensor has no `len()`
23
How can I use the value in tensor a
?
Advertisement
Answer
You can use tf.stack
.
JavaScript
1
6
1
import tensorflow as tf
2
3
@tf.function
4
def join_tns_num(tensor, num):
5
return tf.stack([tensor, tf.constant(num)], axis=0)
6
Check function:
JavaScript
1
3
1
>>> join_tns_num(tf.constant(3), 2)
2
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([3, 2], dtype=int32)>
3