我的目标是做到这一点:
weights[1][0][0] = some_object(1)
但是它抛出了这个错误:
TypeError: float() argument must be a string or a number, not 'some_object'
因此我想将数据类型更改为“object” 在我的代码中我有权重。它们看起来像这样:
>>> print(weights)
[ array([[-2.66665269, 0. ],
[-0.36358187, 0. ],
[ 1.55058871, 0. ],
[ 3.91364328, 0. ]])
array([[ 0.],
[ 0.]])]
我想将weights[1][0][0]
更改为一个对象。我指的是 0:
[ array([[-2.66665269, 0. ],
[-0.36358187, 0. ],
[ 1.55058871, 0. ],
[ 3.91364328, 0. ]])
array([[ 0.], #this zero right here
[ 0.]])]
我想将 0 转换为 some_object(1)。所以我将数据类型更改为“对象”,但它仍然是 float 的!
>>> weights=np.array(weights,dtype='object')
>>> weights.dtype
object
>>> weights[1].dtype
float64
>>> weights[1][0].dtype
float64
>>> weights[1][0][0].dtype
float64
所以现在我尝试:
>>> weights[1].dtype='object'
TypeError: Cannot change data-type for object array.
还有这个
>>> weights[1][0].dtype='object'
TypeError: Cannot change data-type for object array.
所以现在我不能这样做:
weights[1][0][0] = some_object(1)
TypeError: float() argument must be a string or a number, not 'object'
因为数据类型不正确。如何更改数据类型?
编辑:我找到了答案。
weights[1] = weights[1].tolist()
weights[1][0][0] = some_object(1)
....
weights=np.array(weights)
最佳答案
让我们确保我们理解您的出发点:
In [7]: weights
Out[7]:
[array([[-2.66665269, 0. ],
[-0.36358187, 0. ],
[ 1.55058871, 0. ],
[ 3.91364328, 0. ]]), array([[ 0.],
[ 0.]])]
In [8]: len(weights)
Out[8]: 2
In [9]: weights[0]
Out[9]:
array([[-2.66665269, 0. ],
[-0.36358187, 0. ],
[ 1.55058871, 0. ],
[ 3.91364328, 0. ]])
In [10]: weights[0].dtype
Out[10]: dtype('float64')
In [11]: weights[0].shape
Out[11]: (4, 2)
In [13]: weights[1]
Out[13]:
array([[ 0.],
[ 0.]])
In [14]: weights[1].dtype
Out[14]: dtype('float64')
In [15]: weights[1].shape
Out[15]: (2, 1)
这是一个 2 项列表,包含两个数组。两者都是二维 float 。
首先将整个列表包装在一个对象数组中:
In [16]: duh =np.array(weights,dtype='object')
In [17]: duh
Out[17]:
array([ array([[-2.66665269, 0. ],
[-0.36358187, 0. ],
[ 1.55058871, 0. ],
[ 3.91364328, 0. ]]),
array([[ 0.],
[ 0.]])], dtype=object)
这是一个 2 元素数组,形状 (2,)。但它不会改变元素的性质。还有一个潜在的问题 - 如果元素数组具有相同的形状,它将创建一个 3d 对象数组。
这不是更改数组数据类型的正确语法。 dtype
不是可写的属性。
weights[1].dtype='object'
我们可以使用astype
来代替:
In [19]: weights[1].astype(object)
Out[19]:
array([[0.0],
[0.0]], dtype=object)
In [20]: weights[1]=weights[1].astype(object)
In [21]: weights
Out[21]:
[array([[-2.66665269, 0. ],
[-0.36358187, 0. ],
[ 1.55058871, 0. ],
[ 3.91364328, 0. ]]), array([[0.0],
[0.0]], dtype=object)]
它创建了一个新数组,我们将其写回到原始列表中。
现在我可以更改第二个数组的元素
In [22]: weights[1][0,0]=None
In [23]: weights
Out[23]:
[array([[-2.66665269, 0. ],
[-0.36358187, 0. ],
[ 1.55058871, 0. ],
[ 3.91364328, 0. ]]), array([[None],
[0.0]], dtype=object)]
玩这样的游戏时,您必须注意数组和列表的位置。并注意数组的形状和数据类型。不要盲目索引并希望得到最好的结果。显示/打印这些属性,或者整个数组(如果不是太大)。
关于python - 如何将 numpy 数组的 dtype 更改为 'object' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43560486/