如何防止numpy内存溢出?


import numpy as np
x1 = np.arange(0,63, dtype=np.int8).reshape(63,1)
x2 = np.arange(0,63, dtype=np.int8).reshape(1,63)
o = np.zeros((63,63), dtype=np.int16)
o = np.matmul(x1,x2)
print(o)
Output:
[[   0    0    0 ...    0    0    0]
[   0    1    2 ...   60   61   62]
[   0    2    4 ...  120  122  124]
...
[   0   60  120 ...   16   76 -120]
[   0   61  122 ...   76 -119  -58]
[   0   62  124 ... -120  -58    4]]

x1和x2的值在np后的np.int8的范围内。matmul操作,值在int8范围以上,所以我将它存储到int16,我仍然得到不正确的值。有人能解释一下为什么会这样吗?由于

np.matmul(x1,x2)返回一个具有溢出的int8临时数组。然后将结果分配给o,但这为时已晚:溢出已经完成。操作前应调整类型:o = x1.astype(np.int16) @ x2.astype(np.int16).

注意o = ...不执行复制,但通过引用将右侧赋值给o。因此,o = np.zeros((63,63), dtype=np.int16)是无用的。如果你想要复制,你需要使用o[:,:] = ...,但在这里复制不是一个好主意(这只是比较慢)。

最新更新