gpt4 book ai didi

python - Numpy 如何在矢量化中排除数组?

转载 作者:行者123 更新时间:2023-12-01 23:16:08 29 4
gpt4 key购买 nike

我有一个函数:

import numpy as np

t = np.array([['t1', 0],['t2',0],['t3',1],['t4',1]])
i = np.array(['t3', 't4'])

def myfunc(d, x):
return d[:,1][np.where(d[:,0] == x)]

vfunc = np.vectorize(myfunc, excluded=['d'])
vfunc(d=t,x=i)

预期输出为:array(['1', '1'], dtype='<U2')

给出错误:ValueError: setting an array element with a sequence

我不明白为什么这在文档中的排除参数之后不起作用:https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html

最佳答案

正如 hpaulj 所说知道,测试,不要猜测。

很难确定,但就是这样。

文档说 By default, pyfunc is assumed to take scalars as input and output.

要删除此错误,请添加 otypes 参数,您将不会获得准确的输出,但 numpy 至少可以正确计算出它需要返回的内容

vfunc = np.vectorize(myfunc, excluded=['d'], otypes='O')
signature : string, optional

Generalized universal function signature, e.g., (m,n),(n)->(m) for
vectorized matrix-vector multiplication. If provided, pyfunc will be called
with (and expected to return) arrays with shapes given by the size of
corresponding core dimensions. By default, pyfunc is assumed to take scalars
as input and output.

以下是建议解决方案的详细原因

您的函数不返回标量输出,它为每个输入标量返回一个向量输出。虽然输入是标量 (t3,) 和 (t4,),但实际输出是向量 array(['1'], dtype='<U2') , array(['1'], dtype='<U2')]分别。

由于您没有指定签名,默认情况下 numpy 认为输出是标量,并尝试将它们放入 numpy 数组中,dtypes 作为输入的 dtype(但实际 dtype 是对象),试图制作一个向量。

那是错误ValueError: setting an array element with a sequence ,因为您的 ufunc 输出是每个输入标量的向量而不是标量,并且也没有定义签名(numpy 假定输出是标量的原因)。

另请参阅 numpy vectorize 文档中类似于您的示例,numpy 使用标量返回类型而不是向量

def mypolyval(p, x):

_p = list(p)

res = _p.pop(0)

while _p:

res = res*x + _p.pop(0)

return res

vpolyval = np.vectorize(mypolyval, excluded=['p'])

vpolyval(p=[1, 2, 3], x=[0, 1])
array([3, 6])

我是通过调试得出这个结论的,因为我自己使用向量化的经验还不够。

function_base.py 中调试时, 在 L2257 行输出被积累并具有值(value)array([array(['1'], dtype='<U2'), array(['1'], dtype='<U2')], dtype=object) .然后在 L2260 numpy 尝试将它们转换为所需的 dtype,但失败了,因为它假定标量序列,但得到了序列序列。

只需在 vscode 中放置一个断点,然后尝试查看您可以计算出的变量输出。

关于python - Numpy 如何在矢量化中排除数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68800110/

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