本文转载于[https://blog.csdn.net/j515332019/article/details/108630901]。
x[:,:,None,:]-x[:,:,:,None]
None相当于在数组中多加一个维度。
输入:
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]]]])