1

想要制作由较小的numpy数组A组成的大数组B,以不同的方式翻转:

B[0,:,:,:,:]   = A
B[1,:,:,:,:]   = B[0,:,::-1,:,:]
B[2:4,:,:,:,:] = B[0:2,:,:,::-1,:]
B[4:8,:,:,:,:] = B[0:4,:,:,:,::-1]

有没有办法只将 A 存储在内存中,但为 B 保留一些 numpy 数组的功能?我主要对两件事感兴趣:

  • 能够缩放 B[m,n,...](即 B[m,n,...] *= C where B.shape[2:] == C.shape)
  • 能够求和到第二维(即 np.sum(B,axis=(2,3,4)))
4

1 回答 1

0

我最终做的是创建一个类来返回 A 的任意反射部分的视图。在返回这个视图之后,我正在按 C 和总和进行缩放,这在现在看来已经足够快了。这是没有错误检查的:

class SymmetricArray:
    '''
    Attributes:
        A (np.ndarray): an [m, (a,b,c...)] array.
        idx (np.ndarray): an [n,] array where idx[n] points to A[idx[n], ...]
            to be used.
        reflect (np.ndarray): an [n, d] array where every entry is 1 or -1 and
            reflect[n, i] indicates whether or not the ith dimension of
            A[idx[n], ...] should be reflected, and d = len(A.shape - 1).
    '''
    def __init__(self, A, idx, reflect):
        self.A = np.asarray(A)
        self.idx = np.asarray(idx, dtype=int)
        self.reflect = np.asarray(reflect, dtype=int)

    def __getitem__(self, ii):
        '''
        Returns:
            np.ndarray: appropriately reflected A[idx[ii], ...]
        '''
        a_mask = [slice(None, None, a) for a in self.reflect[ii, :]]
        return self.A[self.idx[ii], ...][a_mask]
于 2016-05-05T16:52:37.940 回答