将函数映射到 numpy 数组,改变参数

发布于 2024-09-28 10:32:26 字数 512 浏览 0 评论 0原文

首先,让我向您展示 codez:

a = array([...])
for n in range(10000):
    func_curry = functools.partial(func, y=n)
    result = array(map(func_curry, a))
    do_something_else(result)
    ...

我在这里所做的是尝试将 func 应用于数组,每次更改 func 第二个参数的值。这太慢了(每次迭代创建一个新函数肯定没有帮助),而且我也觉得我错过了 pythonic 的做法。有什么建议吗?

为我提供二维数组的解决方案是个好主意吗?我不知道,但也许是这样。

对可能问题的回答:

  • 是的,这是(使用广义定义),一个优化问题(do_something_else() 隐藏了这个)
  • 不,scipy.optimize 不起作用,因为我正在处理布尔值而且它似乎永远不会收敛。

First, let me show you the codez:

a = array([...])
for n in range(10000):
    func_curry = functools.partial(func, y=n)
    result = array(map(func_curry, a))
    do_something_else(result)
    ...

What I'm doing here is trying to apply func to an array, changing every time the value of the func's second parameter. This is SLOOOOW (creating a new function every iteration surely does not help), and I also feel I missed the pythonic way of doing it. Any suggestion?

Could a solution that gives me a 2D array be a good idea? I don't know, but maybe it is.

Answers to possible questions:

  • Yes, this is (using a broad definition), an optimization problem (do_something_else() hides this)
  • No, scipy.optimize hasn't worked because I'm dealing with boolean values and it never seems to converge.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

落在眉间の轻吻 2024-10-05 10:32:26

您尝试过 numpy.vectorize 吗?

...
    vfunc_curry = vectorize(functools.partial(func, y=n))
    result = vfunc_curry(a)
...

Did you try numpy.vectorize?

...
    vfunc_curry = vectorize(functools.partial(func, y=n))
    result = vfunc_curry(a)
...
梦里的微风 2024-10-05 10:32:26

如果a 的大小很大,那么瓶颈不应该是函数的创建,而是数组的复制。

If a is of significant size the bottleneck should not be the creation of the function, but the duplication of the array.

太阳男子 2024-10-05 10:32:26

你能重写这个函数吗?如果可能,您应该编写函数来获取两个 numpy 数组 anumpy.arange(n)。您可能需要重新调整形状以使数组排列起来进行广播。

Can you rewrite the function? If possible, you should write the function to take two numpy arrays a and numpy.arange(n). You may need to reshape to get the arrays to line up for broadcasting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文