在多处理模块中使用Pool.map_async() (以及Pool.map())时遇到问题。我已经实现了一个并行循环函数,只要输入到Pool.map_async的函数是“常规”函数,它就能正常工作。当函数是一个类的方法时,我会得到一个PicklingError
cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed我只使用Python进行科学计算,所以我对酸洗的概念不是很熟悉,今天我才学到了一点。我已经看过几个以前的答案,比如Can't pickle when using multiprocessing Pool.map(),但我不知道如何让它工作,即使是按照答案中提供的链接。
我的代码,其中的目标是使用多个内核模拟正常r.v的向量。请注意,这只是一个示例,可能在多个内核上运行甚至不会带来回报。
import multiprocessing as mp
import scipy as sp
import scipy.stats as spstat
def parfor(func, args, static_arg = None, nWorkers = 8, chunksize = None):
"""
Purpose: Evaluate function using Multiple cores.
Input:
func - Function to evaluate in parallel
arg - Array of arguments to evaluate func(arg)
static_arg - The "static" argument (if any), i.e. the variables that are constant in the evaluation of func.
nWorkers - Number of Workers to process computations.
Output:
func(i, static_arg) for i in args.
"""
# Prepare arguments for func: Collect arguments with static argument (if any)
if static_arg != None:
arguments = [[arg] + static_arg for arg in list(args)]
else:
arguments = args
# Initialize workers
pool = mp.Pool(processes = nWorkers)
# Evaluate function
result = pool.map_async(func, arguments, chunksize = chunksize)
pool.close()
pool.join()
return sp.array(result.get()).flatten()
# First test-function. Freeze location and scale for the Normal random variates generator.
# This returns a function that is a method of the class Norm_gen. Methods cannot be pickled
# so this will give an error.
def genNorm(loc, scale):
def subfunc(a):
return spstat.norm.rvs(loc = loc, scale = scale, size = a)
return subfunc
# Second test-function. The same as above but does not return a method of a class. This is a "plain" function and can be
# pickled
def test(fargs):
x, a, b = fargs
return spstat.norm.rvs(size = x, loc = a, scale = b)
# Try it out.
N = 1000000
# Set arguments to function. args1 = [1, 1, 1,... ,1], the purpose is just to generate a random variable of size 1 for each
# element in the output vector.
args1 = sp.ones(N)
static_arg = [0, 1] # standarized normal.
# This gives the PicklingError
func = genNorm(*static_arg)
sim = parfor(func, args1, static_arg = None, nWorkers = 12, chunksize = None)
# This is OK:
func = test
sim = parfor(func, args1, static_arg = static_arg, nWorkers = 12, chunksize = None)根据Can't pickle when using multiprocessing Pool.map()中问题答案中提供的链接,Steven Bethard (几乎在最后)建议使用copy_reg模块。他的代码是:
def _pickle_method(method):
func_name = method.im_func.__name__
obj = method.im_self
cls = method.im_class
return _unpickle_method, (func_name, obj, cls)
def _unpickle_method(func_name, obj, cls):
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get__(obj, cls)
import copy_reg
import types
copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)我真的不明白我该如何利用它。我唯一能想到的就是把它放在我的代码之前,但这并不管用。当然,一个简单的解决方案是只使用有效的解决方案,并避免涉及到copy_reg。我更感兴趣的是让copy_reg正常工作,以充分利用多进程,而不必每次都绕过问题。
发布于 2011-08-11 04:44:17
这里的问题与其说是"pickle“错误消息,不如说是概念性的:多进程确实在"worker”不同的进程中派生代码,以便执行它的魔术。
然后,它通过无缝序列化和反序列化数据(即使用pickle的部分)将数据发送到不同的进程或从不同的进程发送数据。
当来回传递的部分数据是一个函数时-它假定被调用进程中存在一个同名的函数,并(我猜)将函数名作为字符串传递。因为函数是无状态的,所以被调用的工作进程只使用它接收到的数据调用相同的函数。(Python函数不能通过pickle序列化,所以只在主进程和辅助进程之间传递引用)
当你的函数是一个实例中的一个方法时-尽管当我们编写python代码时,它很像一个函数,有一个“自动”的self变量,但它的本质是不同的。因为实例(对象)是有状态的。这意味着辅助进程没有对象的副本,该对象是您要在另一端调用的方法的所有者。
绕过将方法作为函数传递给map_async调用的方法也是行不通的-因为多进程在传递函数时只使用函数引用,而不是实际的函数。
因此,您应该(1)更改您的代码,以便将函数(而不是方法)传递给工作进程,将对象保留的任何状态转换为要调用的新参数。(2)为map_async调用创建一个“目标”函数,该函数在工作进程端重新构造所需的对象,然后在其中调用该函数。Python中大多数简单的类本身都是可拾取的,因此您可以在map_async调用中传递作为函数所有者本身的对象-“目标”函数将在工作程序端调用适当的方法本身。
(2)听起来很“难”,但它可能就像这样--除非你的对象的类不能被酸洗:
import types
def target(object, *args, **kw):
method_name = args[0]
return getattr(object, method_name)(*args[1:])
(...)
#And add these 3 lines prior to your map_async call:
# Evaluate function
if isinstance (func, types.MethodType):
arguments.insert(0, func.__name__)
func = target
result = pool.map_async(func, arguments, chunksize = chunksize)*免责声明:我还没有测试过
https://stackoverflow.com/questions/7016567
复制相似问题