Python 以数据帧为输入的模型上的多处理
我想对一个模型进行多处理,以获得使用数据帧作为输入的预测。我有以下代码:Python 以数据帧为输入的模型上的多处理,python,machine-learning,svm,python-multiprocessing,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 mo
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
函数。如有任何建议或帮助,将不胜感激 诀窍是将数据帧分割成块map
需要一个将由模型处理的对象列表。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)
请注意,此处选择的块数与内核数(或您想要分配的任何数量)匹配。通过这种方式,每个核心都可以获得公平的份额,多处理
不会在对象序列化上花费太多时间
如果您想单独处理每一行(pd.Series
),那么在序列化上花费的时间可能是一个问题。在这种情况下,我建议使用joblib
并在其各种后端阅读文档。我没有在上面写,因为您似乎想在pd.Dataframe
上调用predict
额外警告
可能发生的情况是,
多处理
,不但不能提高性能,反而会使性能更差。当您的model.predict
调用自身产生线程的外部模块时,这种情况非常罕见。我写了关于这个问题的文章。长话短说,joblib
也可能是答案。我尝试使用:data=class\u name.perform\u model\u transformation(model,transformed\u data)chunk\u size=len(data)//cores+cores chunk=[df\u chunk for g,df\u chunk in data.groupby(np.arange(len(data))//chunk\u size]标记为\u data=class\u name。执行\u model\u预测(模型、块、核心)
我得到了相同的错误:稀疏矩阵长度不明确;使用getnnz()或shape[0]
错误来自您的predict
代码,我们不知道那里发生了什么,您的原始代码是不正确的,因为它正在传递一个数据帧,其中需要iterable元素。复制并粘贴我的代码以查看它是否有效。调整predict
code,使其与数据框一起工作。参考:数据的类型为:data
,形状为(49800)
,那么你的标题和文本是误导性的,因为它使人们认为你在使用数据框。您可以使用与此处相同的逻辑将矩阵切分为更小的块。@YihanBao清楚如何将矩阵切分为块?