Python RandomForest sk-learn:卡住了几个小时,发生了什么?

时间:2017-02-04 05:20:37

标签: python machine-learning scikit-learn curve-fitting

我有一个很大的输入向量。目前,它已经停留在运行calibrated_clf.fit(x_train, y_train)几个小时。我不知道该程序是死了还是什么。如何在calibrated_clf.fit(x_train, y_train)函数调用中运行时打印出某种进度?

clf = ensemble.RandomForestClassifier(criterion = 'entropy', n_estimators = 350, max_features = 200,n_jobs=-1)
calibrated_clf = CalibratedClassifierCV(clf, method='isotonic')
print "Here 1"
calibrated_clf.fit(x_train, y_train)
print "Here 2"

x_train是大小(51733,250)的向量。 我在坚持"在这里1"在打印输出上几个小时。

3 个答案:

答案 0 :(得分:2)

您可以简单地将详细信息设置为高于0的值。

from sklearn.externals import joblib
help(joblib.parallel)
  

详细:int,可选               详细级别:如果非零,则进度消息为               打印。超过50,输出被发送到stdout。               消息的频率随着详细程度而增加。               如果超过10,则报告所有迭代。

RandomForestClassifier使用parallel库中的joblib函数。

import numpy
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier

n = 1000

X, y = make_blobs(n_samples=n)
X_train, y_train = X[0:n // 2], y[0:n // 2]
X_valid, y_valid = X[n // 2:], y[n // 2:]

clf = RandomForestClassifier(n_estimators=350, verbose=100)
clf.fit(X_train, y_train)

<强>输出

building tree 1 of 350
[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.0s remaining:    0.0s
building tree 2 of 350
[Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.0s remaining:    0.0s
building tree 3 of 350
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.0s remaining:    0.0s
building tree 4 of 350
[Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    0.0s remaining:    0.0s
building tree 5 of 350

[...]

building tree 100 of 350
building tree 101 of 350
building tree 102 of 350
building tree 103 of 350
building tree 104 of 350
[...]
building tree 350 of 350
[Parallel(n_jobs=1)]: Done 350 out of 350 | elapsed:    1.6s finished

答案 1 :(得分:1)

显然,这可以通过在CalibratedClassifierCV源代码中插入打印来完成,该源代码作为sklearn的一部分提供,但它需要一个人非常熟悉算法和实现。

因为您不需要知道拟合的确切进度,所以解决方法是子类化ndarray并重载索引操作符 - 我假设您传入的x_train和y_train是ndarrays。因此,每次CalibratedClassifierCV fit方法迭代并尝试访问数据时,它都会调用您的自定义代码。例如:

import numpy as np

class array_plus(np.ndarray):
    def __getitem__(self, idx):
        print("array_plus indexing operator called")
        return np.ndarray.__getitem__(self, idx)

在将这些数据传递给fit方法之前,您可以“转换”(正式地,Python不支持“转换”)它们进入您的新类:

new_x_train = array_plus(x_train)
new_y_train = array_plus(y_train)

calibrated_clf.fit(new_x_train, new_y_train)

你甚至可以在子类中放置一个计数器来大致了解你的位置。

答案 2 :(得分:1)

如果问题来自您使用的树的数量,这里有一个小技巧可以克服它:

您可以将参数warm_start更改为True。请执行以下操作:

# Start with 10 estimators
growing_rf = RandomForestClassifier(n_estimators=10, n_jobs=-1,  
                                    warm_start=True, random_state=42)
for i in range(35): # Let's suppose you want to add 340 more trees, to add up to 350
    growing_rf.fit(X_train, y_train)
    growing_rf.n_estimators += 10

最后,您可以使用包含350树的随机森林预测您的测试数据。

growing_rf.predict_proba(X_test)))
相关问题