如何绘制过度拟合是否发生在多类分类器中

use*_*302 5 python-2.7 scikit-learn

我想监测多类梯度增强分类器训练过程中的损失,以此来了解是否发生过度拟合.这是我的代码:

%matplotlib inline
import numpy as np
#import matplotlib.pyplot as plt
import matplotlib.pylab as plt
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor

iris = datasets.load_iris()
X, y = iris.data, iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)

n_est = 100
clf = GradientBoostingClassifier(n_estimators=n_est, max_depth=3, random_state=2)
clf.fit(X_train, y_train)


test_score = np.empty(len(clf.estimators_))
for i, pred in enumerate(clf.staged_predict(X_test)):
    test_score[i] = clf.loss_(y_test, pred)
plt.plot(np.arange(n_est) + 1, test_score, label='Test')
plt.plot(np.arange(n_est) + 1, clf.train_score_, label='Train')
plt.show()
Run Code Online (Sandbox Code Playgroud)

但是我收到以下值错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-27194f883893> in <module>()
     22 test_score = np.empty(len(clf.estimators_))
     23 for i, pred in enumerate(clf.staged_predict(X_test)):
---> 24     test_score[i] = clf.loss_(y_test, pred)
     25 plt.plot(np.arange(n_est) + 1, test_score, label='Test')
     26 plt.plot(np.arange(n_est) + 1, clf.train_score_, label='Train')

C:\Documents and Settings\Philippe\Anaconda\lib\site-packages\sklearn\ensemble\gradient_boosting.pyc in __call__(self, y, pred)
    396             Y[:, k] = y == k
    397 
--> 398         return np.sum(-1 * (Y * pred).sum(axis=1) +
    399                       logsumexp(pred, axis=1))
    400 

ValueError: operands could not be broadcast together with shapes (45,3) (45) 
Run Code Online (Sandbox Code Playgroud)

我知道如果我使用GradientBoostingRegressor这个代码工作正常,但我无法弄清楚如何使它与多类分类器(如GradientBoostingClassifier)一起工作.谢谢你的帮助.

mba*_*rov 8

似乎loss_需要一个 shape 数组n_samples, k,而staged_predict返回一个 shape 数组[n_samples](根据文档)。您可能希望将staged_predict_proba或的结果staged_decision_function传入loss_.

我认为您可以像这样测量训练集和测试集的损失:

for i, pred in enumerate(clf.staged_decision_function(X_test)):
    test_score[i] = clf.loss_(y_test, pred)

for i, pred in enumerate(clf.staged_decision_function(X_train)):
    train_score[i] = clf.loss_(y_train, pred)

plot(test_score)
plot(train_score)
legend(['test score', 'train score'])
Run Code Online (Sandbox Code Playgroud)

注意我第二次打电话时loss_我在火车上路过。输出看起来像我所期望的:

在此处输入图片说明