如何在 TensorFlow 中对 4 阶张量进行切片?

How to slice a rank 4 tensor in TensorFlow?

我正在尝试使用 tf.slice() 运算符对四维张量进行切片,如下所示:

x_image = tf.reshape(x, [-1,28,28,1], name='Images_2D')
slice_im = tf.slice(x_image,[0,2,2],[1, 24, 24])

但是,当我尝试 运行 这段代码时,出现以下异常:

raise ValueError("Shape %s must have rank %d" % (self, rank))

ValueError: Shape TensorShape([Dimension(None), Dimension(28), Dimension(28), Dimension(1)]) must have rank 3

如何对这个张量进行切片?

tf.slice(input, begin, size) 运算符要求 beginsize 向量(定义要切片的子张量)的长度与 [=15= 中的维数相同].因此,要对 4-D 张量进行切片,您必须传递一个包含四个数字的向量(或列表)作为 tf.slice().

的第二个和第三个参数

例如:

x_image = tf.reshape(x, [-1, 28, 28, 1], name='Images_2D')

slice_im = tf.slice(x_image, [0, 2, 2, 0], [1, 24, 24, 1])

# Or, using the indexing operator:
slice_im = x_image[0:1, 2:26, 2:26, :]

索引运算符稍微更强大一些,因为它还可以降低输出的等级,如果您为维度指定单个整数而不是范围:

slice_im = x_image[0:1, 2:26, 2:26, :]
print slice_im_2d.get_shape()  # ==> [1, 24, 24, 1]

slice_im_2d = x_image[0, 2:26, 2:26, 0]
print slice_im_2d.get_shape()  # ==> [24, 24]