x[:,:,None,:]-x[:,:,:,None]

09/18 15:28
阅读数 70

x[:,:,None,:]-x[:,:,:,None]

None相当于在数组中多加一个维度。

输入:

x = np.arange(24).reshape((2,3,4))

输出:

array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
 x[:,:,None,:]

输出,形状(2,3,1,4):

array([[[[ 0,  1,  2,  3]],

        [[ 4,  5,  6,  7]],

        [[ 8,  9, 10, 11]]],


       [[[12, 13, 14, 15]],

        [[16, 17, 18, 19]],

        [[20, 21, 22, 23]]]])
x[:,:,:,None]

输出,形状(2,3,4,1):

array([[[[ 0],
         [ 1],
         [ 2],
         [ 3]],

        [[ 4],
         [ 5],
         [ 6],
         [ 7]],

        [[ 8],
         [ 9],
         [10],
         [11]]],


       [[[12],
         [13],
         [14],
         [15]],

        [[16],
         [17],
         [18],
         [19]],

        [[20],
         [21],
         [22],
         [23]]]])
x[:,:,None,:]-x[:,:,:,None]

这里相减时用到了广播机制,都先变成(2,3,4,4),再相减
输出,形状(2,3,4,4):

array([[[[ 0,  1,  2,  3],
         [-1,  0,  1,  2],
         [-2, -1,  0,  1],
         [-3, -2, -1,  0]],

        [[ 0,  1,  2,  3],
         [-1,  0,  1,  2],
         [-2, -1,  0,  1],
         [-3, -2, -1,  0]],

        [[ 0,  1,  2,  3],
         [-1,  0,  1,  2],
         [-2, -1,  0,  1],
         [-3, -2, -1,  0]]],


       [[[ 0,  1,  2,  3],
         [-1,  0,  1,  2],
         [-2, -1,  0,  1],
         [-3, -2, -1,  0]],

        [[ 0,  1,  2,  3],
         [-1,  0,  1,  2],
         [-2, -1,  0,  1],
         [-3, -2, -1,  0]],

        [[ 0,  1,  2,  3],
         [-1,  0,  1,  2],
         [-2, -1,  0,  1],
         [-3, -2, -1,  0]]]])
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部