Python 连接后如何正确访问单个张量?
我需要连接两个张量,但我对之后访问元素有点困惑。例如:Python 连接后如何正确访问单个张量?,python,tensorflow,concatenation,Python,Tensorflow,Concatenation,我需要连接两个张量,但我对之后访问元素有点困惑。例如: 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) 现在我如何访问整个xtensor或ytensor?我知道,但不确定。可能是制作张量列表并使用索引访问每个张量。但是如果可
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)
现在我如何访问整个
x
tensor或y
tensor?我知道,但不确定。可能是制作张量列表并使用索引访问每个张量。但是如果可能的话,我更喜欢使用连接的方式!欢迎提供任何建议或提示。以下是@Lescurel的完整答案参考,请使用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))
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))
使用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))
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))
仅供参考,您也可以使用np.stack
,操作相同
import numpy as np
np.array_equal(np.stack([x, y, z]), tf.stack([x, y, z]))
True
如果使用concat,则不会创建新标注。也许你在找
tf.stack
?@Lescurel非常感谢你说得对。我得到了它,它也起了作用