【机器学习(13)】参数搜索相关概念及sklearn中代码实现

1. 参数相关概念

1) 参数类型
        一般参数:模型通过最小化损失函数自动求解的参数
        超参数:不能通过模型对数据进行学习而求解的参数,比如神经网络的层数、正则系数的alpha值等

2) 参数搜索:
        超参数的搜索:提前设置好参数可以选择的候选值,然后根据不同参数组合对于模型泛化能力的贡献,选取最佳的超参数组合。(是针对于超参数的搜索)

3) 参数搜索的方法:

GridSearchCV,基于交叉验证的网格搜索法:将要搜索的参数候选值输入搜索器内,搜索器遍历每一种参数组合,使用交叉验证法对比每种参数组合下模型的表现,返回表现最好模型的参数值

        优点:自动调参,参数准确性高
        缺点:需要耗费巨大的算例和计算时间(比如:搜索100颗树的随机森森模型的两种参数各三个候选值,选择k等于10的交叉验证,则需要训练验证9000颗决策树才能返回最佳参数)

RandomizedSearchCV,基于交叉验证的随机搜索法:基本原理与GridSearchCV一致,但为了提高搜索效率,搜索器会从参数组合中随机搜索一些参数进行训练和验证,返回其中表现最好的参数值

        优点:运行效率高,适合大数据量样本
        缺点:参数的准确性有所牺牲

2. 代码实现

2.1 数据加载

还是和之前一样,直接copy过来,可以将警报处理放在最开始的地方

import pandas as pd
import matplotlib.pyplot as plt
import os
os.chdir(r'C:\Users\86177\Desktop')
import warnings
warnings.filterwarnings('ignore')
# 样例数据读取
df = pd.read_excel('realestate_sample_preprocessed.xlsx')
# 根据共线性矩阵,保留与房价相关性最高的日间人口,将夜间人口和20-39岁夜间人口进行比例处理
def age_percent(row):
    if row['nightpop'] == 0:
        return 0
    else:
        return row['night20-39']/row['nightpop']
df['per_a20_39'] = df.apply(age_percent,axis=1)
df = df.drop(columns=['nightpop','night20-39'])
# 制作标签变量
price_median = df['average_price'].median()
print(price_median)
df['is_high'] = df['average_price'].map(lambda x: True if x>= price_median else False)
print(df['is_high'].value_counts())
# 数据集基本情况查看
print(df.shape)
print(df.dtypes)
print(df.isnull().sum())

–> 输出的结果为:

30273.0

True     449
False    449
Name: is_high, dtype: int64

(898, 10)

id                 int64
complete_year      int64
average_price    float64
area             float64
daypop           float64
sub_kde          float64
bus_kde          float64
kind_kde         float64
per_a20_39       float64
is_high             bool
dtype: object

id               0
complete_year    0
average_price    0
area             0
daypop           0
sub_kde          0
bus_kde          0
kind_kde         0
per_a20_39       0
is_high          0
dtype: int64
2.2 使用留出法划分数据集

这个也是和之前的一样

from sklearn.model_selection import train_test_split
# 将数据集划分成训练集和验证集:划分比例0.75训练,0.25验证
training, testing = train_test_split(df,test_size=0.25, random_state=1)
# 提取训练集中的x与y
x_train = training.copy()[['complete_year','area', 'daypop', 'sub_kde',
       'bus_kde', 'kind_kde','per_a20_39']]
y_train = training.copy()['is_high']
# 提取验证集中的x与y
x_test = testing.copy()[['complete_year','area', 'daypop', 'sub_kde',
       'bus_kde', 'kind_kde','per_a20_39']]
y_test = testing.copy()['is_high']
print(f'the shape of training set is: {x_train.shape}')
print(f'the shape of testing set is: {x_test.shape}')

–> 输出的结果为:

the shape of training set is: (673, 7)
the shape of testing set is: (225, 7)
2.3 使用Pipeline创建工作流,构造模型

模型选择随机森林,核心内容讲解,

关于max_features(最大特征数量),里面是有四个类型
‘auto’:特征总数量的开方;
5代表整数型,选取5个特征进行训练;
0.8代表浮点数型,选取80%的特征进行训练;
None就是没有限制

关于 'max_depth'(最大深度),里面有三个
None:每棵树的深度没有限制;
3: 代表每棵树的深度为3,较为严格;
9:代表每棵树的深度为9,较为宽松

GridSearchCV(参数搜索器)中参数的讲解
第一个参数:搜索的模型
第二个参数:要搜索的参数矩阵,也就是上面的内容
第三个参数:设置的线程数,进行同步搜索
第四个参数:★★★★★交叉验证机制,这里和之前的不一样,不是用来做输出的,这是用来划分数据的,用来找到最佳的参数,分类使用选择的验证机制的模块是StratifiedKFold(不要搞错了),找到最佳参数后,还是使用留出法划分的数据进行预测的,不要和之前的内容搞混了
第五个参数:评价标准,在之前分类模型的评价指标中也有提到
第六个参数:就是提醒,可以在最后的输出中看到
第七个参数:当为True的时候,在找到最佳参数后会用最佳参数组重新训练一个模型,这样就可以直接使用GridSearchCV对象进行模型训练与预测

from sklearn.preprocessing import PowerTransformer, StandardScaler, PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import  StratifiedKFold,GridSearchCV
# 如果是选择随机网格搜索则:
from sklearn.model_selection import RandomizedSearchCV 
# 定义随机森林模型
rf_model = RandomForestClassifier(criterion='gini',
                                  n_jobs=16,
                                  n_estimators = 100,
                                  random_state=133)
# 定义需要搜索的参数矩阵
parameters = {'max_features': ['auto',5, 0.8, None],
              'max_depth': [None, 3, 9]}
# 定义交叉验证机制    
cv = StratifiedKFold(n_splits=3, shuffle=True)
# 定义参数搜索器
rf_gridsearch = GridSearchCV(rf_model, parameters, n_jobs=16, cv=cv, scoring='roc_auc',
                                      verbose=2, refit=True)
# pipline 模型封装
pipe_clf = Pipeline([
        ('sc',StandardScaler()),
        ('power_trans',PowerTransformer()),
        ('polynom_trans',PolynomialFeatures(degree=2)),
        ('rf_clf',rf_gridsearch)
        ])
print(pipe_clf)

–> 输出的结果为:

Pipeline(memory=None,
         steps=[('sc',
                 StandardScaler(copy=True, with_mean=True, with_std=True)),
                ('power_trans',
                 PowerTransformer(copy=True, method='yeo-johnson',
                                  standardize=True)),
                ('polynom_trans',
                 PolynomialFeatures(degree=2, include_bias=True,
                                    interaction_only=False, order='C')),
                ('rf_clf',
                 GridSearchCV(cv=StratifiedKFold(n_splits=3, random_state=None, shuffle=T...
                                                               min_samples_leaf=1,
                                                               min_samples_split=2,
                                                               min_weight_fraction_leaf=0.0,
                                                               n_estimators=100,
                                                               n_jobs=16,
                                                               oob_score=False,
                                                               random_state=133,
                                                               verbose=0,
                                                               warm_start=False),
                              iid='warn', n_jobs=16,
                              param_grid={'max_depth': [None, 3, 9],
                                          'max_features': ['auto', 5, 0.8,
                                                           None]},
                              pre_dispatch='2*n_jobs', refit=True,
                              return_train_score=False, scoring='roc_auc',
                              verbose=2))],
         verbose=False)
2.4 留出法在验证集上模型的表现
from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score
pipe_clf.fit(x_train,y_train)
y_predict = pipe_clf.predict(x_test)
print(f'accuracy score is: {accuracy_score(y_test,y_predict)}')
print(f'precision score is: {precision_score(y_test,y_predict)}')
print(f'recall score is: {recall_score(y_test,y_predict)}')
print(f'auc: {roc_auc_score(y_test,y_predict)}')

–> 输出的结果为:

Fitting 3 folds for each of 12 candidates, totalling 36 fits

[Parallel(n_jobs=16)]: Using backend LokyBackend with 16 concurrent workers.
[Parallel(n_jobs=16)]: Done  24 out of  36 | elapsed:    5.0s remaining:    2.5s
[Parallel(n_jobs=16)]: Done  36 out of  36 | elapsed:    5.4s finished

accuracy score is: 0.8622222222222222
precision score is: 0.8695652173913043
recall score is: 0.8620689655172413
auc: 0.8622271433090793
2.5 如何查看最佳参数
print(pipe_clf.named_steps['rf_clf'].best_params_)

–> 输出的结果为:(运行的结果会有不同的)

{'max_depth': 9, 'max_features': 'auto'}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lys_828

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值