首页 > 解决方案 > PyQt5 在单独的 QThread 上运行 sklearn 计算

问题描述

我正在创建一个 PyQt5 应用程序,并希望在单击按钮时在单独的线程中运行一些 ML 代码。我无法这样做。这是我的线程代码:

newthread = QtCore.QThread()
runthread = RunThread()
runthread.moveToThread(newthread)
runthread.finished.connect(newthread.quit)
newthread.started.connect(runthread.long_run)
newthread.start()

RunThread 类如下:

class RunThread(QtCore.QObject):

finished = QtCore.pyqtSignal()

def __init__(self):
    super().__init__()

@pyqtSlot()
def long_run(self):
    #ML code called in the line below
    simulation.start_simulation()
    self.finished.emit()

正常运行是不行的。Pycharm 退出并出现以下错误:

process finished with exit code -1073740791 (0xc0000409)

在调试模式下运行它会引发 sklearn 抛出的数千条警告:

Multiprocessing-backed parallel loops cannot be nested below threads,
setting n_jobs=1

代码最终会运行,但这样做需要更多时间(至少 4 倍)。

有人可以让我知道这里的问题是什么吗?

标签: pythonscikit-learnpyqtpyqt5

解决方案


sklearn 的警告在这里非常明确。基本上,当从嵌套线程执行时,您无法训练超参数n_jobs设置为大于 1 的任何 sklearn 模型。

话虽如此,如果没有看到内部发生的simulation.start_simulation()事情,很难推测。

我最好的猜测是寻找start_simulation()使用多个作业的任何内容,看看当您将其设置为n_jobs=1.

或者,您可以尝试将 ML 代码编写为独立脚本并使用 QProcess 执行它。这可能允许您使用n_jobs大于 1。


推荐阅读