gpt4 book ai didi

python - NumPy:有限的累积总和

转载 作者:行者123 更新时间:2023-12-04 17:57:04 25 4
gpt4 key购买 nike

有什么办法可以避免 for在这段代码中循环:

X = numpy array ~8000 long
running_total = 0
for x in X:
this_step = min(x, running_total)
running_total += this_step

换句话说,这是计算一个系列的累积总和,其中样本之间的差异仅限于累积总和的先前值。有没有办法使用 numpy 的元素操作来做到这一点?或者,如果我关心它的运行速度,我应该编写一个 C 函数吗?

编辑 显然我没有说清楚。我试图简化上面的代码似乎比其他任何事情都引起了更多的困惑。这是更接近实际代码的内容:
monthly_income = numpy array ~ 8000 long
monthly_expenditure = numpy array ~ 8000 long
running_credit = numpy.zeros(len(monthly_income) + 1)
monthly_borrowing = numpy.zeros(len(monthly_income))
for index, i, e in zip(range(len(monthly_income)), monthly_income, monthly_expenditure):
assets_used = max(0, e - i)
assets_used = min(assets_used, running_credit[index])
monthly_borrowing[index] = max(0, e - i - running_credit[index])
running_credit[index+1] += max(0, i - e) - assets_used

重点是 running_index[index+1]取决于 assets_used在 sample index ,这取决于 running_credit[index] .在 Python 循环中执行此操作很慢 - 在使用 NumPy 操作对相同输入数组执行许多类似计算的函数中,上述循环占用了超过 80% 的执行时间。但是我看不到没有 for 循环进行上述操作的方法。

那么有没有什么方法可以在没有 for 循环的情况下在 NumPy 中进行这种迭代操作?或者如果我想让它运行得快,我是否需要编写一个 C 函数?

最佳答案

对于我发现的此类问题,最简单的快速解决方法是使用 numba。例如。

from numba import jit
import numpy as np

def cumsumcapped(X):
running_total = 0
for x in X:
this_step = min(x, running_total)
running_total += this_step

@jit
def cumsumcappedjit(X):
running_total = 0
for x in X:
this_step = min(x, running_total)
running_total += this_step

X = np.random.randint(1, 100, 10000)

In [5]: %timeit cumsumcapped(X)
100 loops, best of 3: 4.1 ms per loop

In [6]: %timeit stack.cumsumcappedjit(X)
The slowest run took 170143.03 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 587 ns per loop

关于python - NumPy:有限的累积总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39599512/

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