【六 (6)机器学习-分类任务-kaggle泰坦尼克号宇宙飞船实战使用BayesianOptimization搜索参数并用SequentialFeatureSelector进行特征选择】

文章导航

【一 简明数据分析进阶路径介绍(文章导航)】

本篇文章在上篇的基础上,使用BayesianOptimization搜索参数并用SequentialFeatureSelector进行了特征选择

一、BayesianOptimization

BayesianOptimization,即贝叶斯优化,是一种基于贝叶斯定理的全局优化算法。其核心思想是通过建立一个目标函数的概率模型来指导搜索过程,从而找到使目标函数取得最优值的参数配置。

在贝叶斯优化中,首先假设目标函数服从一个先验分布(通常是高斯过程模型)。然后,在每次迭代中,根据当前的目标函数概率模型选择一个最有可能改善性能的点进行评估。评估完成后,将新的观测结果添加到模型中,并更新概率模型。这个过程会一直重复,直到达到预设的迭代次数或满足其他停止条件。

二、SequentialFeatureSelector

SequentialFeatureSelector(顺序特征选择器)是一种常用的特征选择算法。它的基本思想是从初始特征集合中逐步选择最佳特征,直到满足某种停止准则为止。这种算法用于从给定的特征集合中选择最佳的特征子集。

三、代码实现

1、初始化参数

params={
    'loss_function': 'Logloss', # 损失函数,取值RMSE, Logloss, MAE, CrossEntropy, Quantile, LogLinQuantile, Multiclass, MultiClassOneVsAll, MAPE, Poisson。默认Logloss。
    'custom_loss': 'AUC', # 训练过程中计算显示的损失函数,取值Logloss、CrossEntropy、Precision、Recall、F、F1、BalancedAccuracy、AUC等等
    'eval_metric': 'AUC', # 用于过度拟合检测和最佳模型选择的指标,取值范围同custom_loss
    'iterations': 50, # 最大迭代次数,默认500. 别名:num_boost_round, n_estimators, num_trees
    'learning_rate': 0.1, # 学习速率,默认0.03 别名:eta
    'random_seed': 123, # 训练的随机种子,别名:random_state
    'l2_leaf_reg': 5, # l2正则项,别名:reg_lambda
    'bootstrap_type': 'Bernoulli', # 确定抽样时的样本权重,取值Bayesian、Bernoulli(伯努利实验)、MVS(仅支持cpu)、Poisson(仅支持gpu)、No(取值为No时,每棵树为简单随机抽样);默认值GPU下为Bayesian、CPU下为MVS
#     'bagging_temperature': 0,  # bootstrap_type=Bayesian时使用,取值为1时采样权重服从指数分布;取值为0时所有采样权重均等于1。取值范围[0,inf),值越大、bagging就越激进
    'subsample': 0.6, # 样本采样比率(行采样)
    'sampling_frequency': 'PerTree', # 采样频率,取值PerTree(在构建每棵新树之前采样)、PerTreeLevel(默认值,在子树的每次分裂之前采样);仅支持CPU
    'use_best_model': True, # 让模型使用效果最优的子树棵树/迭代次数,使用验证集的最优效果对应的迭代次数(eval_metric:评估指标,eval_set:验证集数据),布尔类型可取值0,1(取1时要求设置验证集数据)
    'best_model_min_trees': 50, # 最少子树棵树,和use_best_model一起使用
    'depth': 4, # 树深,默认值6
    'grow_policy': 'SymmetricTree', # 子树生长策略,取值SymmetricTree(默认值,对称树)、Depthwise(整层生长,同xgb)、Lossguide(叶子结点生长,同lgb)
    'min_data_in_leaf': 500, # 叶子结点最小样本量
#     'max_leaves': 12, # 最大叶子结点数量
    'one_hot_max_size': 4, # 对唯一值数量<one_hot_max_size的类别型特征使用one-hot编码
    'rsm': 0.6, # 列采样比率,别名colsample_bylevel 取值(0,1],默认值1
    'nan_mode': 'Max', # 缺失值处理方法,取值Forbidden(不支持缺失值,输入包含缺失时会报错)、Min(处理为该列的最小值,比原最小值更小)、Max(同理)
    'input_borders': None, # 特征数据边界(最大最小边界)、会影响缺失值的处理(nan_mode取值Min、Max时),默认值None、在训练时特征取值的最大最小值即为特征值边界
    'boosting_type': 'Ordered', # 提升类型,取值Ordered(catboost特有的排序提升,在小数据集上效果可能更好,但是运行速度较慢)、Plain(经典提升)
    'max_ctr_complexity': 2, # 分类特征交叉的最高阶数,默认值4
    'logging_level':'Verbose', # 模型训练过程的信息输出等级,取值Silent(不输出信息)、Verbose(默认值,输出评估指标、已训练时间、剩余时间等)、Info(输出额外信息、树的棵树)、Debug(debug信息)
    'metric_period': 1, # 计算目标值、评估指标的频率,默认值1、即每次迭代都输出目标值、评估指标
    'early_stopping_rounds': 20,
    'border_count': 254, # 数值型特征的分箱数,别名max_bin,取值范围[1,65535]、默认值254(CPU下), # 设置提前停止训练,在得到最佳的评估结果后、再迭代n(参数值为n)次停止训练,默认值不启用
    'feature_border_type': 'GreedyLogSum', # 数值型特征的分箱方法,取值Median、Uniform、UniformAndQuantiles、MaxLogSum、MinEntropy、GreedyLogSum(默认值)
    
}

2、创建catboost建模函数

def catboost_model(train,test,params,cate_col=[]):
    x_train,x_test, y_train, y_test =train_test_split(train,test,test_size=0.2, random_state=123)
    
    model = CatBoostClassifier(**params)
    model.fit(x_train, y_train,eval_set=[(x_train, y_train),(x_test,y_test)],cat_features=cate_col)
    
    train_pred = [pred[1] for pred in  model.predict_proba(x_train)]
    train_auc= roc_auc_score(list(y_train),train_pred)
    
    test_pred = [pred[1] for pred in  model.predict_proba(x_test)]
    test_auc= roc_auc_score(list(y_test),test_pred)
    
    result={
        'train_auc':train_auc,
        'test_auc':test_auc,
    }
    return model,result

3、初始化模型

model,model_result=catboost_model(train.drop(columns=['PassengerId','Name','Transported']),train['Transported']
                                    ,params,qualitative)

4、查看特征重要性

def feature_importance_catboost(model):
    result=pd.DataFrame(model.get_feature_importance(),index=model.feature_names_,columns=['FeatureImportance'])
    return result.sort_values('FeatureImportance',ascending=False)
feature_importance_catboost(model)

输出:

Spa	15.638631
SumSpends	15.523511
VRDeck	14.034354
RoomService	12.184887
FoodCourt	10.298564
CryoSleep	8.575797
HomePlanet	7.752741
deck	7.750258
ShoppingMall	4.894730
side	2.516696
Destination	0.802385
Age	0.027448
VIP	0.000000
num	0.000000

5、使用贝叶斯调参

def catboost_cv(iterations,learning_rate,depth,subsample,rsm):
    params={
        'loss_function': 'Logloss', # 损失函数,取值RMSE, Logloss, MAE, CrossEntropy, Quantile, LogLinQuantile, Multiclass, MultiClassOneVsAll, MAPE, Poisson。默认Logloss。
        'custom_loss': 'AUC', # 训练过程中计算显示的损失函数,取值Logloss、CrossEntropy、Precision、Recall、F、F1、BalancedAccuracy、AUC等等
        'eval_metric': 'AUC', # 用于过度拟合检测和最佳模型选择的指标,取值范围同custom_loss
        'iterations': 50, # 最大迭代次数,默认500. 别名:num_boost_round, n_estimators, num_trees
        'learning_rate': 0.1, # 学习速率,默认0.03 别名:eta
        'random_seed': 123, # 训练的随机种子,别名:random_state
        'l2_leaf_reg': 5, # l2正则项,别名:reg_lambda
        'bootstrap_type': 'Bernoulli', # 确定抽样时的样本权重,取值Bayesian、Bernoulli(伯努利实验)、MVS(仅支持cpu)、Poisson(仅支持gpu)、No(取值为No时,每棵树为简单随机抽样);默认值GPU下为Bayesian、CPU下为MVS
    #     'bagging_temperature': 0,  # bootstrap_type=Bayesian时使用,取值为1时采样权重服从指数分布;取值为0时所有采样权重均等于1。取值范围[0,inf),值越大、bagging就越激进
        'subsample': 0.6, # 样本采样比率(行采样)
        'sampling_frequency': 'PerTree', # 采样频率,取值PerTree(在构建每棵新树之前采样)、PerTreeLevel(默认值,在子树的每次分裂之前采样);仅支持CPU
        'use_best_model': True, # 让模型使用效果最优的子树棵树/迭代次数,使用验证集的最优效果对应的迭代次数(eval_metric:评估指标,eval_set:验证集数据),布尔类型可取值0,1(取1时要求设置验证集数据)
        'best_model_min_trees': 50, # 最少子树棵树,和use_best_model一起使用
        'depth': 4, # 树深,默认值6
        'grow_policy': 'SymmetricTree', # 子树生长策略,取值SymmetricTree(默认值,对称树)、Depthwise(整层生长,同xgb)、Lossguide(叶子结点生长,同lgb)
        'min_data_in_leaf': 500, # 叶子结点最小样本量
    #     'max_leaves': 12, # 最大叶子结点数量
        'one_hot_max_size': 4, # 对唯一值数量<one_hot_max_size的类别型特征使用one-hot编码
        'rsm': 0.6, # 列采样比率,别名colsample_bylevel 取值(0,1],默认值1
        'nan_mode': 'Max', # 缺失值处理方法,取值Forbidden(不支持缺失值,输入包含缺失时会报错)、Min(处理为该列的最小值,比原最小值更小)、Max(同理)
        'input_borders': None, # 特征数据边界(最大最小边界)、会影响缺失值的处理(nan_mode取值Min、Max时),默认值None、在训练时特征取值的最大最小值即为特征值边界
        'boosting_type': 'Ordered', # 提升类型,取值Ordered(catboost特有的排序提升,在小数据集上效果可能更好,但是运行速度较慢)、Plain(经典提升)
        'max_ctr_complexity': 2, # 分类特征交叉的最高阶数,默认值4
        'logging_level':'Silent', # 模型训练过程的信息输出等级,取值Silent(不输出信息)、Verbose(默认值,输出评估指标、已训练时间、剩余时间等)、Info(输出额外信息、树的棵树)、Debug(debug信息)
        'metric_period': 1, # 计算目标值、评估指标的频率,默认值1、即每次迭代都输出目标值、评估指标
        'early_stopping_rounds': 20,
        'border_count': 254, # 数值型特征的分箱数,别名max_bin,取值范围[1,65535]、默认值254(CPU下), # 设置提前停止训练,在得到最佳的评估结果后、再迭代n(参数值为n)次停止训练,默认值不启用
        'feature_border_type': 'GreedyLogSum', # 数值型特征的分箱方法,取值Median、Uniform、UniformAndQuantiles、MaxLogSum、MinEntropy、GreedyLogSum(默认值)
#         'cat_features':cate_col
    }
    params.update({'iterations':int(iterations),'depth':int(depth),'learning_rate':learning_rate,'subsample':subsample,'rsm':rsm})
#     model = CatBoostClassifier(**params)
#     cv_result=cross_validate(model,df_copy[all_fea],df_copy['isDefault'], cv=5,scoring='roc_auc',return_train_score=True)
    
    model,result=catboost_model(train.drop(columns=['PassengerId','Name','Transported']),train['Transported']
                                    ,params,qualitative)
    return result.get('test_auc')
param_value_dics={
                'iterations':(20, 50),
                'learning_rate':(0.02,0.2),
                'depth':(3, 6),
                'subsample':(0.6, 1.0),
                'rsm':(0.6, 1.0)
                }
 
cat_bayes = BayesianOptimization(
        catboost_cv,
        param_value_dics
    )        
cat_bayes.maximize(init_points=1,n_iter=20) #init_points-调参基准点,n_iter-迭代次数
cat_bayes.max.get('params')

输出:

{'depth': 6.0,
 'iterations': 50.0,
 'learning_rate': 0.2,
 'rsm': 0.72498292390826,
 'subsample': 0.6}

6、设置最优参数并重新训练模型

cat_bayes.max.get('params')
params.update(
    {
        'depth': 6,
        'iterations': 50,
        'learning_rate': 0.2,
        'rsm': 0.725,
        'subsample': 0.6
    }
)
model,model_result=catboost_model(train.drop(columns=['PassengerId','Name','Transported']),train['Transported']
                                    ,params,qualitative)
model_result

输出:

{'train_auc': 0.8930049646962288, 'test_auc': 0.8973875461830807}

7、特征选择

# SequentialFeatureSelector 是 scikit-learn 提供的一个用于特征选择的工具,它支持向前选择(forward)、向后消除(backward)或双向选择(both)
from sklearn.feature_selection import SequentialFeatureSelector

model_fs = CatBoostClassifier(verbose=False)
sf = SequentialFeatureSelector(model_fs, scoring='accuracy', direction = 'backward')
sf.fit(X_train,y_train)
best_features = list(sf.get_feature_names_out())
best_features

输出:

['CryoSleep', 'RoomService', 'Spa', 'VRDeck', 'deck', 'side', 'SumSpends']

8、使用筛选后的特征重新训练模型并预测

cat_classifier = CatBoostClassifier(depth= 6,
        iterations=50,
        learning_rate=0.2,
        rsm=0.725,
        subsample=0.6)
cat_classifier.fit(X_train[['CryoSleep', 'RoomService', 'Spa', 'VRDeck', 'deck', 'side', 'SumSpends']], y_train)  

# 对输入数据进行预测
y_pred = cat_classifier.predict(test[['CryoSleep', 'RoomService', 'Spa', 'VRDeck', 'deck', 'side', 'SumSpends']])
# 将预测结果添加到数据表中,# 0是False 1是True
test['Transported'] = y_pred
test['Transported'] = test['Transported'].replace({0: False, 1: True})
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值