从形状为(5,5,5)
的张量x
开始,我尝试将形状为(5,5)
的另一张量y
附加到最后一个维度。 我想要得到的是一个新的x
,形状为(5,5,6)
。
用numpy做很容易,我只需要做x=np.dstack([x,y])
。 但是,在TensorFlow中我做不到。 由于x
和y
的形状不同,tf.concat()
和tf.stack()
都返回错误。
在TensorFlow中怎么做?
您可以使用tf.newaxis
有效地重塑张量,然后使用tf.concat
a = tf.zeros((5,5,5))
b = tf.ones((5,5))
tf.concat((a, b[:, :, tf.newaxis]), axis=2)
tf.concat((a, tf.expand_dims(b, axis=2)), axis=2)
两者都导致
<tf.Tensor: shape=(5, 5, 6), dtype=float32, numpy=
array([[[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.]],
[[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.]],
[[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.]],
[[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.]],
[[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1.]]], dtype=float32)>