Python sklearn LogisticRegression:它使用多个后台线程吗?

Python sklearn LogisticRegression:它使用多个后台线程吗?,python,scikit-learn,python-multiprocessing,python-multithreading,Python,Scikit Learn,Python Multiprocessing,Python Multithreading,我有使用和的代码。代码中的其他内容保持不变,使用多进程池运行代码会在逻辑回归路径中启动数百个线程,因此会完全影响性能-36个处理器的htop屏幕截图: 闲置: 林(一个处理器按预期保持空闲): 物流(所有处理器均为100%): 那么逻辑回归是否会产生后台线程(是),如果是,有没有办法防止这种情况发生 $ python3.6 Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux >>> skl

我有使用和的代码。代码中的其他内容保持不变,使用多进程池运行代码会在逻辑回归路径中启动数百个线程,因此会完全影响性能-36个处理器的htop屏幕截图:

闲置:

林(一个处理器按预期保持空闲):

物流(所有处理器均为100%):

那么逻辑回归是否会产生后台线程(是),如果是,有没有办法防止这种情况发生

$ python3.6
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
>>> sklearn.__version__
'0.20.1'

实例化
sklearn.linear\u model.LogisticRegression
时,始终可以通过
n\u jobs=n
传递要使用的线程数,其中
n
是所需的线程数。我会检查是否使用
n_jobs=1
运行它没有帮助。否则,Python可能会误读环境中可用线程的数量。为了确保它做得好,我会检查

import multiprocessing
print(multiprocessing.cpu_count())

在引擎盖下
logisticReturnal
使用执行线程的
sklearn.externals.joblib.Parallel
。它的逻辑相当复杂,因此如果不了解您的环境设置,就很难知道它到底在做什么。

假设在拟合模型时发生这种情况,请查看模型的fit()方法源代码()的这一部分:

敏锐地看到形势

prefer = 'threads'
**_joblib_parallel_args(prefer=prefer)
如果使用
sag
saga
解算器,可能会遇到线程问题。但是默认的解算器是
liblinear

另外,从上面()使用的Parallel()的源代码中,sklearn还谈到了线程问题的可能解决方法:

根据我的理解,以下内容可以减少线程:

from dask.distributed import Client
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression


...
# create local cluster
client = Client(processes=False)             
model = LogisticRegression()
with joblib.parallel_backend('dask'):
    model.fit(...)
...

按照建议进行利用。

我在林和回归初始化调用中将
n_作业
显式设置为1,并且我使用
多处理.cpu_count()
设置池大小-它工作正常<代码>n_作业会产生进程我这里说的是线程对不起,我误解了你。那么我的答案在这里没有用。我没有使用
sag
saga
。即使我是,是否有办法阻止skleran生成这些线程?我不确定线程生成代码是否实际位于实际计算回归的库中(
sklearn
只是它的一个接口)。也许这会有帮助:谢谢,@VivekKumar这是一个合格的答案-添加一些提示,说明我如何指定哪个库正在执行此操作,这将是一件非常重要的事情,尽管我仍然不确定为什么RandomForests不使用任何一个,但我不能确定。但这可能与@ChuckIvan指出的事实有关,LR在内部使用liblinear,这可能有不同的实现,而RandomForests是由sklearn开发的,因此涵盖了这一点。
'threading' is a low-overhead alternative that is most efficient for
functions that release the Global Interpreter Lock: e.g. I/O-bound code or
CPU-bound code in a few calls to native code that explicitly releases the
GIL.
In addition, if the `dask` and `distributed` Python packages are installed,
it is possible to use the 'dask' backend for better scheduling of nested
parallel calls without over-subscription and potentially distribute
parallel calls over a networked cluster of several hosts.
from dask.distributed import Client
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression


...
# create local cluster
client = Client(processes=False)             
model = LogisticRegression()
with joblib.parallel_backend('dask'):
    model.fit(...)
...