Skip to main content
 首页 » 编程设计

python之RandomForestClassifier 性能不佳

2025年04月02日22lidabo

我编写了以下 Python 代码,用于在 UCI ML 存储库的 Forest CoverType 数据集上运行 RandomForestClassifier(使用默认参数设置)。然而,结果很差,准确率在 60% 左右,而这种技术应该能够达到 90% 以上(例如使用 Weka)。我已经尝试将 n_estimators 增加到 100,但这并没有带来太大的改善。

有什么想法可以让我在 scikit-learn 中使用这种技术获得更好的结果,或者性能不佳的原因是什么?

    from sklearn.datasets import fetch_covtype 
    from sklearn.ensemble import RandomForestClassifier 
    from sklearn import cross_validation 
 
 
    covtype = fetch_covtype() 
    clf = RandomForestClassifier() 
    scores = cross_validation.cross_val_score(clf, covtype.data, covtype.target) 
    print scores 
 
[ 0.5483831   0.58210057  0.61055001]  

请您参考如下方法:

我设法通过使用 GridSearchCV 对您的模型进行了很好的改进

from sklearn.datasets import fetch_covtype 
from sklearn.ensemble import RandomForestClassifier 
from sklearn import cross_validation 
from sklearn import grid_search 
import numpy as np 
 
 
covtype = fetch_covtype() 
clf = RandomForestClassifier() 
 
X_train, X_test, y_train, y_test = cross_validation.train_test_split(covtype.data, 
                                                                     covtype.target, 
                                                                     test_size=0.33, 
                                                                     random_state=42) 
params = {'n_estimators':[30, 50, 100], 
          'max_features':['sqrt', 'log2', 10]} 
gsv = grid_search.GridSearchCV(clf, params, cv=3, 
                               n_jobs=-1, scoring='f1') 
gsv.fit(X_train, y_train) 
 
print metrics.classification_report(y_train, gsv.best_estimator_.predict(X_train)) 
 
print metrics.classification_report(y_test, gsv.best_estimator_.predict(X_test)) 

输出:

         precision    recall  f1-score   support 
 
          1       1.00      1.00      1.00    141862 
          2       1.00      1.00      1.00    189778 
          3       1.00      1.00      1.00     24058 
          4       1.00      1.00      1.00      1872 
          5       1.00      1.00      1.00      6268 
          6       1.00      1.00      1.00     11605 
          7       1.00      1.00      1.00     13835 
 
avg / total       1.00      1.00      1.00    389278 
 
             precision    recall  f1-score   support 
 
          1       0.97      0.95      0.96     69978 
          2       0.95      0.97      0.96     93523 
          3       0.95      0.96      0.95     11696 
          4       0.92      0.86      0.89       875 
          5       0.94      0.78      0.86      3225 
          6       0.94      0.90      0.92      5762 
          7       0.97      0.95      0.96      6675 
 
avg / total       0.96      0.96      0.96    191734 

这与 Kaggle leaderboard 上的分数相差不远。 (请注意,尽管 Kaggle 竞赛使用了更具挑战性的数据拆分!)

如果您想看到更多改进,那么您将不得不考虑不均匀的类别以及如何最好地选择您的训练数据。

注意

为了节省时间,我使用了比通常情况下更少的估计量,但是该模型在训练集上表现良好,因此您可能不必考虑这一点。

我使用了少量的 max_features,因为这通常会减少模型训练中的偏差。尽管这并不总是正确的。

我使用 f1 评分,因为我不太了解数据集,而 f1 在分类问题上往往效果很好。