在以数据框为输入的模型上进行多处理

时间:2019-02-20 22:28:35

标签: python machine-learning svm python-multiprocessing

我想对模型使用多重处理,以使用数据框作为输入来获取预测。我有以下代码:

def perform_model_predictions(model, dataFrame, cores=4): 
    try:
        with Pool(processes=cores) as pool:
            result = pool.map(model.predict, dataFrame)
            return result
        # return model.predict(dataFrame)
    except AttributeError:
        logging.error("AttributeError occurred", exc_info=True)

我得到的错误是:

raise TypeError("sparse matrix length is ambiguous; use getnnz()"
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0]

我认为问题在于我将数据帧作为第二个参数传递给pool.map函数。任何建议或帮助,将不胜感激。

1 个答案:

答案 0 :(得分:2)

诀窍是将数据帧拆分为多个块。 map期望model.predict将要处理的对象的列表。这是一个完整的工作示例,其中的模型显然被嘲笑了:

import numpy as np
import pandas as pd
from multiprocessing import Pool

no_cores = 4

large_df = pd.concat([pd.Series(np.random.rand(1111)), pd.Series(np.random.rand(1111))], axis = 1)
chunk_size = len(large_df) // no_cores + no_cores
chunks = [df_chunk for g, df_chunk in large_df.groupby(np.arange(len(large_df)) // chunk_size)]

class model(object):
    @staticmethod
    def predict(df):
        return np.random.randint(0,2)

def perform_model_predictions(model, dataFrame, cores): 
    try:
        with Pool(processes=cores) as pool:
            result = pool.map(model.predict, dataFrame)
            return result
        # return model.predict(dataFrame)
    except AttributeError:
        logging.error("AttributeError occurred", exc_info=True)

perform_model_predictions(model, chunks, no_cores)

请注意,此处选择的块数应与内核数(或您要分配的任何数字)相匹配。这样,每个内核都能获得公平的份额,multiprocessing不会在对象序列化上花费很多时间。

如果您想分别处理每一行(pd.Series),则可能需要花费时间进行序列化。在这种情况下,建议您使用joblib并阅读其各种后端的文档。我没有写它,因为您似乎想在pd.Dataframe上调用预报。

额外警告

multiprocessing可能会变得更糟,而不是让您获得更好的性能。当您的model.predict调用本身产生线程的外部模块时,就会发生这种情况。我写了关于问题here的文章。长话短说,joblib可能也是答案。