翻转张量的第二维

时间:2016-07-19 20:30:16

标签: python theano

我想在张量的第二维中翻转元素的顺序:

x = T.tensor3('x')
f = theano.function([x], ?)
print(f(x_data))

输入:

x_data = [[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]],
          [[5, 0, 0, 0], [0, 6, 0, 0], [0, 0, 7, 0], [0, 0, 0, 8]],
          [[9, 0, 0, 0], [0, 10, 0, 0], [0, 0, 11, 0], [0, 0, 0, 12]]
         ]

期望的输出:

x_data = [[[0, 0, 0, 4], [0, 0, 3, 0], [0, 2, 0, 0], [1, 0, 0, 0]],
          [[0, 0, 0, 8], [0, 0, 7, 0], [0, 6, 0, 0], [5, 0, 0, 0]],
          [[0, 0, 0, 12], [0, 0, 11, 0], [0, 10, 0, 0], [9, 0, 0, 0]]
         ]

x_data [:: - 1]翻转整个第二维(不可取):

x_data = [[[ 11.   0.   0.   0.]
           [  0.  12.   0.   0.]
           [  0.   0.  13.   0.]
           [  0.   0.   0.  14.]]

           [[  5.   0.   0.   0.]
            [  0.   6.   0.   0.]
            [  0.   0.   7.   0.]
            [  0.   0.   0.   8.]]

           [[  1.   0.   0.   0.]
            [  0.   2.   0.   0.]
            [  0.   0.   3.   0.]
            [  0.   0.   0.   4.]]]

实现所需输出的最简单方法是什么?

2 个答案:

答案 0 :(得分:1)

[line[::-1] for line in x_data ]

答案 1 :(得分:1)

您只需翻转所需的尺寸,然后在不希望更改之前在尺寸上使用完整切片:x_data [::,:: - 1]

import numpy as np
x = T.tensor3('x')
x_data = np.asarray([[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]],
                 [[5, 0, 0, 0], [0, 6, 0, 0], [0, 0, 7, 0], [0, 0, 0, 8]],
                 [[9, 0, 0, 0], [0, 10, 0, 0], [0, 0, 11, 0], [0, 0, 0, 12]]
                 ], dtype=theano.config.floatX)
f = theano.function([x], x[::, ::-1])
print(f(x_data))