利用大Numpy阵列的对称性

2024-04-26 00:05:01 发布

您现在位置:Python中文网/ 问答频道 /正文

想制作一个大的数组,B,它是由一个小的numpy数组,a组成,以不同的方式翻转:

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

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

  • 能够缩放B[m,n,…](即B[m,n,…]*=C,其中B.shape[2:]==C.shape)
  • 能够归纳到第二维度(即。np.总和(B,轴=(2,3,4)))

Tags: 内存功能numpynp方式数组两件事感兴趣
1条回答
网友
1楼 · 发布于 2024-04-26 00:05:01

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

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]

相关问题 更多 >