3 回答

TA贡献1843条经验 获得超7个赞
我终于找到了一种方法,可以让 tqdm 进度条使用 np.vectorize 函数进行更新。我使用 with 包装了矢量化函数
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 = 0,然后函数就会调用 with 定义的 pbar
希望对在这里阅读的每个人都有帮助。

TA贡献1825条经验 获得超6个赞
据我所知,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进度。

TA贡献1876条经验 获得超6个赞
我想出了以下解决方案。我将 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)
...
添加回答
举报