用列表切片张量 - TensorFlow

时间:2017-10-23 02:06:18

标签: python tensorflow

有没有办法在Tensorflow中完成这种切片方法(使用numpy显示的例子)?

z = np.random.random((3,7,7,12))
x = z[...,[0,5]]

这样

x_hat = np.concatenate([z[...,[0]], z[...,[5]]], 3)
assert np.all(x == x_hat)
x.shape # (3, 7, 7, 2)
Tensorflow中的

,此操作

tfz = tf.constant(z)
i = np.array([0,5] dtype=np.int32)
tfx = tfz[...,i]

抛出错误

ValueError: Shapes must be equal rank, but are 0 and 1
From merging shape 0 with other shapes. for 'strided_slice/stack_1' (op: 'Pack') with input shapes: [], [2].

3 个答案:

答案 0 :(得分:1)

您需要重塑以使连接结果与原始形状(前3个维度)保持一致。

z = np.arange(36)
tfz = tf.reshape(tf.constant(z), [2, 3, 2, 3])
slice1 = tf.reshape(tfz[:,:,:,1], [2, 3, -1, 1])
slice2 = tf.reshape(tfz[:,:,:,2], [2, 3, -1, 1])
slice = tf.concat([slice1, slice2], axis=3)

with tf.Session() as sess:
  print sess.run([tfz, slice])


> [[[[ 0,  1,  2],
     [ 3,  4,  5]],

    [[ 6,  7,  8],
     [ 9, 10, 11]],

    [[12, 13, 14],
     [15, 16, 17]]],

   [[[18, 19, 20],
     [21, 22, 23]],

    [[24, 25, 26],
     [27, 28, 29]],

    [[30, 31, 32],
     [33, 34, 35]]]]

  # Get the last two columns
> [[[[ 1,  2],
     [ 4,  5]],

    [[ 7,  8],
     [10, 11]],

    [[13, 14],
     [16, 17]]],

   [[[19, 20],
     [22, 23]],

    [[25, 26],
     [28, 29]],

    [[31, 32],
     [34, 35]]]]

答案 1 :(得分:1)

像格力所说的形状错误。不幸的是,似乎没有像我希望的那样简单的方法,但这是我提出的通用解决方案:

list.files(path, pattern, full.names = T) %>%
  assign("file_name", value = ., pos = 1) %>%
  map(image_read) %>%
  map2(file_name, image_annotate) %>%
  image_join() %>% 
  image_animate(fps = 1) %>% 
  image_write("animated.gif")

答案 2 :(得分:1)

怎么样:

x = tf.stack([tfz[..., i] for i in [0,5]], axis=-1) 

这对我有用:

z = np.random.random((3,7,7,12))
tfz = tf.constant(z)
x = tf.stack([tfz[..., i] for i in [0,5]], axis=-1)

x_hat = np.concatenate([z[...,[0]], z[...,[5]]], 3)

with tf.Session() as sess:
    x_run = sess.run(x)

assert np.all(x_run == x_hat)