如何求向量化矩阵的指数

2024-09-28 19:04:12 发布

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

我在numpy中有一个ndmatrix(nxnnxn),我将其矢量化,以便以特定的方式对数据进行采样,得到(1xn^3)。你知道吗

我想把每个向量化的索引转换回n维索引(nxnnxn)。我不知道究竟有多颠簸向量矩阵。你知道吗

有人能建议吗?你知道吗


Tags: 数据numpy方式矩阵向量矢量化建议ndmatrix
1条回答
网友
1楼 · 发布于 2024-09-28 19:04:12

Numpy有一个函数unravel_index,它的作用相当于:给定一组“平面”索引,它将返回每个维度中索引数组的元组:

>>> indices = np.arange(25, dtype=int)
>>> np.unravel_index(indices, (5, 5))
(array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4,
        4, 4], dtype=int64),
 array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2,
        3, 4], dtype=int64))

然后可以zip它们来获得原始索引。你知道吗

但是要注意,矩阵可以表示为“行序列”(C约定,'C')或“列序列”(Fortran约定,'F'),或更高维度的相应约定。numpy中典型的矩阵展平将保持这种顺序,因此[[1, 2], [3, 4]]可以展平为[1, 2, 3, 4](如果它有'C'顺序)或[1, 3, 2, 4](如果它有'F'顺序)。unravel_index如果要更改默认值(即“C”),则接受可选的order参数,因此可以执行以下操作:

>>> # Typically, transposition will change the order for
>>> # efficiency reasons: no need to change the data !
>>> n = np.random.random((2, 2, 2)).transpose() 
>>> n.flags.f_contiguous
True
>>> n.flags.c_contiguous
False
>>> x, y, z = np.unravel_index([1,2,3,7], (2, 2, 2), order='F')

相关问题 更多 >