繁体   English   中英

如何使用共享状态初始化python多处理工作者池?

[英]How to initialize a pool of python multiprocessing workers with a shared state?

我正在尝试并行执行一些机器学习算法

当我使用多处理时,它比没有处理要慢。 我的疯狂猜测是,我使用的模型的pickle序列化会减慢整个过程。 因此,问题是: 如何用初始状态初始化池的工作程序,这样就不必为每次调用模型都进行序列化/反序列化了?

这是我当前的代码:

import pickle
from pathlib import Path
from collections import Counter
from multiprocessing import Pool

from gensim.models.doc2vec import Doc2Vec

from wikimark import html2paragraph
from wikimark import tokenize


def process(args):
    doc2vec, regressions, filepath = args
    with filepath.open('r') as f:
        string = f.read()
    subcategories = Counter()
    for index, paragraph in enumerate(html2paragraph(string)):
        tokens = tokenize(paragraph)
        vector = doc2vec.infer_vector(tokens)
        for subcategory, model in regressions.items():
            prediction = model.predict([vector])[0]
            subcategories[subcategory] += prediction
    # compute the mean score for each subcategory
    for subcategory, prediction in subcategories.items():
        subcategories[subcategory] = prediction / (index + 1)
    # keep only the main category
    subcategory = subcategories.most_common(1)[0]
    return (filepath, subcategory)


def main():
    input = Path('./build')
    doc2vec = Doc2Vec.load(str(input / 'model.doc2vec.gz'))
    regressions = dict()
    for filepath in input.glob('./*/*/*.model'):
        with filepath.open('rb') as f:
            model = pickle.load(f)
        regressions[filepath.parent] = model

    examples = list(input.glob('../data/wikipedia/english/*'))

    with Pool() as pool:
        iterable = zip(
            [doc2vec] * len(examples),  # XXX!
            [regressions] * len(examples),  # XXX!
            examples
        )
        for filepath, subcategory in pool.imap_unordered(process, iterable):
            print('* {} -> {}'.format(filepath, subcategory))


if __name__ == '__main__':
    main()

标有XXX!的行XXX! 指向我调用pool.imap_unodered时序列化的数据。 至少有200MB的数据已序列化。

如何避免序列化?

该解决方案非常简单,就像对doc2vecregressions使用全局regressions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM