gpt4 book ai didi

Python numpy 数组 : wrong result when mixing int32 and int8

转载 作者:行者123 更新时间:2023-12-01 04:51:56 26 4
gpt4 key购买 nike

我在numpy数组中看到了一个非常奇怪的行为,当我在一个简单的操作中混合int32和int8数组时,int32数组元素ct[4,0]在取+= dleng[4]*4的结果:

import numpy as np
In[3]: ct = np.zeros((6,1), np.int32)
In[4]: ct
Out[4]:
array([[0],
[0],
[0],
[0],
[0],
[0]], dtype=int32)
In[5]: dleng = np.zeros((6, 1), np.int8)
In[6]: dleng[0] = 2
dleng[1] = 3
dleng[2] = 4
dleng[3] = 7
dleng[4] = 3
dleng[5] = 5
In[7]: dleng
Out[7]:
array([[2],
[3],
[4],
[7],
[3],
[5]], dtype=int8)
In[8]: ct[4] = 117
In[9]: ct
Out[9]:
array([[ 0],
[ 0],
[ 0],
[ 0],
[117],
[ 0]], dtype=int32)
In[10]: ct[4,0] += dleng[4]*4
In[11]: ct
Out[11]:
array([[ 0],
[ 0],
[ 0],
[ 0],
[-127],
[ 0]], dtype=int32)}

有人知道为什么会发生这种情况吗?

最佳答案

dleng[4]*4 是一个数组:

In [94]: dleng[4]
Out[94]: array([3], dtype=int8)

In [95]: dleng[4]*4
Out[95]: array([12], dtype=int8)

ct[4, 0] 是类型为 np.int32标量:

In [98]: ct[4,0]
Out[98]: 117

In [99]: type(_)
Out[99]: numpy.int32

正如 @WallyBeaver 指出的,ct[4,0] += dleng[4]*4 就像 ct[4,0] = ct[4,0] + dleng [4]*4。最后一个表达式是一个标量加上一个数组。在这种情况下,数据类型由数组确定,因此最终为np.int8numpy docs中有关于此的注释。 :

Mixed scalar-array operations use a different set of casting rules that ensure that a scalar cannot “upcast” an array unless the scalar is of a fundamentally different kind of data (i.e., under a different hierarchy in the data-type hierarchy) than the array. This rule enables you to use scalar constants in your code (which, as Python types, are interpreted accordingly in ufuncs) without worrying about whether the precision of the scalar constant will cause upcasting on your large (small precision) array.

修复方法是将就地添加编写为

ct[4,0] += dleng[4,0]*4

关于Python numpy 数组 : wrong result when mixing int32 and int8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28243559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com