python循环中的多处理



我正在借助正对生成负对。我想通过使用CPU的所有核心来加快进程。在单个CPU核心上,包括白天和黑夜,几乎需要5天。

我倾向于在多处理中更改以下代码。与此同时,我没有&;positives_negatives.csv&;

if Path("positives_negatives.csv").exists():
df = pd.read_csv("positives_negatives.csv")
else:
for combo in tqdm(itertools.combinations(identities.values(), 2), desc="Negatives"):
for cross_sample in itertools.product(combo[0], combo[1]):
negatives = negatives.append(pd.Series({"file_x": cross_sample[0], "file_y": cross_sample[1]}).T,
ignore_index=True)
negatives["decision"] = "No"
negatives = negatives.sample(positives.shape[0])
df = pd.concat([positives, negatives]).reset_index(drop=True)
df.to_csv("positives_negatives.csv", index=False)
<<p>修改代码/strong>
def multi_func(iden, negatives):
for combo in tqdm(itertools.combinations(iden.values(), 2), desc="Negatives"):
for cross_sample in itertools.product(combo[0], combo[1]):
negatives = negatives.append(pd.Series({"file_x": cross_sample[0], "file_y": cross_sample[1]}).T,
ignore_index=True)

使用

if Path("positives_negatives.csv").exists():
df = pd.read_csv("positives_negatives.csv")
else:
with concurrent.futures.ProcessPoolExecutor() as executor:
secs = [5, 4, 3, 2, 1]
results = executor.map(multi_func(identities, negatives), secs)
negatives["decision"] = "No"
negatives = negatives.sample(positives.shape[0])
df = pd.concat([positives, negatives]).reset_index(drop=True)
df.to_csv("positives_negatives.csv", index=False)

最好的方法是实现进程池执行器类并创建一个单独的函数。就像你可以通过这种方式实现一样

<<p>库/strong>
from concurrent.futures.process import ProcessPoolExecutor
import more_itertools
from os import cpu_count
def compute_cross_samples(x):
return pd.DataFrame(itertools.product(*x), columns=["file_x", "file_y"])
<<p>修改代码/strong>
if Path("positives_negatives.csv").exists():
df = pd.read_csv("positives_negatives.csv")
else:
with ProcessPoolExecutor() as pool:
# take cpu_count combinations from identities.values
for combos in tqdm(more_itertools.ichunked(itertools.combinations(identities.values(), 2), cpu_count())):
# for each combination iterator that comes out, calculate the cross
for cross_samples in pool.map(compute_cross_samples, combos):
# for each product iterator "cross_samples", iterate over its values and append them to negatives
negatives = negatives.append(cross_samples)
negatives["decision"] = "No"
negatives = negatives.sample(positives.shape[0])
df = pd.concat([positives, negatives]).reset_index(drop=True)
df.to_csv("positives_negatives.csv", index=False)

相关内容

  • 没有找到相关文章

最新更新