【问题标题】:Parallelize function on dictionary in IPythonIPython中字典的并行化函数
【发布时间】:2013-05-19 01:55:12
【问题描述】:

到目前为止,我已经通过使用函数 map_sync(function, list) 将函数映射到分布到各个集群的列表来实现函数的并行化。

现在,我需要对字典的每个条目运行一个函数。

map_sync 似乎不适用于字典。我还尝试分散字典并使用装饰器并行运行该函数。然而,字典似乎也不适合分散。 是否有其他方法可以并行化字典上的函数而无需转换为列表?

这些是我迄今为止的尝试:

from IPython.parallel import Client
rc = Client()
dview = rc[:]

test_dict = {'43':"lion", '34':"tiger", '343':"duck"}
dview.scatter("test",test)

dview["test"]
# this yields [['343'], ['43'], ['34'], []] on 4 clusters
# which suggests that a dictionary can't be scattered?

不用说,当我运行函数本身时,我得到一个错误:

@dview.parallel(block=True)
def run():
    for d,v in test.iteritems():
        print d,v

run()

属性错误
() 中的 Traceback(最近一次调用最后一次) 在运行(字典) AttributeError:“str”对象没有属性“iteritems”

我不知道这是否相关,但我使用的是连接到 Amazon AWS 集群的 IPython Notebook。

【问题讨论】:

    标签: dictionary ipython ipython-notebook ipython-parallel


    【解决方案1】:

    您可以使用以下命令分散一个字典:

    def scatter_dict(view, name, d):
        """partition a dictionary across the engines of a view"""
        ntargets = len(view)
        keys = d.keys() # list(d.keys()) in Python 3
        for i, target in enumerate(view.targets):
            subd = {}
            for key in keys[i::ntargets]:
                subd[key] = d[key]
            view.client[target][name] = subd
    
    scatter_dict(dview, 'test', test_dict)
    

    然后像往常一样对其进行远程操作。

    您还可以将远程字典再次收集到一个本地字典中:

    def gather_dict(view, name):
        """gather dictionaries from a DirectView"""
        merged = {}
        for d in view.pull(name):
            merged.update(d)
        return merged
    
    gather_dict(dv, 'test')
    

    An example notebook

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-28
      相关资源
      最近更新 更多