python - 我的脚本和控制台中使用点积的不同输出

标签 python python-3.x numpy

我已经尝试解决这个问题 2 个多小时了。

我写了一个脚本,我把一些调试 prints

...
print(array)
print(m)
print(np.dot(m.ravel(),array.ravel()))
...

当我启动它时,我有这样的输出:

$ ./test.py 
[[    0     0     0     0     0     0     0]
 [    0     0     0     0     0     0     0]
 [    0     0     0     0     0     0     0]
 [    0     0     0 20303 20303 20303 20303]
 [20303 20303 20303 20303 20303 20303 20303]
 [20303 20303 20303 20303 20303 20303 20303]
 [20303 20303 20303 20303 20303 20303 20303]]
[[False False False False False False False]
 [False False False False False False False]
 [False False False False False False False]
 [False False False False  True False False]
 [False False  True False  True False False]
 [False False False  True False False False]
 [False False False False False False False]]
15676

当我尝试在 python 控制台中重现此行为时,我得到了不同的点积结果:

$ /usr/bin/python3
Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> array=np.array([[    0,     0,     0,     0,     0,     0,     0],
[    0,     0,     0,     0,     0,     0,     0],
[    0,     0,     0,     0,     0,     0,     0],
[    0,     0,     0, 20303, 20303, 20303, 20303],
[20303, 20303, 20303, 20303, 20303, 20303, 20303],
[20303, 20303, 20303, 20303, 20303, 20303, 20303],
[20303, 20303, 20303, 20303, 20303, 20303, 20303]])
>>> 
>>> m=np.array([[False, False, False, False, False, False, False],
[False, False, False, False, False, False, False],
[False, False, False, False, False, False, False],
[False, False, False, False,  True, False, False],
[False, False,  True, False,  True, False, False],
[False, False, False,  True, False, False, False],
[False, False, False, False, False, False, False]])
>>> np.dot(m.ravel(),array.ravel())
81212

什么会导致这种情况?顺便说一句,81212 是我在这里期望的结果,我真的不明白我的脚本中发生了什么。

最佳答案

实际上解决问题,但可能是一个解决方法:

np.ravel在 NumPy 1.10 中略有变化,也许这是导致“奇怪”行为的原因:

As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked array will be returned for a masked array input)

但是在这种情况下你真的需要np.ravel吗?只使用 boolean indexing 怎么样?并总结结果:

>>> print(array[m].sum())
81212

如果这是您最初想要实现的目标,则此方法可能比 np.dot扁平化数组更“pythonic”。

关于python - 我的脚本和控制台中使用点积的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390416/

相关文章:

python - 将 24 位音频样本放入 int32 数组中(小端 WAV 文件)

python - pandas 引发日期时间对象的值错误

python - 记住方法调用之间的状态

python - 需要从 Unix shell -> Python -> & 返回进行控制

python - 类型错误 : 'str' does not support the buffer interface 4

python - 迭代器卡住

python - 字段子类的子类没有新的迁移

python - 按日期和时间从目标机器过滤/var/log/messages 文件数据

python - 什么是 Python 等同于 C++ 命名空间的东西?

python - 高级索引返回形状错误的数组