tqdm和numpy矢量化

yuvru6vn  于 2023-08-05  发布在  其他
关注(0)|答案(3)|浏览(137)

我正在使用一个np.vectorize-艾德函数,并希望看到该函数与tqdm的进展。但是,我一直没能弄清楚如何做到这一点。
我找到的所有建议都与将计算转换为for循环或pd. DataFrame有关。

wgx48brx

wgx48brx1#

我终于找到了一个方法,它可以使用np.vectorize函数来更新tqdm进度条。我使用with Package 了vectorize函数

with tqdm(total=len(my_inputs)) as pbar:
    my_output = np.vectorize(my_function)(my_inputs)

字符串
在my_function()中添加以下行

global pbar
pbar.update(1)


瞧!我现在有了一个随每次迭代更新的进度条。我的代码只有轻微的性能下降。
注意:当你示例化函数时,它可能会抱怨pbar还没有定义。在示例化之前只需输入一个pbar =,然后该函数将调用由with定义的pbar
希望对大家阅读这里有所帮助。

p8h8hvxi

p8h8hvxi2#

根据@Carl Kirstein的回答,我提出了以下解决方案。我将pbar元素作为参数添加到my_function中,并在函数中对其进行了更新。

with tqdm(total=len(my_inputs)) as pbar:
    my_output = np.vectorize(my_function)(my_inputs, pbar)

字符串
my_function中的某个地方添加了pbar.update(1)

def my_function(args, pbar):
    ...
    pbar.update(1)
    ...

zc0qhyus

zc0qhyus3#

据我所知,tqdm不会覆盖numpy.vectorize
要显示numpy数组的进度条,可以使用numpy.ndenumerate
给定输入和函数:

import numpy as np
from tqdm import tqdm

a = np.array([1, 2, 3, 4])
b = 2
def myfunc(a, b):
    "Return a-b if a>b, otherwise return a+b"
    if a > b:
        return a - b
    else:
        return a + b

字符串
替换下面的矢量化部分

# using numpy.vectorize
vfunc = np.vectorize(myfunc)
vfunc(a, b)


用这个

# using numpy.ndenumerate instead
[myfunc(x,b) for index, x in tqdm(np.ndenumerate(a))]


查看tqdm的进度。

相关问题