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

本文主要是介绍XGBoost预测及调参过程(+变量重要性)--血友病计数数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

ddcdd574478b441d91e491390799e8da.png

读取数据及数据集区分

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

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

默认参数XGBoost

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

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

XGBoost调参

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

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

XGBoost变量重要性

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

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

63d57f3d881b494c9c82b321cef4ef92.png

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

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

5d065dbe99f747e68fc9b0d063c7a69c.png

 

这篇关于XGBoost预测及调参过程(+变量重要性)--血友病计数数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1066395

相关文章

C# 中变量未赋值能用吗,各种类型的初始值是什么

对于一个局部变量,如果未赋值,是不能使用的 对于属性,未赋值,也能使用有系统默认值,默认值如下: 对于 int 类型,默认值是 0;对于 int? 类型,默认值是 null;对于 bool 类型,默认值是 false;对于 bool? 类型,默认值是 null;对于 string 类型,默认值是 null;对于 string? 类型,哈哈,没有这种写法,会出错;对于 DateTime 类型,默

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

C/C++的编译和链接过程

目录 从源文件生成可执行文件(书中第2章) 1.Preprocessing预处理——预处理器cpp 2.Compilation编译——编译器cll ps:vs中优化选项设置 3.Assembly汇编——汇编器as ps:vs中汇编输出文件设置 4.Linking链接——链接器ld 符号 模块,库 链接过程——链接器 链接过程 1.简单链接的例子 2.链接过程 3.地址和

【服务器运维】MySQL数据存储至数据盘

查看磁盘及分区 [root@MySQL tmp]# fdisk -lDisk /dev/sda: 21.5 GB, 21474836480 bytes255 heads, 63 sectors/track, 2610 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical)

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测 目录 时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测基本介绍程序设计参考资料 基本介绍 MATLAB实现LSTM时间序列未来多步预测-递归预测。LSTM是一种含有LSTM区块(blocks)或其他的一种类神经网络,文献或其他资料中LSTM区块可能被描述成智能网络单元,因为

SQL Server中,查询数据库中有多少个表,以及数据库其余类型数据统计查询

sqlserver查询数据库中有多少个表 sql server 数表:select count(1) from sysobjects where xtype='U'数视图:select count(1) from sysobjects where xtype='V'数存储过程select count(1) from sysobjects where xtype='P' SE

数据时代的数字企业

1.写在前面 讨论数据治理在数字企业中的影响和必要性,并介绍数据治理的核心内容和实践方法。作者强调了数据质量、数据安全、数据隐私和数据合规等方面是数据治理的核心内容,并介绍了具体的实践措施和案例分析。企业需要重视这些方面以实现数字化转型和业务增长。 数字化转型行业小伙伴可以加入我的星球,初衷成为各位数字化转型参考库,星球内容每周更新 个人工作经验资料全部放在这里,包含数据治理、数据要

如何在Java中处理JSON数据?

如何在Java中处理JSON数据? 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将探讨在Java中如何处理JSON数据。JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,在现代应用程序中被广泛使用。Java通过多种库和API提供了处理JSON的能力,我们将深入了解其用法和最佳

LeetCode--204 计数质数

题目 统计所有小于非负整数 n 的质数的数量。 示例 示例:输入: 10输出: 4解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 class Solution {public:int countPrimes(int n) {if (n <= 2) return 0;int cnt = 0;vector<bool> isPrime(n, true);

两个基因相关性CPTAC蛋白组数据

目录 蛋白数据下载 ①蛋白数据下载 1,TCGA-选择泛癌数据  2,TCGA-TCPA 3,CPTAC(非TCGA) ②蛋白相关性分析 1,数据整理 2,蛋白相关性分析 PCAS在线分析 蛋白数据下载 CPTAC蛋白组学数据库介绍及数据下载分析 – 王进的个人网站 (jingege.wang) ①蛋白数据下载 可以下载泛癌蛋白数据:UCSC Xena (xena