我在 numpy (n x n x n) 中有一个 ndmatrix,我对其进行矢量化以便以特定方式对我的数据进行一些采样,得到 (1 x n^3)。
我想采用单独的向量化索引并将它们转换回形式为 (n x n x n) 的 n 维索引。我不确定矢量化矩阵实际上有多颠簸。
谁能给个建议?
最佳答案
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))
然后您可以压缩
它们以获得您的原始索引。
但是请注意,矩阵可以表示为“行序列”(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')
关于python - 如何找到向量化矩阵 numpy 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615683/