np.unravel_index 的直观解释是什么? [英] What is an intuitive explanation of np.unravel_index?

查看:18
本文介绍了np.unravel_index 的直观解释是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与标题所说的差不多.我已经阅读了文档并且我已经使用了一段时间的函数,但是我无法辨别这种转换的物理表现是什么.

解决方案

计算机内存是线性寻址的.每个存储单元对应一个数字.可以根据基址(即其第一个元素的内存地址)和项目索引来寻址内存块.例如,假设基地址为 10,000:

项目索引 0 1 2 3内存地址 10,000 10,001 10,002 10,003

要存储多维块,必须以某种方式使它们的几何形状适合线性内存.在 CNumPy 中,这是逐行完成的.一个 2D 示例是:

<代码> |0 1 2 3--+------------------------0 |0 1 2 31 |4 5 6 72 |8 9 10 11

因此,例如,在这个 3×4 块中,二维索引 (1, 2) 将对应于线性索引 6,即 1 x 4 + 2.

unravel_index 反之.给定一个线性索引,它计算相应的 ND 索引.由于这取决于块尺寸,因此也必须通过这些尺寸.因此,在我们的示例中,我们可以从线性索引 6 中取回原始的 2D 索引 (1, 2):

<预><代码>>>>np.unravel_index(6, (3, 4))(1, 2)

注意:以上内容掩盖了一些细节.1) 将项目索引转换为内存地址还必须考虑项目大小.例如,一个整数通常有 4 或 8 个字节.因此,在后一种情况下,i 项的内存地址将是 base + 8 x i.2).NumPy 比建议的要灵活一些.如果需要,它可以逐列组织 ND 数据.它甚至可以处理内存中不连续但例如留有间隙等的数据.


额外阅读:internalndarray 的内存布局

Pretty much what the title says. I've read the documentation and I've played with the function for a while now but I can't discern what the physical manifestation of this transformation is.

解决方案

Computer memory is addressed linearly. Each memory cell corresponds to a number. A block of memory can be addressed in terms of a base, which is the memory address of its first element, and the item index. For example, assuming the base address is 10,000:

item index      0       1       2       3
memory address  10,000  10,001  10,002  10,003

To store multi-dimensional blocks, their geometry must somehow be made to fit into linear memory. In C and NumPy, this is done row-by-row. A 2D example would be:

  | 0      1      2      3
--+------------------------
0 | 0      1      2      3
1 | 4      5      6      7
2 | 8      9     10     11

So, for example, in this 3-by-4 block the 2D index (1, 2) would correspond to the linear index 6 which is 1 x 4 + 2.

unravel_index does the inverse. Given a linear index, it computes the corresponding ND index. Since this depends on the block dimensions, these also have to be passed. So, in our example, we can get the original 2D index (1, 2) back from the linear index 6:

>>> np.unravel_index(6, (3, 4))
(1, 2)

Note: The above glosses over a few details. 1) Translating the item index to memory address also has to account for item size. For example, an integer typically has 4 or 8 bytes. So, in the latter case, the memory address for item i would be base + 8 x i. 2). NumPy is a bit more flexible than suggested. It can organize ND data column-by-column if desired. It can even handle data that are not contiguous in memory but for example leave gaps, etc.


Bonus reading: internal memory layout of an ndarray

这篇关于np.unravel_index 的直观解释是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆