gpt4 book ai didi

python - numpy 沿轴应用,错误 "ValueError: could not broadcast input array from shape (2) into shape (1)"

转载 作者:行者123 更新时间:2023-12-01 02:45:14 24 4
gpt4 key购买 nike

这是我的 numpy 数组的示例,我想为矩阵 test 的每一行应用函数 mapping

test = np.array([[0, .1, .9], [.1, .9, .8], [.8, .6, .1]])
test2 = np.array(['a','b','c'])

def mapping(x):
return test2[np.where(x > .7)].tolist()

这有效

mapping(test[0]), mapping(test[1]), mapping(test[2])

正确结果:(['c'], ['b', 'c'], ['a','b'])

但事实并非如此,并且会抛出错误。

np.apply_along_axis(mapping, 1, test)

我不明白为什么会这样。请帮忙。

最佳答案

来自应用文档:

The output array. The shape of `outarr` is identical to the shape of
`arr`, except along the `axis` dimension. This axis is removed, and
replaced with new dimensions equal to the shape of the return value
of `func1d`. So if `func1d` returns a scalar `outarr` will have one
fewer dimensions than `arr`.

mapping的返回值的形状是怎样的? apply... 尝试通过对第一项进行计算来猜测这一点。在你的情况下['c']。因此它尝试返回 (3,1) 数组,并在第二行返回值时遇到问题。

将函数应用到 test 行的最佳方法是:

In [240]: [mapping(x) for x in test]
Out[240]: [['c'], ['b', 'c'], ['a']]

In [246]: np.apply_along_axis(mapping, 1, test[[0,2],:])
Out[246]:
array([['c'],
['a']],
dtype='<U1')

即使在有效的情况下,apply_along_axis 也不会提高速度 - 事实上,情况更糟

In [249]: timeit [mapping(x) for x in test]
20.4 µs ± 33 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [250]: timeit np.array([mapping(x) for x in test])
25.1 µs ± 192 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [251]: timeit np.apply_along_axis(mapping, 1, test[[0,2,2],:])
146 µs ± 194 ns per loop (mean ± std. dev. of 7 runs, 10000 loops e

关于python - numpy 沿轴应用,错误 "ValueError: could not broadcast input array from shape (2) into shape (1)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45317740/

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