• XGBoost预测及调参过程(+变量重要性)--血友病计数数据


             所使用的数据是血友病数据,如有需要,可在主页资源处获取,数据信息如下:

    ddcdd574478b441d91e491390799e8da.png

    读取数据及数据集区分

            数据预处理及区分数据集代码如下(详细预处理说明见上篇文章--随机森林):

    1. import pandas as pd
    2. import numpy as np
    3. hemophilia = pd.read_csv('D:/my_files/data.csv') #读取数据
    4. #数值变量化为分类变量
    5. hemophilia['hiv']=hemophilia['hiv'].astype(object)
    6. hemophilia['factor']=hemophilia['factor'].astype(object)
    7. new_hemophilia=pd.get_dummies(hemophilia,drop_first=True)
    8. #drop_first=True--删去一列,如hiv,处理后为两列,都是01表示,但只保留一列就足够表示两种状态
    9. new_data=new_hemophilia
    10. from sklearn.model_selection import train_test_split
    11. x = new_data.drop(['deaths'],axis=1) #删去标签列
    12. X_train, X_test, y_train, y_test = train_test_split(x, new_data.deaths, test_size=0.3, random_state=0)
    13. #区分数据集,70%训练集,30%测试集

    默认参数XGBoost

            先使用默认参数XGBoost进行预测,输出预测均方误差为0.334.

    1. from xgboost import XGBRegressor
    2. from sklearn.model_selection import GridSearchCV
    3. xgb_model = XGBRegressor(random_state=0) #random_state=0是随机种子数
    4. xgb_model.fit(X_train, y_train)
    5. y_pred = xgb_model.predict(X_test)
    6. print('MSE of xgb: %.3f' %metrics.mean_squared_error(y_test, y_pred))
    7. '''MSE of xgb: 0.334
    8. '''

    XGBoost调参

            接下来对XGBoost进行调参,XGBoost参数很多,一般对少数参数进行调整就可以得到不错的效果,所以这里只对'max_depth','min_child_weight','gamma'这三个参数进行粗略调参,如果追求更加有效的调参结果,可以对多个参数逐一调参。调参后输出预测均方误差为0.287,已经有所下降,说明模型的预测效果已经得到了提升。

    1. param_grid = {'max_depth':[1,2,3,4,5],
    2. 'min_child_weight':range(10,70,10),
    3. 'gamma':[i*0.01 for i in range(0,20,3)]}
    4. GS = GridSearchCV(xgb_model,param_grid,scoring = 'neg_mean_squared_error',cv=5)
    5. GS.fit(X_train, y_train)
    6. GS.best_params_ #最佳参数组合
    7. #{'gamma': 0.15, 'max_depth': 3, 'min_child_weight': 68}
    8. xgb_model = XGBRegressor(gamma = 0.15, max_depth = 3, min_child_weight = 60, random_state=0)
    9. xgb_model.fit(X_train, y_train)
    10. y_pred = xgb_model.predict(X_test)
    11. print('MSE of xgb: %.3f' %metrics.mean_squared_error(y_test, y_pred))
    12. '''MSE of xgb: 0.287
    13. '''

    XGBoost变量重要性

            XGBoost和随机森林都能够输出变量重要性,代码如下:

    1. import matplotlib.pyplot as plt
    2. importances = list(xgb_model.feature_importances_) #XGBoost
    3. feature_list = list(x.columns)
    4. feature_importances = [(feature, round(importance, 2)) for feature, importance in zip(feature_list, importances)]
    5. feature_importances = sorted(feature_importances, key=lambda x: x[1], reverse=True)
    6. f_list = []
    7. importances_list = []
    8. for i in range(0,8):
    9. feature = feature_importances[i][0]
    10. importances_r = feature_importances[i][1]
    11. f_list.append(feature),importances_list.append(importances_r)
    12. x_values = list(range(len(importances_list)))
    13. plt.figure(figsize=(14, 9))
    14. plt.bar(x_values, importances_list, orientation='vertical')
    15. plt.xticks(x_values, f_list, rotation=25, size =18)
    16. plt.yticks(size =18)
    17. plt.ylabel('Importance',size = 20)
    18. plt.xlabel('Variable',size = 20)
    19. plt.title('XGB Variable Importances',size = 22)
    20. #plt.savefig('D:/files/xgb变量重要性.png', dpi=800)
    21. #保存图片到指定位置 dpi--分辨率
    22. plt.show()

    63d57f3d881b494c9c82b321cef4ef92.png

            还可以输出图片对比预测结果和真实值的差异,代码及图片如下:

    1. import matplotlib.pyplot as plt
    2. y_test = y_test.reset_index(drop = True)
    3. plt.plot(y_test,color="b",label = 'True')
    4. plt.plot(y_pred,color="r",label = 'Prediction')
    5. plt.xlabel("index") #x轴命名表示
    6. plt.ylabel("deaths") #y轴命名表示
    7. plt.title("xgb Comparison between real and perdiction")
    8. plt.legend() #增加图例
    9. #plt.savefig('D:/my_files/xgb Comparison between real and perdiction.png', dpi = 500) #保存图片
    10. plt.show() #显示图片

    5d065dbe99f747e68fc9b0d063c7a69c.png

     

  • 相关阅读:
    详细介绍项目开发中多种常用的分布式锁的实现以及分析比较
    今天面了一个大学生:这82道SpringBoot面试题都答不上来?还想进大厂?
    use embeddings stored in vector db to reduce work for LLM generating response
    Async await的使用,调用axios后,等待axios执行完毕再继续往下执行
    docker迁移容器
    create® 3入门教程-创建Create3 Docker映像
    [LeetCode][LCR149]彩灯装饰记录 I——二叉树的层序遍历
    编程语言界再添新锐,Google 前工程师开源 Toit 语言
    Redis从入门到放弃(11):雪崩、击穿、穿透
    VS2019 error LNK2001: 无法解析的外部符号 解决方法
  • 原文地址:https://blog.csdn.net/wodertianna/article/details/138318258