简体   繁体   中英

How to properly access individual tensor after concatenate?

I need to concatenate two tensors, but I am a bit confused about accessing the element afterward. For an example:

import numpy as np
import tensorflow as tf

x = np.random.randint(100,size=(100,120,14))
y = np.random.randint(50,size=(100,120,14))
z = tf.concat([x,y],axis=0)

Now how can I access the entire x tensor or y tensor? I know, but not sure. might be making the list of tensors and accessing each tensor using indexing. But I would prefer the way to use concatenation, if possible. Any suggestions or hints are most welcome.

Here is the complete answer reference by @Lescurel, use tf.stack

import tensorflow as tf 
from tensorflow.keras.backend import eval 

# let's say x, y, z
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])

eval(x), eval(y), eval(z)
(array([1, 4], dtype=int32),
 array([2, 5], dtype=int32),
 array([3, 6], dtype=int32)) 

Using tf.stack

a = tf.stack([x, y, z], axis=0)
eval(a)
array([[1, 4],
       [2, 5],
       [3, 6]], dtype=int32)

# later access each element with indexing 
eval(a[0]), eval(a[1]), eval(a[2])
(array([1, 4], dtype=int32),
 array([2, 5], dtype=int32),
 array([3, 6], dtype=int32))

FYI, you can also use np.stack , the operations are same.

import numpy as np 
np.array_equal(np.stack([x, y, z]), tf.stack([x, y, z]))
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM