【机器学习 模型调参】GridSearchCV模型调参利器

导入模块sklearn.model_selection

from sklearn.model_selection import GridSearchCV

GridSearchCV 称为网格搜索交叉验证调参,它通过遍历传入的参数的所有排列组合,通过交叉验证的方式,返回所有参数组合下的评价指标得分,GridSearchCV 函数的参数详细解释如下:

class sklearn.model_selection.GridSearchCV(estimator,param_grid,scoring = None,n_jobs = None,iid ='deprecated',refit = True,cv = None,verbose = 0,pre_dispatch ='2 * n_jobs',error_score = nan,return_train_score = False )


GridSearchCV官方说明

参数:

estimator:scikit-learn 库里的算法模型;
param_grid:需要搜索调参的参数字典;
scoring:评价指标,可以是 auc, rmse,logloss等;
n_jobs:并行计算线程个数,可以设置为 -1,这样可以充分使用机器的所有处理器,并行数量越多,有利于缩短调参时间;
iid:如果设置为True,则默认假设数据在每折中具有相同地分布,并且最小化的损失是每个样本的总损失,而不是每折的平均损失。简单点说,就是如果你可以确定 cv 中每折数据分布一致就设置为 True,否则设置为 False;
cv:交叉验证的折数,默认为3折;

常用属性:
cv_results_:用来输出cv结果的,可以是字典形式也可以是numpy形式,还可以转换成DataFrame格式
best_estimator_:通过搜索参数得到的最好的估计器,当参数refit=False时该对象不可用
best_score_:float类型,输出最好的成绩
best_params_:通过网格搜索得到的score最好对应的参数
best_index_:对应于最佳候选参数设置的索引(cv_results_数组)。cv_results _ [‘params’] [search.best_index_]中的dict给出了最佳模型的参数设置,给出了最高的平均分数(search.best_score_)。
scorer_:评分函数
n_splits_:交叉验证的数量
refit_time_:refit所用的时间,当参数refit=False时该对象不可用


常用函数:

decision_function(X):返回决策函数值(比如svm中的决策距离)
fit(X,y=None,groups=None,fit_params):在数据集上运行所有的参数组合
get_params(deep=True):返回估计器的参数
inverse_transform(Xt):Call inverse_transform on the estimator with the best found params.
predict(X):返回预测结果值(0/1predict_log_proba(X): Call predict_log_proba on the estimator with the best found parameters.
predict_proba(X):返回每个类别的概率值(有几类就返回几列值)
score(X, y=None):返回函数
set_params(**params):Set the parameters of this estimator.
transform(X):在X上使用训练好的参数

属性grid_scores_已经被删除,改用:

means = grid_search.cv_results_['mean_test_score']
params = grid_search.cv_results_['params']

GBDT例子:


# -*- coding: utf-8 -*-

# 载入包
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error,r2_score,mean_absolute_error
import warnings
warnings.filterwarnings('ignore')
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV
import numpy as np


# 读取数据
data_path=r'D:\data.txt'
# 导入数据
data=pd.read_table(data_path)

# 筛选自变量
X=data.iloc[:,1:]
# 筛选因变量
y=data.iloc[:,0]
# 提取特征名
feature_names=list(X.columns)
# 切分数据,划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=33)


param_gbdt3 = {'learning_rate':[0.06,0.07,0.08,0.09,0.1],
               'n_estimators':[100,150,200,250,300]}


gbdt_search2 = GridSearchCV(estimator=GradientBoostingRegressor(loss='ls',max_depth=9,max_features=9,
                                                             subsample=0.8,min_samples_leaf=4, min_samples_split=6),n_jobs=-1,
                            param_grid=param_gbdt3,scoring='neg_mean_squared_error',iid=False,cv=5)
gbdt_search2.fit(X_train,y_train)
print(gbdt_search2.best_params_)

2、xgboost例子:

# -*- coding: utf-8 -*-

# 载入包
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error,r2_score,mean_absolute_error
import warnings
warnings.filterwarnings('ignore')
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV
import numpy as np


# 读取数据
data_path=r'D:\data.txt'
# 导入数据
data=pd.read_table(data_path)

# 筛选自变量
X=data.iloc[:,1:]
# 筛选因变量
y=data.iloc[:,0]
# 提取特征名
feature_names=list(X.columns)
# 切分数据,划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=33)


cv_params  = {'n_estimators': [280,290,300,320,330]}


other_params = {
    'learning_rate':0.1,
    'max_depth':8,
    'min_child_weight':1,
    'gamma':0.05,
    'subsample':0.8,
    'colsample_bytree':0.8,
    'reg_alpha':0,
    'reg_lambda':1
}
xgb_model_ = XGBRegressor(**other_params)
xgb_search = GridSearchCV(xgb_model_,
                          param_grid=cv_params ,
                          scoring='r2',
                          iid=False,n_jobs=-1,
                          cv=5)

xgb_search.fit(X_train, y_train)


means = xgb_search.cv_results_['mean_test_score']
params = xgb_search.cv_results_['params']

print(means)
print(params)
print(xgb_search.best_params_)
print(xgb_search.best_score_)


常用参数解读:

estimator:所使用的分类器,如果比赛中使用的是XGBoost的话,就是生成的model。比如: model = xgb.XGBRegressor(**other_params)
param_grid:值为字典或者列表,即需要最优化的参数的取值。比如:cv_params = {‘n_estimators’: [550, 575, 600, 650, 675]}
scoring :准确度评价标准,默认None,这时需要使用score函数;或者如scoring=‘roc_auc’,根据所选模型不同,评价准则不同。字符串(函数名),或是可调用对象,需要其函数签名形如:scorer(estimator, X, y);如果是None,则使用estimator的误差估计函数。scoring参数选择如下:
scoring参数 说明:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章