如何在张量流中操纵多维张量?

时间:2019-06-14 10:42:48

标签: python tensorflow

我有一个[?,128,128,128,5]形状的张量。它表示具有5种可能类别的3D图像。

我想在[?,:,:,:,2]内添加子张量[?,:,:,:,3][?,:,:,:,4],目前它们都是零。

然后,我想将这些先前的子张量[?,:,:,:,2][?,:,:,:,3]设置为零。我该怎么办?

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果我理解正确,我想你想要这样的东西:

import tensorflow as tf

img = tf.placeholder(tf.float32, [None, 128, 128, 128, 5])
s = tf.shape(img)
img2 = tf.concat([img[..., :2],
                  tf.zeros([s[0], s[1], s[2], s[3], 2], img.dtype),
                  tf.reduce_sum(img[..., 2:], axis=-1, keepdims=True)], axis=-1)

编辑:根据注释,如果要保持原轴的第一个和最后一个索引不变,请将第二个和第三个索引聚合到第四个索引中,并用零替换第二个和第三个索引,那么您会做这样的事情:

import tensorflow as tf

img = tf.placeholder(tf.float32, [None, 128, 128, 128, 5])
z = tf.expand_dims(tf.zeros(tf.shape(img)[:-1], img.dtype), axis=-1)
img2 = tf.concat([img[..., :1],  # New 1st index is the same as before
                  z,  # New 2nd index is zeros
                  z,  # New 3rd index is zeros
                  # New 4th index is sum of 2nd, 3rd and 4th indices
                  tf.reduce_sum(img[..., 1:4], axis=-1, keepdims=True)],
                  # New last index is the same as before
                  img[..., -1:]], axis=-1)