微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在大矩阵中打乱下三角

如何解决在大矩阵中打乱下三角

我有一个大的、稀疏的邻接矩阵 (64948 x 64948),它在对角线上对称。我需要做的是随机化矩阵的上三角或下三角中非零元素的位置(然后将被转置。)我有下面的代码。它适用于 10x10 矩阵,但不适用于 64948x64948(我在集群上遇到内存错误)。我意识到我的方法可能存在缺陷,如果有人对我如何以更有效的方式执行此操作有任何见解,我将不胜感激!

首先,我创建了“掩码”,它本质上是下三角形中每个位置的数组。

mask_mtx = np.ones([10,10]) #all ones
mask_mtx = np.tril(mask_mtx,-1) #lower triangle ones
mask_mtx = sparse.csr_matrix(mask_mtx)
mask = sparse.find(mask_mtx) #indices of ones
np.save('struc_conn_mat_mask.npy',mask) #cluster fails here when n=64948. I'm trying to save it out from a cluster so I can use the mask on my local machine with code below
len_mask = len(mask[0]) #how many indices there are

出于本示例的目的,我将 mtx 创建为数组,但通常我会读取 65k x 65k csr_matrix。然后我找到 mtx 下三角形中非零元素的数量,并从掩码中随机选择许多位置。然后我将 1s 放在空的 tmp_mtx 中的这些位置。最后,我将下三角转换为上三角。

mtx = sparse.random(10,10,format='csr',density=0.1) #for the purposes of this example,create random matrix
lmtx = sparse.tril(mtx,-1,format='csr') #lower triangle
tmp_mtx = np.zeros((10,10)) #empty lower triangle to set
lvals = sparse.csr_matrix.count_nonzero(lmtx) #how many 1s in lmtx?
coordinate_indices = random.sample(range(len_mask),lvals) #choose n=lvals random indices to fill with ones
for idx in coordinate_indices:
    tmp_mtx[mask[0][idx]][mask[1][idx]] = 1 #at randomly chosen index from mask,put a 1
tmp_mtx = sparse.csr_matrix(tmp_mtx)
mtx = tmp_mtx + tmp_mtx.T #transpose to upper triangle

同样,这适用于 10x10 矩阵,但在具有较大矩阵的几个地方失败。最终,我想做的是一个看似简单的操作——将三角形洗牌——但我想不出如何以更有效的方式进行。也许有一些方法可以对列和行进行改组(但仅针对其中一个三角形?)

任何帮助都会如此,非常感谢!谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。