sklearn模型调优(判断是否过过拟合及选择参数)

sklearn模型调优(判断是否过过拟合及选择参数)

这篇博客主要介绍两个方面的东西,其实就是两个函数:

1. learning_curve():这个函数主要是用来判断(可视化)模型是否过拟合的,关于过拟合,就不多说了,具体可以看以前的博客:模型选择和改进
2. validation_curve():这个函数主要是用来查看在参数不同的取值下模型的性能
下面通过代码例子来看下这两个函数:
一、learning_curve()
这个函数的官方API为:官方API。部分参数含义为:

参数含义
estimator训练的模型
X数据集样本(不包括label)
y样本label
train_sizes用于产生learning_curve的样本数量,比如[0.1,0.25,0.5,0.75,1]就是当样本是总样本数量的10%,25%,…100%时产生learning_curve,其实就是对应折线图上那几个点的横坐标(见下图),因为样本数量很多,因此都设置比例,当然你也可以直接设置样本数量,默认是np.linspace(0.1, 1.0, 5)。
cv交叉验证的折数
scoring模型性能的评价指标,如(‘accuracy’、‘f1’、”mean_squared_error”等)


返回值:
返回值
其中:n_ticks表示设置的参数个数,n_cv_folds表示折数,比如下面的代码中,进行调参的参数是train_size,我train_size设置了6个数(0.1,0.2,0.4,…)因此n_ticks=6,而cv设置了10,因此n_cv_folds=10,这样输出的train_score,test_score就是一个6*10的矩阵,行表示你要测试的参数,列表示cv(关于k折交叉验证,这里科普下,k折交叉验证,把数据集划分成k份,每次把其中k-1份作为训练集,1分作为测试集。重复k次),所以当cv=10的时候,每一行会有10个结果。

直接看个代码吧:

from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import learning_curve
import numpy as np
import matplotlib.pyplot as plt

(X,y) = datasets.load_digits(return_X_y=True)
# print(X[:2,:])

train_sizes,train_score,test_score = learning_curve(RandomForestClassifier(),X,y,train_sizes=[0.1,0.2,0.4,0.6,0.8,1],cv=10,scoring='accuracy')
train_error =  1- np.mean(train_score,axis=1)
test_error = 1- np.mean(test_score,axis=1)
plt.plot(train_sizes,train_error,'o-',color = 'r',label = 'training')
plt.plot(train_sizes,test_error,'o-',color = 'g',label = 'testing')
plt.legend(loc='best')
plt.xlabel('traing examples')
plt.ylabel('error')
plt.show()

运行结果:

运行结果

二、validation_curve()
官方的API为:validation_curve(),这个函数的部分重要的参数为:

参数含义
param_name要改变的参数的名字,如果当model为SVC时,改变gamma的值,求最好的那个gamma值
param_range给定的参数范围


这个函数只有两个返回值:
这里写图片描述

代码示例:

from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import validation_curve
import numpy as np
import matplotlib.pyplot as plt

(X,y) = datasets.load_digits(return_X_y=True)
# print(X[:2,:])
param_range = [10,20,40,80,160,250]
train_score,test_score = validation_curve(RandomForestClassifier(),X,y,param_name='n_estimators',param_range=param_range,cv=10,scoring='accuracy')
train_score =  np.mean(train_score,axis=1)
test_score = np.mean(test_score,axis=1)
plt.plot(param_range,train_score,'o-',color = 'r',label = 'training')
plt.plot(param_range,test_score,'o-',color = 'g',label = 'testing')
plt.legend(loc='best')
plt.xlabel('number of tree')
plt.ylabel('accuracy')
plt.show()


运行结果:

这里写图片描述


        可以看到当树的数量为80-90左右的时候,model的性能最好,因此我们可以把n_estimators设置85,这样model的性能会相对好些。

        以上就是learning_curve()和validation_curve()的简介。



  • 23
    点赞
  • 94
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
随机森林分类模型调优的重要参数包括以下几个: 1. n_estimators:决策树的数量。增加决策树的数量可以提高模型的性能,但会增加计算成本。通常情况下,增加决策树的数量可以提高模型的准确性,但是在一定数量后,模型的性能会趋于稳定。 2. max_features:每个决策树使用的特征数量。较小的max_features值可以减少模型的方差,但可能会增加模型的偏差。较大的max_features值可以增加模型的多样性,但可能会导致决策树之间的相关性增加。 3. max_depth:决策树的最大深度。增加max_depth可以增加模型的复杂度,但也可能导致过拟合。较小的max_depth值可以减少模型的复杂度,但可能会导致欠拟合。 4. min_samples_split:拆分内部节点所需的最小样本数。较小的min_samples_split值可以增加模型的复杂度,但也可能导致过拟合。较大的min_samples_split值可以减少模型的复杂度,但可能会导致欠拟合。 5. min_samples_leaf:叶节点所需的最小样本数。较小的min_samples_leaf值可以增加模型的复杂度,但也可能导致过拟合。较大的min_samples_leaf值可以减少模型的复杂度,但可能会导致欠拟合。 6. criterion:用于衡量节点纯度的指标。常见的指标有基尼系数(gini)和信息增益(entropy)。不同的指标可能会导致不同的模型性能。 7. class_weight:用于处理类别不平衡问题的权重。可以通过设置不同类别的权重来平衡模型对不同类别的预测能力。 8. random_state:随机种子。设置相同的随机种子可以确保每次运行模型时得到相同的结果。 下面是一个示例代码,演示了如何使用GridSearchCV进行随机森林分类模型参数调优: ```python from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV # 定义参数网格 param_grid = { 'n_estimators': [100, 200, 300], 'max_features': ['auto', 'sqrt'], 'max_depth': [None, 5, 10], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4], 'criterion': ['gini', 'entropy'], 'class_weight': [None, 'balanced'] } # 创建随机森林分类器 rf = RandomForestClassifier() # 使用GridSearchCV进行参数调优 grid_search = GridSearchCV(estimator=rf, param_grid=param_grid, cv=5) grid_search.fit(X, y) # 输出最佳参数和最佳得分 print("Best parameters: ", grid_search.best_params_) print("Best score: ", grid_search.best_score_) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值