张量流或numpy中矩阵的特殊平铺

时间:2017-09-22 22:53:48

标签: numpy tensorflow numpy-broadcasting tiling

考虑T(w x h x d)的3D张量。

目标是通过以独特方式沿第三维平铺来创建R(w x h x K)的张量,其中K = d x k。

张量应该在第三维中重复每个切片k次,这意味着:

T[:,:,0]=R[:,:,0:k] and T[:,:,1]=R[:,:,k:2*k]

与标准平铺有细微差别,它给出T[:,:,0]=R[:,:,::k],在第3维中每隔kth重复一次。

1 个答案:

答案 0 :(得分:1)

沿着该轴使用np.repeat -

np.repeat(T,k,axis=2) 

示例运行 -

In [688]: # Setup
     ...: w,h,d = 2,3,4
     ...: k = 2
     ...: T = np.random.randint(0,9,(w,h,d))
     ...: 
     ...: # Original approach
     ...: R = np.zeros((w,h,d*k),dtype=T.dtype)
     ...: for i in range(4):
     ...:     R[:,:,i*k:(i+1)*k] = T[:,:,i][...,None]
     ...:  

In [692]: T
Out[692]: 
array([[[4, 5, 6, 4],
        [5, 4, 4, 3],
        [8, 0, 0, 8]],

       [[7, 3, 8, 0],
        [8, 7, 0, 8],
        [3, 6, 8, 5]]])


In [690]: R
Out[690]: 
array([[[4, 4, 5, 5, 6, 6, 4, 4],
        [5, 5, 4, 4, 4, 4, 3, 3],
        [8, 8, 0, 0, 0, 0, 8, 8]],

       [[7, 7, 3, 3, 8, 8, 0, 0],
        [8, 8, 7, 7, 0, 0, 8, 8],
        [3, 3, 6, 6, 8, 8, 5, 5]]])

In [691]: np.allclose(R, np.repeat(T,k,axis=2))
Out[691]: True

或者使用np.tilereshape -

np.tile(T[...,None],k).reshape(w,h,-1)