Scikit-learn: GridSearchCV 并行执行与自己的得分手冻结

创建于 2014-02-24  ·  99评论  ·  资料来源: scikit-learn/scikit-learn

我一直在寻找这个问题的时间,并且可以始终如一地复制它:

clf = GridSearchCV( sk.LogisticRegression(),
                            tuned_parameters,
                            cv = N_folds_validation,
                            pre_dispatch='6*n_jobs', 
                            n_jobs=4,
                            verbose = 1,
                            scoring=metrics.make_scorer(metrics.scorer.f1_score, average="macro")
                        )

由于 score=metrics.make_scorer(metrics.scorer.f1_score,average="macro") 其中 metrics 指的是 sklearn.metrics 模块,此代码段会崩溃。 如果我取消 score=... 行,则并行执行有效。 如果我想使用 f1 分数作为评估方法,我必须通过设置 n_jobs = 1 来取消并行执行。

有没有一种方法可以在不失去并行执行可能性的情况下定义另一种评分方法?

谢谢

最有用的评论

嗯,这可能与 Windows 上的多处理问题有关。 也许@GaelVaroquaux@ogrisel可以提供帮助。
我不知道笔记本的__name__ == "__main__"
尝试不在笔记本中定义指标,而是在单独的文件中定义并导入它。 我认为这会解决它。
这与 GridSearchCV 并没有真正的关系,而是 Windows 多处理、IPython notebook 和 joblib 之间的一些有趣的交互。

所有99条评论

这令人惊讶,所以我们必须找出问题所在并确保它有效!

能否请您提供更详细的信息:

  • 你说的“崩溃”是什么意思?
  • 这是什么版本的 scikit-learn? 如果是0.14,在目前的开发版本中还会出现吗?
  • 多处理具有特定于平台的问题。 你在什么平台? (例如import platform; platform.platform()
  • 您是否在不同的数据集上尝试过?

FWIW,我的机器在 sklearn 的开发版本上用这个片段安装 iris 没有问题。

感谢您的快速回复。

崩溃我实际上是指冻结。 它不再继续,并且在windows任务管理器的python进程中也没有更多的活动需要监控。 这些进程仍然存在并消耗恒定数量的 RAM,但不需要处理时间。

这是 scikit-learn 0.14 版,最后更新并使用 Enthought Canopy 运行。

我在平台“Windows-7-6.1.7601-SP1”上。

我将通过提供该问题的通用示例来更深入。 我认为这与 GridSearchCV 被放置在 for 循环中有关。 (为了不浪费太多时间,您可能应该从在代码底部调用的 run_tune_process() 方法开始,并在 for 循环中调用包含 GridSearchCV() 的方法)

代码:

import sklearn.metrics as metrics
from sklearn.grid_search import GridSearchCV
import numpy as np
import os
from sklearn import datasets
from sklearn import svm as sk


def tune_hyperparameters(trainingData, period):
    allDataTrain = trainingData

    # Define hyperparameters and construct a dictionary of them
    amount_kernels = 2
    kernels = ['rbf','linear']
    gamma_range =   10. ** np.arange(-5, 5)
    C_range =       10. ** np.arange(-5, 5)
    tuned_parameters = [
                        {'kernel': ['rbf'],     'gamma': gamma_range , 'C': C_range},
                        {'kernel': ['linear'],  'C': C_range}
                       ]

    print("Tuning hyper-parameters on period = " + str(period) + "\n")

    clf = GridSearchCV( sk.SVC(), 
                        tuned_parameters,
                        cv=5,
                        pre_dispatch='4*n_jobs', 
                        n_jobs=2,
                        verbose = 1,
                        scoring=metrics.make_scorer(metrics.scorer.f1_score, average="macro")
                        )
    clf.fit(allDataTrain[:,1:], allDataTrain[:,0:1].ravel())

    # other code will output some data to files, graphs and will save the optimal model with joblib package


    #   Eventually we will return the optimal model
    return clf

def run_tune_process(hyperparam_tuning_method,trainingData, testData):    
    for period in np.arange(0,100,10):
                clf = hyperparam_tuning_method(trainingData,period)

                y_real = testData[:,0:1].ravel()
                y_pred = clf.predict(testData[:,1:])

# import some data to play with
iris = datasets.load_iris()
X_training = iris.data[0:100,:]  
Y_training = (iris.target[0:100]).reshape(100,1)
trainingset = np.hstack((Y_training, X_training))

X_test = iris.data[100:150,:]  
Y_test = (iris.target[100:150]).reshape(50,1)
testset = np.hstack((Y_test, X_test))

run_tune_process(tune_hyperparameters,trainingset,testset)

再一次,只有当我将 n_jobs 更改为 1 或当我没有定义 score= 参数时,此代码才能在我的计算机上运行。

一般Windows中的多处理会遇到很多问题。 但是我
不知道为什么这应该与自定义指标相关联。 有
没有关于 0.14 中的 average=macro 选项表明它应该是
比默认平均值(加权)更有可能挂起。 在发展
头,这在我的 macbook 上在 11 秒内完成,在 0.14 版中在 7 秒内完成
(这是要研究的东西!)

你能在当前的开发版本中尝试这个,看看是否
它仍然是一个问题?

自2014年2月25日20时40分,adverley [email protected]写道:

感谢您的快速回复。

崩溃我实际上是指冻结。 它不再继续并且
在 python 进程中也没有更多的活动需要监控
windows的任务管理器。 进程仍然存在并消耗
恒定数量的 RAM,但不需要处理时间。

这是 scikit-learn 0.14 版,最后更新并使用 Enthought 运行
天篷。

我在平台“Windows-7-6.1.7601-SP1”上。

我将通过提供该问题的通用示例来更深入。 一世
认为这与 GridSearchCV 被放置在 for 循环中有关。 (到
不要浪费太多时间,你应该从
在代码底部调用的 run_tune_process() 方法
并在 for 循环中调用包含 GridSearchCV() 的方法)
代码:

导入 sklearn.metrics 作为指标
从 sklearn.grid_search 导入 GridSearchCV
将 numpy 导入为 np
导入操作系统
从 sklearn 导入数据集
从 sklearn 导入 svm 作为 sk

def tune_hyperparameters(trainingData, period):
allDataTrain = trainingData

# Define hyperparameters and construct a dictionary of them
amount_kernels = 2
kernels = ['rbf','linear']
gamma_range =   10. ** np.arange(-5, 5)
C_range =       10. ** np.arange(-5, 5)
tuned_parameters = [
                    {'kernel': ['rbf'],     'gamma': gamma_range , 'C': C_range},
                    {'kernel': ['linear'],  'C': C_range}
                   ]

print("Tuning hyper-parameters on period = " + str(period) + "\n")

clf = GridSearchCV( sk.SVC(),
                    tuned_parameters,
                    cv=5,
                    pre_dispatch='4*n_jobs',
                    n_jobs=2,
                    verbose = 1,
                    scoring=metrics.make_scorer(metrics.scorer.f1_score, average="macro")
                    )
clf.fit(allDataTrain[:,1:], allDataTrain[:,0:1].ravel())

# other code will output some data to files, graphs and will save the optimal model with joblib package


#   Eventually we will return the optimal model
return clf

def run_tune_process(hyperparam_tuning_method,trainingData,testData):
对于 np.arange(0,100,10) 中的期间:
clf = hyperparam_tuning_method(trainingData,period)

            y_real = testData[:,0:1].ravel()
            y_pred = clf.predict(testData[:,1:])

导入一些数据来玩

虹膜 = datasets.load_iris()
X_training = iris.data[0:100,:]
Y_training = (iris.target[0:100]).reshape(100,1)
训练集 = np.hstack((Y_training, X_training))

X_test = iris.data[100:150,:]
Y_test = (iris.target[100:150]).reshape(50,1)
测试集 = np.hstack((Y_test, X_test))

run_tune_process(tune_hyperparameters,trainingset,testset)

直接回复本邮件或在 Gi tHub上查看
.

顺便说一句
master 中的并行化开销——至少在 OS X 上——不存在
在 0.14...)

2014 年 2 月 25 日 21:52,乔尔·诺思曼[email protected] 写道

一般Windows中的多处理会遇到很多问题。 但是我
不知道为什么这应该与自定义指标相关联。 有
没有关于 0.14 中的 average=macro 选项表明它应该是
比默认平均值(加权)更有可能挂起。 在发展
头,这在我的 macbook 上在 11 秒内完成,在 0.14 版中在 7 秒内完成
(这是要研究的东西!)

你能在当前的开发版本中尝试这个,看看是否
它仍然是一个问题?

自2014年2月25日20时40分,adverley [email protected]写道:

感谢您的快速回复。

崩溃我实际上是指冻结。 它不再继续并且
在 python 进程中也没有更多的活动需要监控
windows的任务管理器。 进程仍然存在并消耗
恒定数量的 RAM,但不需要处理时间。

这是 scikit-learn 0.14 版,最后更新并使用 Enthought 运行
天篷。

我在平台“Windows-7-6.1.7601-SP1”上。

我将通过提供该问题的通用示例来更深入。
我认为这与 GridSearchCV 被放置在 for 循环中有关。 (到
不要浪费太多时间,你应该从
在代码底部调用的 run_tune_process() 方法
并在 for 循环中调用包含 GridSearchCV() 的方法)
代码:

导入 sklearn.metrics 作为指标
从 sklearn.grid_search 导入 GridSearchCV
将 numpy 导入为 np
导入操作系统
从 sklearn 导入数据集
从 sklearn 导入 svm 作为 sk

def tune_hyperparameters(trainingData, period):
allDataTrain = trainingData

# Define hyperparameters and construct a dictionary of them
amount_kernels = 2
kernels = ['rbf','linear']
gamma_range =   10. ** np.arange(-5, 5)
C_range =       10. ** np.arange(-5, 5)
tuned_parameters = [
                    {'kernel': ['rbf'],     'gamma': gamma_range , 'C': C_range},
                    {'kernel': ['linear'],  'C': C_range}
                   ]

print("Tuning hyper-parameters on period = " + str(period) + "\n")

clf = GridSearchCV( sk.SVC(),
                    tuned_parameters,
                    cv=5,
                    pre_dispatch='4*n_jobs',
                    n_jobs=2,
                    verbose = 1,
                    scoring=metrics.make_scorer(metrics.scorer.f1_score, average="macro")
                    )
clf.fit(allDataTrain[:,1:], allDataTrain[:,0:1].ravel())

# other code will output some data to files, graphs and will save the optimal model with joblib package


#   Eventually we will return the optimal model
return clf

def run_tune_process(hyperparam_tuning_method,trainingData,testData):
对于 np.arange(0,100,10) 中的期间:
clf = hyperparam_tuning_method(trainingData,period)

            y_real = testData[:,0:1].ravel()
            y_pred = clf.predict(testData[:,1:])

导入一些数据来玩

虹膜 = datasets.load_iris()
X_training = iris.data[0:100,:]
Y_training = (iris.target[0:100]).reshape(100,1)
训练集 = np.hstack((Y_training, X_training))

X_test = iris.data[100:150,:]
Y_test = (iris.target[100:150]).reshape(50,1)
测试集 = np.hstack((Y_test, X_test))

run_tune_process(tune_hyperparameters,trainingset,testset)

直接回复本邮件或在 Gi tHub上查看
.

这与自定义得分手无关。 这是 Windows 上 Python 多处理的一个众所周知的特性:你必须在if __name__ == '__main__'块中运行所有使用n_jobs=-1东西,否则你会死机/崩溃。 也许我们应该在显眼的地方记录这一点,例如在自述文件中?

你必须在 if name == 中运行所有使用 n_jobs= -1 的东西
' main ' 块,否则你会死机/崩溃。

好消息是,现在 joblib 给出了一个有意义的错误
关于此类崩溃的消息,而不是分叉炸弹。

@GaelVaroquaux当前的 scikit-learn 是否给出了错误信息? 如果是这样,恕我直言,这个问题可以被认为是固定的。

@GaelVaroquaux当前的 scikit-learn 是否给出了错误信息? 如果是这样,则
恕我直言,问题可以被认为是固定的。

应该可以。 唯一确定的方法是检查。 我在右边
现在,我无法启动 Windows VM 来执行此操作。

我不会为此在 Windows 上安装 C 编译器。 对不起,但我真的不做 Windows :)

我不会为此在 Windows 上安装 C 编译器。 对不起,但我
真的不要做 Windows :)

我有一个 Windows 虚拟机。 我可以检查。 这只是找到一个问题
几乎没有时间去做。

@larsmans ,你是完全正确的。 自定义计分器对象是我的错误,问题确实出在 Windows 上的多处理中。 我在 Linux 上尝试了相同的代码,它运行良好。

我没有收到任何错误消息,因为它没有崩溃,它只是停止做任何有意义的事情。

@adverley你能在你的 Windows 机器上试试 GitHub 上的最新版本吗?

由于缺乏反馈而关闭,这可能是一个已知问题,已在较新的 joblib 中修复。

不确定是否相关,似乎确实如此。

在 Windows 中,自定义计分器仍然冻结。 我在谷歌上遇到了这个线程 - 删除了记分员,并且网格搜索有效。

当它冻结时,它不会显示任何错误消息。 也产生了 3 个 python 进程(因为我设置了 n_jobs=3)。 但是,所有 python 进程的 CPU 利用率保持为 0。 我正在使用 IPython 笔记本。

你能分享一下得分手的代码吗? 似乎有点不太可能。

您的记分员是否在任何地方使用 joblib / n_jobs? 它不应该,这可能会导致问题(尽管我认为 joblib 应该检测到这一点)。

当然 - 这是完整的代码 - http://pastebin.com/yUE26SNs

评分器函数是“score_model”,它不使用 joblib。

这从命令提示符运行,但不是从 IPython Notebook 运行。 错误信息是 -
AttributeError: Can't get attribute 'score_model' on <module '__main__' (built-in)>;

然后 IPython 和所有生成的 python 实例变得空闲 - 静默 - 并且在我重新启动它之前不再响应任何 python 代码。

修复属性错误,然后它会起作用。
你在 IPython notebook 中进行 pylab 导入吗? 否则一切都应该是一样的。

好吧,我不知道是什么导致了 AttributeError ......虽然它很可能与 joblibs 有关,因为 _it 仅在 n_jobs 大于 1_ 时才会发生,使用n_jobs=1运行良好。

有关属性的错误会谈score_model从失踪__main__ ,不管是不是我有一个if __name__ == '__main__'在IPython的笔记本电脑或没有。

(我意识到错误行在上面粘贴不正确 - 我在上面的帖子中进行了编辑。)

我不使用pylab。

这是完整的扩展错误消息 - http://pastebin.com/23y5uHT2

嗯,这可能与 Windows 上的多处理问题有关。 也许@GaelVaroquaux@ogrisel可以提供帮助。
我不知道笔记本的__name__ == "__main__"
尝试不在笔记本中定义指标,而是在单独的文件中定义并导入它。 我认为这会解决它。
这与 GridSearchCV 并没有真正的关系,而是 Windows 多处理、IPython notebook 和 joblib 之间的一些有趣的交互。

伙计们...感谢您的线程。 无论如何,我之前应该检查过这个线程,浪费了我 5 个小时的时间。 试图在并行处理中运行。 非常感谢 :)
添加反馈:它仍然冻结。 当存在我自己的 make_Score 成本函数时,我遇到了同样的问题......我的系统开始冻结。 当我没有使用自定义成本函数时,我没有在并行处理中遇到这些冻结

将这 5 个小时转化为对项目有用的最好方法是为我们提供一个独立的示例来重现问题。

我在尝试在嵌套交叉验证和 n_jobs=-1 中使用自定义评分器的 Jupyter Notebook 中的 Windows 10 上遇到了同样的问题。 我收到了AttributeError: Can't get attribute 'custom_scorer' on <module '__main__' (built-in)>;消息。
正如@amueller 所建议的,导入自定义

我在 OSX 10.10.5 上遇到了完全相同的问题

同样在这里。
OSX 10.12.5

请给出一个可重现的代码片段。 我们很想深入了解这件事。 如果没有代码(包括数据)向我们展示问题,就很难理解。

只需在 python shell 中运行这些行

import numpy as np
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.preprocessing import RobustScaler
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_predict

np.random.seed(1234)
X = np.random.sample((1000, 100))
Y = np.random.sample((1000)) > 0.5
svc_pipeline = Pipeline([('pca', PCA(n_components=95)), ('svc', SVC())])
predictions = cross_val_predict(svc_pipeline, X, Y, cv=30, n_jobs=-1)
print classification_report(Y, predictions)

请注意,从管道中删除 PCA 步骤可以解决该问题。

更多信息:

Darwin-16.6.0-x86_64-i386-64bit
('Python', '2.7.13 (default, Apr 4 2017, 08:47:57) \n[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)]')
('NumPy', '1.12.1')
('SciPy', '0.19.1')
('Scikit-Learn', '0.18.2')

看到您不使用自定义计分器,我们是否应该假设这是一个
单独的问题?

2017 年 8 月 8 日下午 6:15,“boazsh”通知@github.com 写道:

只需在 python shell 中运行这些行

from sklearn.decomposition import PCAfrom sklearn.svm import SVCfrom sklearn.preprocessing import RobustScalerfrom sklearn.metrics import classification_reportfrom sklearn.pipeline import Pipelinefrom sklearn.model_selection import cross_val_predict

X = np.random.sample((1000, 100))
Y = np.random.sample((1000)) > 0.5
svc_pipeline = Pipeline([('pca', PCA(n_components=95)), ('svc', SVC())])
预测 = cross_val_predict(svc_pipeline, X, Y, cv=30, n_jobs=-1) 打印分类报告(Y, 预测)

请注意,从管道中删除 PCA 步骤可以解决该问题。

更多信息:

scikit-learn==0.18.2
scipy==0.19.1
numpy==1.12.1


您收到此消息是因为您发表了评论。
直接回复本邮件,在GitHub上查看
https://github.com/scikit-learn/scikit-learn/issues/2889#issuecomment-320885103
或静音线程
https://github.com/notifications/unsubscribe-auth/AAEz6-6Klhc67b5kZ17fFTxc8RfZQ_BWks5sWBkLgaJpZM4BkiD9
.

当我第一次遇到这个问题时,我使用的是自定义评分器,但在尝试尽可能简化示例代码时,我发现它不一定必须包含自定义评分器。 至少在我的机器上。 在我的情况下,导入记分员也没有帮助。 无论如何,症状看起来相似。 脚本永远挂起,CPU 利用率低。

@boazsh非常感谢这个片段,虽然它不是确定性的,你能编辑它并使用np.random.RandomState来确保每次运行时随机数总是相同的。

如果您使用例如https://github.com/scikit-learn/scikit-learn/issues/5115#issuecomment -187683383 中建议的 Python 3,还有一种解决方法。

我目前没有办法在 OSX 上测试这个,但我可能会在接下来的几天里尝试。

一些有用的信息(只需将缺少的内容添加到您之前的评论 https://github.com/scikit-learn/scikit-learn/issues/2889#issuecomment-320885103):

import platform; print(platform.platform())
import sys; print("Python", sys.version)
import numpy; print("NumPy", numpy.__version__)
import scipy; print("SciPy", scipy.__version__)
import sklearn; print("Scikit-Learn", sklearn.__version__)

另外,您是如何使用 pip、conda 以及 OSX 软件包管理器之一(brew 等...)安装 scikit-learn 的?

更新了片段(使用 np.random.seed)

Darwin-16.6.0-x86_64-i386-64bit
('Python', '2.7.13 (default, Apr 4 2017, 08:47:57) \n[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)]')
('NumPy', '1.12.1')
('SciPy', '0.19.1')
('Scikit-Learn', '0.18.2')

更新了片段(使用 np.random.seed)

非常感谢!

另外,您是如何使用 pip、conda 以及 OSX 软件包管理器之一(brew 等...)安装 scikit-learn 的?

你有没有回答这个,我找不到你的答案......

对不起,错过了 - pip。

FWIW,我运行该代码段没有问题:

进口平台; 打印(平台。平台())
Darwin-16.7.0-x86_64-i386-64bit
导入系统; 打印(“Python”,sys.version)
Python 2.7.12 |Continuum Analytics, Inc.| (默认,2016 年 7 月 2 日,17:43:17)
[GCC 4.2.1(基于 Apple Inc. build 5658)(LLVM build 2336.11.00)]
进口麻木; 打印(“NumPy”,numpy.__version__)
NumPy 1.13.1
进口scipy; 打印(“SciPy”,scipy.__version__)
SciPy 0.19.1
导入sklearn; 打印(“Scikit-Learn”,sklearn.__version__)
Scikit-Learn 0.18.2

你能不能把 verbose=10 也放在 cross_val_predict 中,这样我们也许可以
看看它在哪里打破?

2017 年 8 月 8 日 22:59,boazsh [email protected]写道:

对不起,错过了 - pip。


您收到此消息是因为您发表了评论。
直接回复本邮件,在GitHub上查看
https://github.com/scikit-learn/scikit-learn/issues/2889#issuecomment-320948362
或静音线程
https://github.com/notifications/unsubscribe-auth/AAEz67S64KIXUGvARGjvxBOw_4aCAdqhks5sWFu0gaJpZM4BkiD9
.

@jnothman我猜你的 conda 环境使用 MKL 而不是 Accelerate。 此冻结问题特定于 Accelerate 和 Python 多处理。 http://scikit-learn.org/stable/faq.html#why -do-i-sometime-get-a-crash-freeze-with-n-jobs-1-under-osx-or-linux 了解更多详情.

另一方面,pip 将使用 Accelerate 附带的轮子(在撰写本文时)。

避免此特定错误的解决方法(JOBLIB_START_METHOD 除外)是使用 MKL(例如通过 conda)或 OpenBLAS(例如通过 conda-forge 通道)。

什么都没有打印...

screen shot 2017-08-08 at 16 43 35

@jnothman我猜你的 conda 环境使用 MKL 而不是 Accelerate。

@jnothman如果您想重现该问题,IIRC 您可以使用 Accelerate 在 OSX 上创建一个环境,例如:

conda create -n test-env python=3 nomkl scikit-learn ipython

FWIW 我无法在我的 OS X VM 上重现该问题。 我试图尽可能地模仿@boazsh的版本:

Darwin-16.1.0-x86_64-i386-64bit
('Python', '2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) \n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]')
('NumPy', '1.12.1')
('SciPy', '0.19.1')
('Scikit-Learn', '0.18.2')

嗯,实际上我可以复制,但你的片段不是一个完整的复制器。 这是一个更新的片段:

import numpy as np
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.preprocessing import RobustScaler
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_predict

np.random.seed(1234)
X = np.random.sample((1000, 100))
Y = np.random.sample((1000)) > 0.5
svc_pipeline = Pipeline([('pca', PCA(n_components=95)), ('svc', SVC())])
PCA(n_components=95).fit(X, Y) # this line is required to reproduce the freeze
predictions = cross_val_predict(svc_pipeline, X, Y, cv=30, n_jobs=-1)
print(classification_report(Y, predictions))

无论如何,这是 Accelerate 和 Python 多处理的一个已知问题。 存在变通方法,并且已在之前的帖子中列出。 最简单的方法可能是使用 conda 并确保您使用 MKL 而不是 Accelerate。

从长远来看(可能是 scikit-learn 0.20),这个问题将被 joblib 的新 loky 后端普遍解决: https :

修复依赖于 scikit-learn 版本的多处理是 vendoring 问题的征兆。...

修复依赖于 scikit-learn 版本的多处理是 vendoring 问题的征兆。...

我最近阅读了以下内容,我觉得很有趣:
https://lwn.net/Articles/730630/rss

我有一个与 RandomizedSearchCV 类似的问题; 它无限期地挂起。 我使用的是 3 岁的 macbook pro、16GB 内存和核心 i7,我的 scikit-learn 版本是 0.19。

令人费解的部分是它在上周五工作!!! 星期一早上,我回去尝试跑步,结果就死机了。 我从之前的运行中知道大约需要 60 分钟才能完成,但我等待的时间比那要长得多,但没有任何反应,它只是挂起,没有错误消息,什么也没有,我的电脑发热并耗电,就像没有明天一样。 代码如下。 在阅读了这里的一些评论后,我尝试将 n_iter 更改为 2 和 n_jobs=1 并且有效。 所以它可能与n_jobs=-1有关。 尽管如此,这段代码上周五运行良好! 它只是讨厌星期一。 我的数据集大小小于 20k 个维度 < 100 的示例。

from sklearn.metrics import make_scorer
from sklearn.cross_validation import cross_val_score
from sklearn.grid_search import RandomizedSearchCV
import sklearn_crfsuite

crf = sklearn_crfsuite.CRF(
    algorithm='lbfgs', 
    max_iterations=100, 
    all_possible_transitions=True
)
params_space = {
    'c1': scipy.stats.expon(scale=0.5),
    'c2': scipy.stats.expon(scale=0.05),
}

f1_scorer = make_scorer(metrics.flat_f1_score, 
                        average='weighted', labels=labels)
rs = RandomizedSearchCV(crf, params_space, 
                        cv=3, 
                        verbose=1, 
                        n_jobs=-1, 
                        n_iter=50, 
                        scoring=f1_scorer)

rs.fit(X_train, y_train)  # THIS IS WHERE IT FREEZES

crf是什么? 只是为了消除可能性,您可以尝试使用
return_train_score=假?

这个@KaisJM的问题很可能是由于众所周知的多处理加速限制造成的,请参阅我们的常见问题解答。

你是如何安装 scikit-learn 的?

另外为了将来参考,您能否粘贴以下输出:

import platform; print(platform.platform())
import sys; print("Python", sys.version)
import numpy; print("NumPy", numpy.__version__)
import scipy; print("SciPy", scipy.__version__)
import sklearn; print("Scikit-Learn", sklearn.__version__)

这是上周五工作! 从那以后我什么也没做。 我认为 scikit learn 是 anaconda 的一部分,但我确实用 pip 升级(pip install --upgrade sklearn),但那是在我遇到这个问题之前..升级到 0.19 后我运行代码很好。

这是上面打印的输出:

Darwin-15.6.0-x86_64-i386-64bit
('Python', '2.7.12 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:43:17) \n[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)]')
('NumPy', '1.13.1')
('SciPy', '0.19.1')
('Scikit-Learn', '0.19.0')

@jnothman :我使用的是 sklearn.grid_search 中的 RandomizedSearchCV,它没有 return_train_score 参数。 我知道 sklearn.grid_search 已被弃用 .. 我会尝试 sklearn.model_selection 中的那个,但有人告诉我我会遇到完全相同的问题)。 用更多信息和代码更新了原始评论。

你能发布conda list | grep numpy的输出吗? 我会疯狂地猜测,通过使用 pip 更新 scikit-learn,您也使用 pip 更新了 numpy,并且您获得了使用 Accelerate 并具有上述限制的 numpy 轮子。

小小的忠告:

  • 发布一个完全独立的片段(为您的下一个问题)。 这意味着任何人都可以将其复制并粘贴到 IPython 会话中,并轻松尝试重现。 这将为您提供获得良好反馈的最佳机会。
  • 如果您使用的是 conda,请坚持使用 conda 来管理可通过 conda 获得的软件包。 仅在必要时使用 pip。
  • 如果您坚持要使用pip install --update ,我强烈建议您使用pip install --update --no-deps 。 否则,如果一个包依赖,比如 numpy,而你碰巧没有最新的 numpy,numpy 将使用 pip 升级,这是你不想要的。

哦,是的,顺便说一句,sklearn.grid_search 已被弃用,您可能想在不久的将来使用 sklearn.model_selection。

很好的建议,谢谢。 那么降级numpy的解决方法是什么? 你指的是什么限制? 上面的常见问题链接? 我确实读过它,但我不明白这些东西(我只是一个算法人:))。

conda list | grep numpy

麻木 1.12.0
麻木 1.12.0 py27_0
麻木 1.13.1
numpydoc 0.7.0

哇,安装了三个 numpy 我以前看到过两个,但从来没有看到过三个……无论如何,这似乎表明了我提到的问题,即您混合了 pip 和 conda,这对于给定的包来说是个坏主意。

pip uninstall -y # maybe a few times to make sure you have removed pip installed packages
conda install numpy -f

希望之后你会有一个使用 MKL 的 numpy。

如果我是你,我会仔细检查你对其他核心科学包没有同样的问题,例如 scipy 等......

我对某些包使用 pip 的原因是 conda 没有一些包,这实际上非常令人沮丧,因为我知道将 pip 与 conda 混合是一个坏主意。 下次发生这种情况时,我将使用 --no-deps 选项。

我应该提到的一件事是我在我工作的 python 环境中安装了 Spyder。但是,在安装 Spyder 后,我能够在 Spyder 和 Jupyter 中运行代码。

我确实卸载了 Spyder 和上面的 numpys,用 conda(将 scikit 更新到 0.19)重新安装了颠簸,但仍然出现相同的错误。 由于安装了Spyder,可能发生了一些事情,但是为什么它会工作一天然后突然停止?

好的,没有任何效果!! 我应该创建一个新环境(使用 conda)并在那里重新安装所有内容吗? 这会解决它还是让它变得更糟?

听起来值得一试!

创建了一个新的 env 并使用 conda 安装了所有内容,但仍然无限期地冻结。 每个包裹只有一份副本等。

n_jobs=1 有效,但当然需要永远(它也适用于以前的环境)。 n_jobs=-1 是无限期冻结。

conda list | grep numpy
numpy                     1.13.1           py27hd567e90_2


Darwin-15.6.0-x86_64-i386-64bit
('Python', '2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) \n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]')
('NumPy', '1.13.1')
('SciPy', '0.19.1')
('Scikit-Learn', '0.19.0')

那我就不知道了。 我们可以调查的唯一方法是您发布一个完全独立的片段,我们可以将其复制并粘贴到 IPython 会话中,看看我们是否可以重现问题。

将尝试创建一个重现问题的最小示例。 我需要这样做才能更有效地调试。

我阅读了您提到的有关“加速”的常见问题解答条目……它对我没有太大帮助。 我从中得到的是 fork() 后面没有 exec() 调用是不好的。 我已经对此进行了一些谷歌搜索,到目前为止还没有任何暗示解决方法。 您能否指出更多信息,有关问题所在的更多详细信息? 谢谢,

试试这个片段(取自 https://github.com/numpy/numpy/issues/4776):

import multiprocessing as mp

import numpy as np


def compute(n):
    print('Enter')
    np.dot(np.eye(n), np.eye(n))
    print('Exit')


print('\nWithout multiprocessing:')
compute(1000)

print('\nWith multiprocessing:')
workers = mp.Pool(1)
results = workers.map(compute, (1000, 1000))
  • 如果这冻结(即它没有在一秒内完成),则意味着您正在使用 Accelerate,并且冻结是 Python 多处理的一个已知限制。解决方法是不使用 Accelerate。 在 OSX 上,您可以使用默认使用 MKL 的 conda 来做到这一点。 您还可以使用 conda-forge 使用 OpenBLAS。
  • 如果它没有冻结,那么您没有使用 Accelerate,我们需要一个独立的代码段来进行调查。

将尝试以最少的代码重现。

Without multiprocessing:
Enter
Exit

With multiprocessing:
Enter
Exit
Enter
Exit

@GaelVaroquaux scikit-learn 不是应用程序,而是丰富生态系统中的库。 如果每个人都像我们一样做,一切都会崩溃。 这是一个非常明确的信号,我们需要改变。 并且有许多环境与该评论相反。

我在谷歌云计算引擎中使用了一个 ubuntu 虚拟实例(颠簸、辛辣、scikit 等不是最新的)。 代码运行良好。 然后我安装了 Gensim。 这将 numpy 和 scipy 更新为最新版本,并安装了它需要的其他一些东西(boto、bz2file 和 smart_open)。 之后代码冻结。 我希望这能提供有关导致这种冻结的原因的有用线索。

安装 Gensim 后
numpy (1.10.4) 更新为 numpy (1.13.3)
scipy (0.16.1) 更新到 scipy (0.19.1)

更多信息:
做了一些研究,我发现我的 /usr/lib/ 中缺少 libblas、liblapack 和 liblapack_atlas,而且我也没有看到目录 /usr/lib/atlas-base/。 我不知道他们是否在那里并且安装 gensim 删除了它们,因为它更新了 numpy 等,但这很可能是因为代码在安装 gensim 之前工作。 我根据高级 scikit安装说明使用sudo apt-get --yes install libatlas-base-dev和“_update-alternatives_”安装了它们,但没有帮助,代码仍然因 n_jobs=-1 而冻结。

我认为问题在于 numpy 正在使用 OpenBlas。 将它切换到 ATLAS,看看会发生什么。

>>> import numpy as np
>>> np.__config__.show()
lapack_opt_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
blas_opt_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
openblas_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
openblas_lapack_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
blas_mkl_info:
  NOT AVAILABLE

还是一样的问题。 以下运行正常,除非我插入 n_jobs=-1。

from sklearn.metrics import fbeta_score

def f2_score(y_true, y_pred):
    y_true, y_pred, = np.array(y_true), np.array(y_pred)
    return fbeta_score(y_true, y_pred, beta=2, average='binary')

clf_rf = RandomForestClassifier()
grid_search = GridSearchCV(clf_rf, param_grid=param_grid, scoring=make_scorer(f2_score), cv=5)
grid_search.fit(X_train, y_train)  

@paulaceccon是您使用 ATLAS 或 OpenBLAS 安装的 Numpy 和 Scipy 吗?

遵循您所做的@KaisJM 有点困难。 从维护者的角度来看,我们需要的是一个完全独立的 python 片段,看看我们是否可以重现。 如果我们可以复制,只有这样我们才能调查并尝试了解正在发生的事情。 如果这仅在您安装 gensim 时发生并且您设法始终如一地重现此行为,那么我们将需要完整说明如何创建有问题的 Python 环境与没有问题的 Python 环境。

这需要大量的时间和精力,我完全同意,但如果没有它,恐怕我们无法调查您面临的问题。

根据高级安装说明

@KaisJM顺便说一下,这个页面已经过时了,因为现在轮子在 Linux 上可用并且包含它们自己的 OpenBLAS。 如果您使用 pip 安装已发布的 scikit-learn,您将使用 OpenBLAS。

@lesteve你是说 Openblas 不再导致冻结?

@lesteve paula发布了一个也有同样问题的片段。 我可以看到它不是完整的代码,但我希望它提供一些线索。 我可以在这里制作“完整”片段并为您发布。 然而,很明显,“过时”——正如你所说的——说明页面可能不会过时。 最大的可能性是 OpenBLAS 导致了他们在该页面中谈论的费用。

这些说明已经过时了,相信我。 如果您详细阅读,它会说“但可以在 OpenBLAS 版本 0.2.8-4 之前冻结 joblib/multiprocessing”。 我检查了最近的一个 numpy 轮子,它包含 OpenBLAS 0.2.8.18。 他们所指的冻结是https://github.com/scikit-learn/scikit-learn/issues/2889#issuecomment -334155175 中的冻结,您似乎没有。

我可以看到它不是完整的代码,但我希望它提供一些线索

不是真的没有。 我们有用户报告似乎表明冻结仍然可能发生,我们没有设法重现 AFAIK。 这似乎表明,这个问题发生在一些非常具体的因素组合中。 除非遇到问题的人花一些时间并弄清楚如何以受控方式繁殖并且我们设法繁殖,否则我们无能为力。

我可以在这里制作“完整”片段并为您发布

那很好啊。 如果您可以检查这样的代码段是否仍然导致在单独的 conda 环境(或 virtualenv 取决于您使用的环境)中冻结,那就太好了。

@lesteve @paulaceccon :我采用了 Paula 的摘录代码并制作了一个完整的可运行代码片段。 只需将其粘贴到 Jupyter 单元中并运行它。 宝拉:我无法冻结这个片段。 请注意 n_jobs=-1 并且运行良好。 如果您可以查看并发布冻结的版本,那就太好了。 请注意,您可以在 grid_search 模块和 model_selection 模块之间切换,这两个模块对我来说都运行良好。

import platform; print(platform.platform())
import sys; print("Python", sys.version)
import numpy as np; print("NumPy", np.__version__)
import scipy; print("SciPy", scipy.__version__)
import sklearn; print("Scikit-Learn", sklearn.__version__)

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification

import scipy.stats
from sklearn.metrics import make_scorer
from sklearn.grid_search import RandomizedSearchCV
#from sklearn.model_selection import RandomizedSearchCV
#from sklearn.model_selection import GridSearchCV
from sklearn.metrics import fbeta_score

X, y = make_classification(n_samples=1000, n_features=4,
                           n_informative=2, n_redundant=0,
                           random_state=0, shuffle=False)

clf_rf = RandomForestClassifier(max_depth=2, random_state=0)

def f2_score(y_true, y_pred):
    y_true, y_pred, = np.array(y_true), np.array(y_pred)
    return fbeta_score(y_true, y_pred, beta=2, average='binary')

param_grid = {'max_depth':[2, 3, 4], 'random_state':[0, 3, 7, 17]}

grid_search = RandomizedSearchCV(clf_rf, param_grid, n_jobs=-1, scoring=make_scorer(f2_score), cv=5)

grid_search.fit(X, y)

@KaisJM我认为如果您从冻结脚本开始并设法简化并发布完全独立的冻结脚本,这会更有用。

@lesteve同意。 我创建了一个新的 python2 环境,就像在安装 Gensim 之前一样。 代码运行良好,n_jobs=-1 时不会冻结。 更重要的是,Numpy 正在使用 OpenBLAS,并且具有与显示冻结的环境(安装 Gensim 的环境)相同的配置。 所以似乎 openblas 不是这种冻结的原因。

bumpy.__config__.show()
lapack_opt_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
blas_opt_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
openblas_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
openblas_lapack_info:
    libraries = ['openblas']
    library_dirs = ['/usr/local/lib']
    define_macros = [('HAVE_CBLAS', None)]
    language = c
blas_mkl_info:
  NOT AVAILABLE

@KaisJM我在这里(windows)运行相同的代码片段并且它冻结了。

from sklearn.datasets import make_classification
X, y = make_classification()

from sklearn.ensemble import RandomForestClassifier
clf_rf_params = {
    'n_estimators': [400, 600, 800],
    'min_samples_leaf' : [5, 10, 15],
    'min_samples_split' : [10, 15, 20],
    'criterion': ['gini', 'entropy'],
    'class_weight': [{0: 0.51891309,  1: 13.71835531}]
}

import numpy as np
def ginic(actual, pred):
    actual = np.asarray(actual) # In case, someone passes Series or list
    n = len(actual)
    a_s = actual[np.argsort(pred)]
    a_c = a_s.cumsum()
    giniSum = a_c.sum() / a_s.sum() - (n + 1) / 2.0
    return giniSum / n

def gini_normalizedc(a, p):
    if p.ndim == 2:  # Required for sklearn wrapper
        p = p[:,1]   # If proba array contains proba for both 0 and 1 classes, just pick class 1
    return ginic(a, p) / ginic(a, a)

from sklearn import metrics
gini_sklearn = metrics.make_scorer(gini_normalizedc, True, True)

from sklearn.model_selection import GridSearchCV

clf_rf = RandomForestClassifier()
grid = GridSearchCV(clf_rf, clf_rf_params, scoring=gini_sklearn, cv=3, verbose=1, n_jobs=-1)
grid.fit(X, y)

print (grid.best_params_)

我知道这很尴尬,但在使用 _custom_ 指标运行时并没有冻结。

我有一个类似的问题。 我一直在运行相同的代码,只是想用新的月份数据更新模型,但它停止运行。 我相信 sklearn 同时更新到 0.19

在循环中运行 GridSearchCV 或 RandomizedSearchCV 并且 n_jobs > 1 将在 Jupiter 和 IntelliJ 中静默挂起:

for trial in tqdm(range(NUM_TRIALS)):
    ...
    gscv = GridSearchCV(estimator=estimator, param_grid=param_grid,
                          scoring=scoring, cv=cv, verbose=1, n_jobs=-1)
    gscv.fit(X_data, y_data)

    ...

遵循@lesteve 的建议并检查环境并删除与 pip 一起安装的 numpy:

Darwin-16.6.0-x86_64-i386-64bit
Python 3.6.1 |Anaconda 自定义 (x86_64)| (默认,2017 年 5 月 11 日,13:04:09)
[GCC 4.2.1 兼容 Apple LLVM 6.0 (clang-600.0.57)]
NumPy 1.13.1
SciPy 0.19.1
Scikit-Learn 0.19.0

$conda 列表 | grep numpy
gnumpy 0.2 点
麻木 1.13.1 py36_0
麻木 1.13.3 点
numpydoc 0.6.0 py36_0

$pip 卸载 numpy

$conda 列表 | grep numpy
gnumpy 0.2 点
麻木 1.13.1 py36_0
numpydoc 0.6.0 py36_0

$conda install numpy -f // 很可能不需要

$conda 列表 | grep numpy
gnumpy 0.2 点
麻木 1.13.1 py36_0
numpydoc 0.6.0 py36_0

解决了我的问题。

@paulaceccon您的问题与

https://stackoverflow.com/questions/36533134/cant-get-attribute-abc-on-module-main-from-abc-h-py
如果在声明要并行使用的函数之前声明池,则会引发此错误。 颠倒顺序,它就不会再抛出这个错误了。

以下将运行您的代码:

import multiprocessing

if __name__ == '__main__':
    multiprocessing.set_start_method('spawn')

    from external import *

    from sklearn.datasets import make_classification
    X, y = make_classification()

    from sklearn.ensemble import RandomForestClassifier
    clf_rf_params = {
        'n_estimators': [400, 600, 800],
        'min_samples_leaf' : [5, 10, 15],
        'min_samples_split' : [10, 15, 20],
        'criterion': ['gini', 'entropy'],
        'class_weight': [{0: 0.51891309,  1: 13.71835531}]
    }

    from sklearn.model_selection import GridSearchCV

    clf_rf = RandomForestClassifier()
    grid = GridSearchCV(clf_rf, clf_rf_params, scoring=gini_sklearn, cv=3, verbose=1, n_jobs=-1)
    grid.fit(X, y)

    print (grid.best_params_)

与外部.py

import numpy as np
def ginic(actual, pred):
    actual = np.asarray(actual) # In case, someone passes Series or list
    n = len(actual)
    a_s = actual[np.argsort(pred)]
    a_c = a_s.cumsum()
    giniSum = a_c.sum() / a_s.sum() - (n + 1) / 2.0
    return giniSum / n

def gini_normalizedc(a, p):
    if p.ndim == 2:  # Required for sklearn wrapper
        p = p[:,1]   # If proba array contains proba for both 0 and 1 classes, just pick class 1
    return ginic(a, p) / ginic(a, a)

from sklearn import metrics
gini_sklearn = metrics.make_scorer(gini_normalizedc, True, True)

结果在 8 个内核上运行

对 54 个候选者中的每一个进行 3 次拟合,总共 162 次拟合
{'class_weight':{0:0.51891309,1:13.71835531},'标准':'gini','min_samples_leaf':10,'min_samples_split':20,'n_estimators':400}

问题仍然存在,伙计们。 我正在使用自定义计分器,当我将 n_jobs 设置为任何内容时,它会一直持续下去。 当我根本不指定 n_jobs 时,它工作正常,但否则它会冻结。

你能提供一个独立的片段来重现这个问题吗? 请阅读https://stackoverflow.com/help/mcve了解更多详情。

使用相同的示例代码仍然面临这个问题。

Windows-10-10.0.15063-SP0
Python 3.6.4 |Anaconda 自定义(64 位)| (默认,2018 年 1 月 16 日,10:22:32)[MSC v.1900 64 位 (AMD64)]
NumPy 1.14.1
SciPy 1.0.0
Scikit-Learn 0.19.1

你能提供一个独立的片段来重现这个问题吗? 请阅读https://stackoverflow.com/help/mcve了解更多详情。

我怀疑这与 Windows 问题中的旧多处理相同。 请参阅我们的常见问题解答

我在 thomberg1 的https://github.com/scikit-learn/scikit-learn/issues/2889#issuecomment -337985212 中测试了代码。

操作系统:Windows 10 x64 10.0.16299.309
Python 包:WinPython-64bit-3.6.1
麻木 (1.14.2)
scikit-learn (0.19.1)
scipy (1.0.0)

它在 Jupyter Notebook 和命令行中运行良好。

嗨,我有同样的问题,所以我不想打开可能导致几乎相同线程的新问题。

-苹果系统
-蟒蛇
-scikit-learn 0.19.1
-scipy 1.0.1
-numpy 1.14.2

# MLP for Pima Indians Dataset with grid search via sklearn
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
import numpy

# Function to create model, required for KerasClassifier
def create_model(optimizer='rmsprop', init='glorot_uniform'):
  # create model
  model = Sequential()
  model.add(Dense(12, input_dim=8, kernel_initializer=init, activation='relu'))
  model.add(Dense(8, kernel_initializer=init, activation='relu'))
  model.add(Dense(1, kernel_initializer=init, activation='sigmoid'))
  # Compile model
  model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
  return model

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]


# create model
model = KerasClassifier(build_fn=create_model, verbose=0)
# grid search epochs, batch size and optimizer
optimizers = ['rmsprop', 'adam']
init = ['glorot_uniform', 'normal', 'uniform']
epochs = [50, 100, 150]
batches = [5, 10, 20]
param_grid = dict(optimizer=optimizers, epochs=epochs, batch_size=batches, init=init)
grid = GridSearchCV(estimator=model, param_grid=param_grid)
grid_result = grid.fit(X, Y)
# summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
  print("%f (%f) with: %r" % (mean, stdev, param))

代码来自教程: https :
我尝试将 n_jobs 参数更改为 1, -1,但这些都不起作用。 任何提示?

如果我添加多处理导入和 if 语句,它会运行,如下所示 - 我不使用 keras,所以我没有更多的洞察力

import multiprocessing

if __name__ == '__main__':

    # MLP for Pima Indians Dataset with grid search via sklearn
    from keras.models import Sequential
    from keras.layers import Dense
    from keras.wrappers.scikit_learn import KerasClassifier
    from sklearn.model_selection import GridSearchCV
    import numpy

    # Function to create model, required for KerasClassifier
    def create_model(optimizer='rmsprop', init='glorot_uniform'):
      # create model
      model = Sequential()
      model.add(Dense(12, input_dim=8, kernel_initializer=init, activation='relu'))
      model.add(Dense(8, kernel_initializer=init, activation='relu'))
      model.add(Dense(1, kernel_initializer=init, activation='sigmoid'))
      # Compile model
      model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
      return model

    # fix random seed for reproducibility
    seed = 7
    numpy.random.seed(seed)
    # load pima indians dataset
    dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
    # split into input (X) and output (Y) variables
    X = dataset[:,0:8]
    Y = dataset[:,8]


    # create model
    model = KerasClassifier(build_fn=create_model, verbose=0)
    # grid search epochs, batch size and optimizer
    optimizers = ['rmsprop', 'adam']
    init = ['glorot_uniform', 'normal', 'uniform']
    epochs = [5]
    batches = [5, 10, 20]
    param_grid = dict(optimizer=optimizers, epochs=epochs, batch_size=batches, init=init)
    grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=12, verbose=1)
    grid_result = grid.fit(X, Y)
    # summarize results
    print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
    means = grid_result.cv_results_['mean_test_score']
    stds = grid_result.cv_results_['std_test_score']
    params = grid_result.cv_results_['params']
    for mean, stdev, param in zip(means, stds, params):
      print("%f (%f) with: %r" % (mean, stdev, param))

对 18 个候选中的每一个进行 3 次拟合,总共 54 次拟合

最佳:0.675781 使用 {'batch_size': 5, 'epochs': 5, 'init': 'glorot_uniform', 'optimizer': 'adam'}
0.621094 (0.036225) 与:{'batch_size': 5, 'epochs': 5, 'init': 'glorot_uniform', 'optimizer': 'rmsprop'}
0.675781(0.006379)与:{'batch_size':5,'epochs':5,'init':'glorot_uniform','优化器':'adam'}
...
0.651042(0.025780):{'batch_size':20,'epochs':5,'init':'uniform','optimizer':'adam'}


如果需要,版本信息
sys 3.6.4 |Anaconda 自定义(64 位)| (默认,2018 年 1 月 16 日,12:04:33)
[GCC 4.2.1 兼容 Clang 4.0.1 (tags/RELEASE_401/final)]
麻木 1.14.2
熊猫 0.22.0
sklearn 0.19.1
火炬 0.4.0a0+9692519
IPython 6.2.1
keras 2.1.5

编译器:GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)
系统:达尔文
版本:17.5.0
机器:x86_64
处理器:i386
CPU核心:24
解释器:64位

谢谢@thomberg1 ,但添加

import multiprocessing
if __name__ == '__main__':

没有帮助。 问题还是一样

GridsearchCV使用自定义评分函数时,我的机器上存在同样的问题。
蟒蛇 3.6.4,
scikit-learn 0.19.1,
视窗 10.,
CPU内核:24

@byrony你能提供代码来重现吗? 你用过if __name__ == "__main__"吗?

当使用n_jobs=-1n_jobs=8作为GridsearchCV参数但使用默认评分器参数时,我在我的机器上多次遇到类似的问题。

  • 蟒蛇 3.6.5,
  • scikit-learn 0.19.1,
  • 拱形Linux,
  • CPU核心数:8。

这是我使用的代码:

from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.utils import shuffle
from sklearn.neural_network import MLPClassifier
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


def main():

    df = pd.read_csv('../csvs/my_data.csv', nrows=4000000)    

    X = np.array(list(map(lambda a: np.fromstring(a[1:-1] , sep=','), df['X'])))
    y = np.array(list(map(lambda a: np.fromstring(a[1:-1] , sep=','), df['y'])))

    scalerX = MinMaxScaler()
    scalerY = MinMaxScaler()
    X = scalerX.fit_transform(X)
    y = scalerY.fit_transform(y)

    grid_params = {
        'beta_1': [ .1, .2, .3, .4, .5, .6, .7, .8, .9 ],
        'activation': ['identity', 'logistic', 'tanh', 'relu'],
        'learning_rate_init': [0.01, 0.001, 0.0001]
    }

    estimator = MLPClassifier(random_state=1, 
                              max_iter=1000, 
                              verbose=10,
                              early_stopping=True)

    gs = GridSearchCV(estimator, 
                      grid_params, 
                      cv=5,
                      verbose=10, 
                      return_train_score=True,
                      n_jobs=8)

    X, y = shuffle(X, y, random_state=0)

    y = y.astype(np.int16)    

    gs.fit(X, y.ravel())

    print("GridSearchCV Report \n\n")
    print("best_estimator_ {}".format(gs.best_estimator_))
    print("best_score_ {}".format(gs.best_score_))
    print("best_params_ {}".format(gs.best_params_))
    print("best_index_ {}".format(gs.best_index_))
    print("scorer_ {}".format(gs.scorer_))
    print("n_splits_ {}".format(gs.n_splits_))

    print("Exporting")
    results = pd.DataFrame(data=gs.cv_results_)
    results.to_csv('../csvs/gs_results.csv')


if __name__ == '__main__':
    main()

我知道这是一个大数据集,所以我预计需要一些时间才能获得结果,但是在运行 2 天后,它就停止工作了(脚本继续执行,但不使用除 RAM 和交换之外的任何资源)。

captura de pantalla de 2018-05-25 17-53-11

captura de pantalla de 2018-05-25 17-54-59

提前致谢!

@amueller我没有使用if __name__ == "__main__" 。 下面是我的代码,它只适用于n_jobs=1

def neg_mape(true, pred):
    true, pred = np.array(true)+0.01, np.array(pred)
    return -1*np.mean(np.absolute((true - pred)/true))

xgb_test1 = XGBRegressor(
    #learning_rate =0.1,
    n_estimators=150,
    max_depth=3,
    min_child_weight=1,
    gamma=0,
    subsample=0.8,
    colsample_bytree=0.8,
    objective= 'reg:linear',
    nthread=4,
    scale_pos_weight=1,
    seed=123,
)

param_test1 = {
    'learning_rate':[0.01, 0.05, 0.1, 0.2, 0.3],
}

gsearch1 = GridSearchCV(estimator = xgb_test1, param_grid = param_test1, scoring=neg_mape, n_jobs=4, cv = 5)

您正在使用 XGBoost。 我不知道他们在内部做什么,很可能这就是问题所在。 您可以尝试看看添加if __name__帮助吗?
否则,我认为目前还没有解决办法。

@Pazitos10你能用合成数据和/或更小的数据重现吗? 没有您的数据,我无法重现,最好在更短的时间内重现。

@amueller好的,我会用 500k 行再次运行它并发布结果。 谢谢!

@amueller ,运行 50k 行的脚本按预期工作。 脚本正确结束,显示结果如下(抱歉,我的意思是 50k 不是 500k):

captura de pantalla de 2018-05-26 13-09-00

captura de pantalla de 2018-05-26 13-09-51

问题是我不知道这些结果是否适合我的整个数据集。 有什么建议吗?

好像你的内存用完了。 也许尝试使用 Keras,它可能是大规模神经网络的更好解决方案。

@amueller哦,好的。 我会尝试改用 Keras。 再次感谢你!

这与自定义得分手无关。 这是 Windows 上 Python 多处理的一个众所周知的特性:你必须在if __name__ == '__main__'块中运行所有使用n_jobs=-1东西,否则你会死机/崩溃。 也许我们应该在显眼的地方记录这一点,例如在自述文件中?

这可能是 scikit 的一个想法,在 Windows 的情况下改变功能
并使用队列将任务提供给一组工作进程并收集结果
如此处所述: https :
对于 3.6 在这里: https :

@PGTBoos这已在 scikit-learn 0.20.0 中修复

此页面是否有帮助?
0 / 5 - 0 等级