将函数映射到 numpy 数组,改变参数
首先,让我向您展示 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尝试过 numpy.vectorize 吗?
Did you try
numpy.vectorize
?如果
a
的大小很大,那么瓶颈不应该是函数的创建,而是数组的复制。If
a
is of significant size the bottleneck should not be the creation of the function, but the duplication of the array.你能重写这个函数吗?如果可能,您应该编写函数来获取两个 numpy 数组
a
和numpy.arange(n)
。您可能需要重新调整形状以使数组排列起来进行广播。Can you rewrite the function? If possible, you should write the function to take two numpy arrays
a
andnumpy.arange(n)
. You may need to reshape to get the arrays to line up for broadcasting.