【发布时间】:2018-09-25 00:37:37
【问题描述】:
这与how to parallelize many (fuzzy) string comparisons using apply in Pandas?有关
再次考虑这个简单(但有趣)的例子:
import dask.dataframe as dd
import dask.multiprocessing
import dask.threaded
from fuzzywuzzy import fuzz
import pandas as pd
master= pd.DataFrame({'original':['this is a nice sentence',
'this is another one',
'stackoverflow is nice']})
slave= pd.DataFrame({'name':['hello world',
'congratulations',
'this is a nice sentence ',
'this is another one',
'stackoverflow is nice'],'my_value': [1,2,3,4,5]})
def fuzzy_score(str1, str2):
return fuzz.token_set_ratio(str1, str2)
def helper(orig_string, slave_df):
slave_df['score'] = slave_df.name.apply(lambda x: fuzzy_score(x,orig_string))
#return my_value corresponding to the highest score
return slave_df.loc[slave_df.score.idxmax(),'my_value']
master
Out[39]:
original
0 this is a nice sentence
1 this is another one
2 stackoverflow is nice
slave
Out[40]:
my_value name
0 1 hello world
1 2 congratulations
2 3 this is a nice sentence
3 4 this is another one
4 5 stackoverflow is nice
我需要做的很简单:
- 对于
master中的每一行,我使用fuzzywuzzy计算的字符串相似度得分在Dataframeslave中查找最佳匹配。
现在让我们把这些数据框放大一点:
master = pd.concat([master] * 100, ignore_index = True)
slave = pd.concat([slave] * 10, ignore_index = True)
首先,我尝试过dask
#prepare the computation
dmaster = dd.from_pandas(master, npartitions=4)
dmaster['my_value'] = dmaster.original.apply(lambda x: helper(x, slave),meta=('x','f8'))
现在是时间安排:
#multithreaded
%timeit dmaster.compute(get=dask.threaded.get)
1 loop, best of 3: 346 ms per loop
#multiprocess
%timeit dmaster.compute(get=dask.multiprocessing.get)
1 loop, best of 3: 1.93 s per loop
#good 'ol pandas
%timeit master['my_value'] = master.original.apply(lambda x: helper(x,slave))
100 loops, best of 3: 2.18 ms per loop
其次,我尝试过使用旧的 multiprocessing 包
from multiprocessing import Pool, cpu_count
def myfunc(df):
return df.original.apply(lambda x: helper(x, slave))
from datetime import datetime
if __name__ == '__main__':
startTime = datetime.now()
p = Pool(cpu_count() - 1)
ret_list = p.map(myfunc, [master.iloc[1:100,], master.iloc[100:200 ,],
master.iloc[200:300 ,]])
results = pd.concat(ret_list)
print datetime.now() - startTime
大约在同一时间
runfile('C:/Users/john/untitled6.py', wdir='C:/Users/john')
0:00:01.927000
问题:为什么与这里的 Pandas 相比,Dask 和 multiprocessing 的多处理速度如此之慢?假设我的真实数据比这大得多。我能得到更好的结果吗?
毕竟我这里考虑的问题是embarassingly parallel(每一行都是一个独立的问题),所以这些包应该真的很亮眼。
我错过了什么吗?
谢谢!
【问题讨论】:
-
我认为这是因为您需要更多的计算(水平扩展)能力来证明 dask 的所有额外开销是合理的。
-
还不够! numpy 也能做到,你需要更多的 computers :D
-
第一次调用 multiprocessing 需要时间来启动额外的进程,然后才能开始计算任何东西。 如果您的所有数据都可以轻松放入内存中,那么 dask 不一定是正确的选择。哦,您应该使用分布式调度程序,即使在单台机器上也是如此。
-
接下来,您需要考虑与序列化数据、将其发送到进程、反序列化以及返回输出。除此之外,还有管理任务执行的开销。
-
这听起来像是答案吗?一些讨论distributed.readthedocs.io/en/latest/efficiency.html
标签: python pandas multiprocessing python-multiprocessing dask