我必须像这样挑选一个对象数组:
import cPickle as pickle
from numpy import sin, cos, array
tmp = lambda x: sin(x)+cos(x)
test = array([[tmp,tmp],[tmp,tmp]],dtype=object)
pickle.dump( test, open('test.lambda','w') )
Run Code Online (Sandbox Code Playgroud)
它会出现以下错误:
TypeError: can't pickle function objects
Run Code Online (Sandbox Code Playgroud)
有办法吗?
我有一个我试图并行化的算法,因为串行运行时间很长。然而,需要并行化的函数在一个类中。multiprocessing.Pool似乎是最好和最快的方式来做到这一点,但有一个问题。它的目标函数不能是对象实例的函数。意思是这个;您可以Pool通过以下方式声明 a :
import multiprocessing as mp
cpus = mp.cpu_count()
poolCount = cpus*2
pool = mp.Pool(processes = poolCount, maxtasksperchild = 2)
Run Code Online (Sandbox Code Playgroud)
然后实际使用它:
pool.map(self.TargetFunction, args)
Run Code Online (Sandbox Code Playgroud)
但这会引发错误,因为无法对对象实例进行腌制,因为该Pool函数确实会将信息传递给其所有子进程。但我必须使用self.TargetFunction
所以我有一个想法,我将创建一个名为的新 Python 文件,parallel并简单地编写几个函数而不将它们放在一个类中,然后从我的原始类(我想并行化其函数)中调用这些函数
所以我试过这个:
import multiprocessing as mp
def MatrixHelper(args):
WM = args[0][0]
print(WM.CreateMatrixMp(*args))
return WM.CreateMatrixMp(*args)
def Start(sigmaI, sigmaX, numPixels, WM):
cpus = mp.cpu_count()
poolCount = cpus * 2
args = [(WM, sigmaI, sigmaX, i) for i in range(numPixels)]
print('Number of cpu\'s …Run Code Online (Sandbox Code Playgroud)