同时训练两个模型

时间:2013-05-19 04:07:18

标签: python multithreading multiprocessing scikit-learn

我需要做的就是,使用不同的核心,同时训练两个回归模型(使用scikit-learn)同一数据。我试图自己想出使用Process而没有成功。

gb1 = GradientBoostingRegressor(n_estimators=10)
gb2 = GradientBoostingRegressor(n_estimators=100)

def train_model(model, data, target):
    model.fit(data, target)

live_data # Pandas DataFrame object
target # Numpy array object
p1 = Process(target=train_model, args=(gb1, live_data, target)) # same data
p2 = Process(target=train_model, args=(gb2, live_data, target)) # same data
p1.start()
p2.start()

如果我运行上面的代码,在尝试启动p1进程时会出现以下错误。

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    p1.start()
  File "C:\Python27\lib\multiprocessing\process.py", line 130, in start
    self._popen = Popen(self)
  File "C:\Python27\lib\multiprocessing\forking.py", line 274, in __init__
    to_child.close()
IOError: [Errno 22] Invalid argument

我在Windows上运行所有这些作为脚本(在IDLE中)。有关如何进行的任何建议?

1 个答案:

答案 0 :(得分:3)

好的..在花了几个小时试图让这个工作,我会发布我的解决方案。 第一件事。如果您使用的是Windows并且正在使用交互式解释器,则需要在“”条件下封装所有代码,例如在函数定义和导入的情况下。这是因为当一个新的进程产生时将继续循环。

我的解决方案如下:

from sklearn.ensemble import GradientBoostingRegressor
from multiprocessing import Pool
from itertools import repeat

def train_model(params):
    model, data, target = params
    # since Pool args accept once argument, we need to pass only one
    # and then unroll it as above
    model.fit(data, target)
    return model

if __name__ == '__main__':
    gb1 = GradientBoostingRegressor(n_estimators=10)
    gb2 = GradientBoostingRegressor(n_estimators=100)

    live_data # Pandas DataFrame object
    target    # Numpy array object

    po = Pool(2) # 2 is numbers of process we want to spawn
    gb, gb2 = po.map_async(train_model, 
                 zip([gb1,gb2], repeat(data), repeat(target))
                 # this will zip in one iterable object
              ).get()
    # get will start the processes and execute them
    po.terminate()
    # kill the spawned processes
相关问题