为什么索引该Numpy矩阵会导致错误? [英] Why does indexing this Numpy matrix cause an error?
问题描述
我正在使用:
- Python 3.5.4
- Numpy 1.16.2
给出代码:
import numpy as np
num = 3
a = np.asmatrix(np.eye(num, num))
b = np.asmatrix(range(0, num))
print(a[b].transpose())
我得到结果:
[[1.00000000e+000 0.00000000e+000 0.00000000e+000]
[1.77658241e-307 0.00000000e+000 0.00000000e+000]
[3.47328271e-310 0.00000000e+000 0.00000000e+000]]
但是通过将b的定义更改为np.asarray(...)
,或者通过执行第二次索引以获得列表中的第一项(print(a[b][0].transpose()
),我得到了预期的结果:
But by either changing the definition of b to np.asarray(...)
, or by performing a second indexing to get the first item in the list (print(a[b][0].transpose()
) I get the expected result:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
这是怎么回事?在没有根本原因的线索之前,我还没有遇到过此错误.如果它是Python的基础知识(我仍然是它的新手),我很想学习它,这样我就不会花很多时间来调试它了.预先非常感谢.
What is going on? I've not experienced this bug before don't have a clue to the underlying cause. If its something fundamental to Python (I'm quite new to it still) I'd quite like to learn about it so that I don't sink quite as much time into debugging it as I have this time. Many thanks in advance.
推荐答案
NumPy matrix
对象试图确保它们始终是2D的,但是它们并没有完全完成它.
NumPy matrix
objects try to ensure they're always 2D, but they don't quite do a complete job of it.
这样做的时候
b = np.asmatrix(range(0, num))
range(0, num)
是一维序列,但是asmatrix
创建单行2D矩阵而不是1D对象. asarray
会产生一维数组.
range(0, num)
is a 1D sequence, but asmatrix
creates a single-row 2D matrix instead of a 1D object. asarray
would produce a 1D array.
这样做的时候
a[b]
这是一个精美的索引操作,可生成一个 3D 矩阵. numpy.matrix
对象永远都不应该是3D的,下面的transpose
不知道如何处理它,从而产生荒谬的结果.特别是,由于舍入误差,输出中的奇数几乎为0不会不;它们是由于结果矩阵的无意义的步幅引起的,这些步幅导致未对齐的内存访问,并尝试将单独的float的片段读取为单个float:
this is a fancy indexing operation that produces a 3D matrix. numpy.matrix
objects are never supposed to be 3D, and the following transpose
doesn't know how to handle that, producing nonsensical results. Particularly, the strange, almost-0 numbers in the output are not due to rounding error; they're due to the nonsensical strides of the resulting matrix, which cause unaligned memory access and try to read fragments of separate floats as a single float:
In [13]: a[b].transpose().strides
Out[13]: (1, 24)
在第一个维度上跨度为1字节.
That's a 1-byte stride in the first dimension.
这里的重点:不要使用numpy.matrix
.
The key takeaway here: don't use numpy.matrix
.
这篇关于为什么索引该Numpy矩阵会导致错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!