自定义Dask可遍历对象

时间:2018-10-07 11:08:43

标签: python dask dask-delayed

我使用了像对象这样的自定义词典来轻松存储Dask图的结果,但是使用结果对象计算Dask图却不计算其子级。

是否可以更改自定义对象,使Dask能够遍历并计算其子对象?

一个例子:

import dask
import dask.delayed as delayed
from collections import defaultdict
print('Dask version', dask.__version__)

Dictionary1 = {}
Dictionary1['a'] = delayed(sum)([2,3])

print('Native Dict', dask.compute(Dictionary1) )

Dictionary2 = defaultdict(defaultdict)
Dictionary2['a'] = delayed(sum)([2,3])

print('Custom Dict', dask.compute(Dictionary2) )

结果输出:

Dask version 0.19.2
Native Dict ({'a': 5},)
Custom Dict (defaultdict(<class 'collections.defaultdict'>, {'a': Delayed('sum-212db0df-1c14-4314-9a56-2eb87ef58abe')}),)

编辑:基于MRocklin答案的解决方案

import dask
import dask.delayed as delayed
from collections import defaultdict
from dask.base import DaskMethodsMixin

class DefaultDictDict(defaultdict, DaskMethodsMixin):
  def __init__(self, *args ): ## Define an infinite nested dict.
    return defaultdict.__init__(self, DefaultDictDict, *args)

  def __dask_graph__(self):
    ## NOTE: Errors in this functions are silent, and disable collections interface
    ## The dask attributes are already a graph with key to itself.
    a = dict()
    self._keys = []
    for x in self.values():
      if not hasattr(x,'dask'): ## Use dummy delayed to convert objects to graphs.
        x = delayed(lambda data:data)(x)
      a.update(x.dask) 
      self._keys.append(x.key)
    return a

  def __dask_keys__(self):
    return self._keys

  __dask_scheduler__ = staticmethod(dask.threaded.get)
  def __dask_postcompute__(self):
      def Reconstruct(results):
        return DefaultDictDict(zip(self.keys(), results))
      return Reconstruct, ()  

Dictionary3 = DefaultDictDict()
Dictionary3['b']['c'] = delayed(sum)([2,3])
print('Collections Dict', dask.compute(Dictionary3)[0] )

结果:

Collections Dict defaultdict(<class '__main__.DefaultDictDict'>, {'b': defaultdict(<class '__main__.DefaultDictDict'>, {'c': 5})})

(它仍然显示defaultdict,因为__repr__未被正确覆盖)

1 个答案:

答案 0 :(得分:1)

目前,Dask仅遍历标准的核心Python集合(字典,列表等)。截至2018年10月7日,此行为不可扩展。

但是,您可以创建自己的Dask集合,这些集合实际上只是传递其成员的图形和键。参见http://docs.dask.org/en/latest/custom-collections.html