python-2.7 - 如何绘制多类分类器中是否发生过拟合

标签 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()

但是我收到以下值错误:
---------------------------------------------------------------------------
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) 

我知道如果我使用 GradientBoostingRegressor,这段代码可以正常工作,但我不知道如何让它与多类分类器(如 GradientBoostingClassifier)一起工作。谢谢你的帮助。

最佳答案

好像loss_需要一个形状数组 n_samples, k , 而 staged_predict返回一个形状数组 [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'])

请注意我第二次调用 loss_我通过了火车组。输出看起来像我所期望的:

enter image description here

关于python-2.7 - 如何绘制多类分类器中是否发生过拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23499423/

相关文章:

python - 寻找逻辑回归的系数

scikit-learn - XGBoost 从 booster 对象中获取分类器对象?

python - sklearn MultinomialNB 仅预测类先验

python - Python 函数定义中的列表构建

Python BeautifulSoup 提取 PHP 链接

python - macOS Sierra 上的 nltk

python - 从 Python 列表中弹出所有项目

Python:用有序的字符串写一个空字典

python - sklearn.metrics. precision_recall_fscore_support输出的解释

Python:比较不同维度的两个不同tfidf矩阵中的项目