如何有效地在Python中创建和处理4D稀疏矩阵(How to create and process a 4D sparse matrix in Python efficiently)

编程入门 行业动态 更新时间:2024-10-28 12:24:32
如何有效地在Python中创建和处理4D稀疏矩阵(How to create and process a 4D sparse matrix in Python efficiently)

我有一个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.

更多推荐

本文发布于:2023-08-03 10:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1388524.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:建和   稀疏   有效地   矩阵   中创

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!