我有一个4D稀疏矩阵形状(21x21x21x21)。 只有一个元素将被设置为1.之后,我将向量化该矩阵并确定非零行。 整个过程大约需要6分钟来计算太长时间。 有没有办法在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]I have a 4D sparse matrix of shape (21x21x21x21). Only one of the element will be set to 1. After which, I will vectorize this matrix and determine the non-zero row. The whole process takes about 6 mins to compute which is too long. Is there a way to do this efficiently in 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]最满意答案
如果你需要(w,x,y,z)来形成一个唯一的整数,其中(w,x,y,z)中的每一个都可以在0到20之间变化,那么只需使用base 21表示。 您要查找的整数是:
N = w *(21 ** 0)+ x *(21 ** 1)+ y *(21 ** 2)+ z *(21 ** 3)。
给定一个整数,您可以使用整数除法和模数返回(w,x,y,z)。
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. The integer you are looking for is:
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.
更多推荐
发布评论