gpt4 book ai didi

python - 使用 numpy 数组优化 python 函数

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:46 24 4
gpt4 key购买 nike

这两天我一直在尝试优化我写的一个python脚本。使用多种分析工具(cProfile、line_profiler 等)我将问题缩小到以下函数。

df 是一个具有 3 列和 +1,000,000 行的 numpy 数组(数据类型为 float)。使用 line_profiler,我发现该函数在需要访问 numpy 数组时花费了大部分时间。

full_length += head + df[rnd_truck, 2]

full_weight += df[rnd_truck,1]

大部分时间,其次

full_length = df[rnd_truck,2]

full_weight = df[rnd_truck,1]

线条。

据我所知,瓶颈是由函数尝试从 numpy 数组中获取数字的访问时间引起的。

当我以 MonteCarlo(df, 15., 1000.) 运行该函数时,在具有 8GB RAM 的 i7 3.40GhZ 64 位 Windows 机器中调用该函数 1,000,000 次需要 37 秒。在我的应用程序中,我需要运行它 1,000,000,000 以确保收敛,这导致执行时间超过一个小时。我尝试对求和线使用 operator.add 方法,但它根本没有帮助我。看来我必须想出一种更快的方法来访问这个 numpy 数组。

欢迎任何想法!

def MonteCarlo(df,head,span):
# Pick initial truck
rnd_truck = np.random.randint(0,len(df))
full_length = df[rnd_truck,2]
full_weight = df[rnd_truck,1]

# Loop using other random truck until the bridge is full
while 1:
rnd_truck = np.random.randint(0,len(df))
full_length += head + df[rnd_truck, 2]
if full_length > span:
break
else:
full_weight += df[rnd_truck,1]

# Return average weight per feet on the bridge
return(full_weight/span)

下面是我正在使用的 df numpy 数组的一部分:

In [31] df
Out[31]:
array([[ 12. , 220.4, 108.4],
[ 11. , 220.4, 106.2],
[ 11. , 220.3, 113.6],
...,
[ 4. , 13.9, 36.8],
[ 3. , 13.7, 33.9],
[ 3. , 13.7, 10.7]])

最佳答案

正如其他人所指出的,这根本不是矢量化的,所以你的缓慢实际上是由于 Python 解释器的缓慢。 Cython可以在这里以最少的更改为您提供很多帮助:

>>> %timeit MonteCarlo(df, 5, 1000)
10000 loops, best of 3: 48 us per loop

>>> %timeit MonteCarlo_cy(df, 5, 1000)
100000 loops, best of 3: 3.67 us per loop

MonteCarlo_cy 只是(在 IPython notebook 中,在 %load_ext cythonmagic 之后):

%%cython
import numpy as np
cimport numpy as np

def MonteCarlo_cy(double[:, ::1] df, double head, double span):
# Pick initial truck
cdef long n = df.shape[0]
cdef long rnd_truck = np.random.randint(0, n)
cdef double full_weight = df[rnd_truck, 1]
cdef double full_length = df[rnd_truck, 2]

# Loop using other random truck until the bridge is full
while True:
rnd_truck = np.random.randint(0, n)
full_length += head + df[rnd_truck, 2]
if full_length > span:
break
else:
full_weight += df[rnd_truck, 1]

# Return average weight per feet on the bridge
return full_weight / span

关于python - 使用 numpy 数组优化 python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18134740/

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