简体   繁体   English

如何在Python中高效创建和处理4D稀疏矩阵

[英]How to create and process a 4D sparse matrix in Python efficiently

I have a 4D sparse matrix of shape (21x21x21x21). 我有一个形状为(21x21x21x21)的4D稀疏矩阵。 Only one of the element will be set to 1. After which, I will vectorize this matrix and determine the non-zero row. 元素中只有一个将被设置为1。之后,我将矢量化该矩阵并确定非零行。 The whole process takes about 6 mins to compute which is too long. 整个过程大约需要6分钟才能计算出来,这太长了。 Is there a way to do this efficiently in Python? 有没有办法在Python中有效地做到这一点?

sparseMatrix = np.zeros((21,21,21,21), dtype = np.int8)
#w,x,y,z can be any random integer from 0 to 20.
w = 3
x = 5
y = 18
z = 16
sparseMatrix[w, x, y, z] = 1
sparseMatrix_vec = np.reshape(sparseMatrix, [-1,1])
sparseMatrix_vec_index = np.nonzero(sparseMatrix_vec)[0][0]

If you need (w,x,y,z) to form a unique integer, where each of (w,x,y,z) can vary between 0 and 20, then simply use base 21 representation. 如果您需要(w,x,y,z)形成一个唯一的整数,其中(w,x,y,z)中的每一个都可以在0到20之间变化,则只需使用以21为底的表示形式。 The integer you are looking for is: 您要查找的整数是:

N = w*(21 ** 0) + x*(21 ** 1) + y*(21 ** 2) + z*(21 ** 3). N = w *(21 ** 0)+ x *(21 ** 1)+ y *(21 ** 2)+ z *(21 ** 3)。

Given an integer, you can go back to (w,x,y,z) by using integer division and modulus. 给定整数,您可以使用整数除法和模数返回(w,x,y,z)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM