【问题标题】:Train two models concurrently同时训练两个模型
【发布时间】:2013-05-19 04:07:17
【问题描述】:

我需要做的就是,使用不同的内核同时在相同数据上训练两个回归模型(使用 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 中)运行。关于我应该如何进行的任何建议?

【问题讨论】:

  • 看看可能使用 multiprocessing.Pool
  • 尝试通过将目标函数和参数更改为非常简单来测试它(即def myfun(*args): pass; Process(target=myfun, args=(1,)),然后查看它是否失败。之后,引入更多元素。至少这样你可以隔离问题出在哪里。
  • 嘿,杰夫,我已经按照你说的定义了 myfun(很酷的想法)。首先我通过了 GradientBoostingRegressor 指针,没有问题。然后我尝试传递数据,这实际上是一个 pandas 数据框,但它失败并显示相同的消息。然后我尝试使用目标变量(这是一个 numpy.ndarray)并得到一个全新的错误消息 IOError: [Errno 32] Broken pipe
  • 为什么不用joblib?它包含在 sklearn 中。
  • 另外:scikit-learn 不接受 pandas DataFrame 对象。

标签: python multithreading multiprocessing scikit-learn


【解决方案1】:

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

我的解决方案如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 2019-08-25
    • 2017-08-19
    • 2020-01-10
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多