利用python进行AdaBoost模型预测
以信用卡违约数据为例,该数据集来源于UCI网站,一共包30 000条记录和25个变量,其中自变量包含客户的性别、受教育水平、年龄、婚姻状况、信用额度、6个月的历史还款状态、账单金额以及还款金额,因变量y表示用户在下个月的信用卡还款中是否存在违约的情况(1表示违约,0表示不违约)。
Python代码如下:
(1)导入包和模块
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn import ensemble
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
(2)绘图查看训练集标签类别是否不平衡
# 读入数据
default = pd.read_excel('default of credit card.xls')
# 为确保绘制的饼图为圆形,需执行如下代码
plt.axes(aspect = 'equal')
# 中文乱码和坐标轴负号的处理
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
# 统计客户是否违约的频数
counts = default.y.value_counts()
# 绘制饼图
plt.pie(x = counts, # 绘图数据labels = pd.Series(counts.index).map({0:'不违约',1:'违约'}), # 添加文字标签autopct = '%.lf%%' # 设置百分比的格式,这里保留一位小数)
# 显示图形
plt.show()
(3)利用AdaBoost模型进行预测,输出模型评估报告
# 排除数据集中的ID变量和因变量,剩余的数据用作自变量x
X = default.drop(['ID','y'], axis = 1)
y = default.y
# 数据拆分
X_train,X_test,y_train,y_test = model_selection.train_test_split(X,y,test_size = 0.25,random_state = 1234)
# 构建AdaBoost算法的类
AdaBoost1 = ensemble.AdaBoostClassifier()
# 算法在训练集上的拟合
AdaBoost1.fit(X_train, y_train)
# 算法在测试集上的预测
pred1 = AdaBoost1.predict(X_test)
# 返回模型的预测结果
print('模型的准确率为:\n',metrics.accuracy_score(y_test, pred1))
print('模型的评估报告:\n',metrics.classification_report(y_test, pred1))
(4)利用ROC曲线对模型进行评估
# 计算客户违约的概率值,用于生成ROC曲线的数据
y_score = AdaBoost1.predict_proba(X_test)[:,1]
fpr,tpr,threshold = metrics.roc_curve(y_test, y_score)
# 计算AUC的值
roc_auc = metrics.auc(fpr, tpr)
# 绘制面积图
plt.stackplot(fpr, tpr, color = 'steelblue', alpha = 0.5, edgecolor = 'black')
# 添加边际线
plt.plot(fpr, tpr, color = 'black', lw = 1)
# 添加对角线
plt.plot([0,1], [0,1], color = 'red', linestyle = '--')
# 添加文本信息
plt.text(0.5, 0.3, 'ROC curve (area = %0.2f)' %roc_auc)
# 添加x轴与y轴标签
plt.xlabel('l-specificity')
plt.ylabel('sensitivity')
# 显示图形
plt.show()
(5)查看自变量的重要性排序
# 自变量的重要性排序
importance = pd.Series(AdaBoost1.feature_importances_, index = X.columns)
importance.sort_values().plot(kind = 'barh')
plt.show()
(6)利用网格搜索寻找AdaBoost模型最优参数
# 取出重要性比较高的自变量建模
predictors = list(importance[importance > 0.02].index)
# 通过网格搜索法选择基础模型所对应的合理参数组合
max_depth = [3, 4, 5, 6]
params1 = {'base_estimator__max_depth':max_depth}
base_model = GridSearchCV(estimator = ensemble.AdaBoostClassifier(base_estimator = DecisionTreeClassifier()),param_grid = params1,scoring = 'roc_auc', cv = 5, n_jobs =4, verbose = 1)
base_model.fit(X_train[predictors], y_train)
n_estimators = [100, 200, 300]
learning_rate = [0.01, 0.05, 0.1, 0.2]
params2 = {'n_estimators':n_estimators, 'learning_rate':learning_rate}
adaboost = GridSearchCV(estimator = ensemble.AdaBoostClassifier(base_estimator =DecisionTreeClassifier(max_depth = 3)),param_grid = params2,scoring = 'roc_auc', cv = 5, n_jobs = 4, verbose = 1)
adaboost.fit(X_train[predictors], y_train)
(7)利用优化后的AdaBoost模型进行预测,输出模型评估报告
# 使用最佳的参数组合构建AdaBoost模型
AdaBoost2 = ensemble.AdaBoostClassifier(base_estimator = DecisionTreeClassifier(max_depth = 3),n_estimators = 300, learning_rate = 0.01)
# 算法在训练数据集上的拟合
AdaBoost2.fit(X_train[predictors], y_train)
# 算法在测试数据集上的预测
pred2 = AdaBoost2.predict(X_test[predictors])
# 返回模型的预测结果
print('模型的准确率为:\n', metrics.accuracy_score(y_test, pred2))
print('模型的评估报告:\n', metrics.classification_report(y_test, pred2))
(8)运行结果:
全部代码如下:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn import ensemble
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV# 读入数据
default = pd.read_excel('default of credit card.xls')
# 为确保绘制的饼图为圆形,需执行如下代码
plt.axes(aspect = 'equal')
# 中文乱码和坐标轴负号的处理
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
# 统计客户是否违约的频数
counts = default.y.value_counts()
# 绘制饼图
plt.pie(x = counts, # 绘图数据labels = pd.Series(counts.index).map({0:'不违约',1:'违约'}), # 添加文字标签autopct = '%.lf%%' # 设置百分比的格式,这里保留一位小数)
# 显示图形
plt.show()# 排除数据集中的ID变量和因变量,剩余的数据用作自变量x
X = default.drop(['ID','y'], axis = 1)
y = default.y
# 数据拆分
X_train,X_test,y_train,y_test = model_selection.train_test_split(X,y,test_size = 0.25,random_state = 1234)
# 构建AdaBoost算法的类
AdaBoost1 = ensemble.AdaBoostClassifier()
# 算法在训练集上的拟合
AdaBoost1.fit(X_train, y_train)
# 算法在测试集上的预测
pred1 = AdaBoost1.predict(X_test)
# 返回模型的预测结果
print('模型的准确率为:\n',metrics.accuracy_score(y_test, pred1))
print('模型的评估报告:\n',metrics.classification_report(y_test, pred1))# 计算客户违约的概率值,用于生成ROC曲线的数据
y_score = AdaBoost1.predict_proba(X_test)[:,1]
fpr,tpr,threshold = metrics.roc_curve(y_test, y_score)
# 计算AUC的值
roc_auc = metrics.auc(fpr, tpr)
# 绘制面积图
plt.stackplot(fpr, tpr, color = 'steelblue', alpha = 0.5, edgecolor = 'black')
# 添加边际线
plt.plot(fpr, tpr, color = 'black', lw = 1)
# 添加对角线
plt.plot([0,1], [0,1], color = 'red', linestyle = '--')
# 添加文本信息
plt.text(0.5, 0.3, 'ROC curve (area = %0.2f)' %roc_auc)
# 添加x轴与y轴标签
plt.xlabel('l-specificity')
plt.ylabel('sensitivity')
# 显示图形
plt.show()# 自变量的重要性排序
importance = pd.Series(AdaBoost1.feature_importances_, index = X.columns)
importance.sort_values().plot(kind = 'barh')
plt.show()# 取出重要性比较高的自变量建模
predictors = list(importance[importance > 0.02].index)
# 通过网格搜索法选择基础模型所对应的合理参数组合
max_depth = [3, 4, 5, 6]
params1 = {'base_estimator__max_depth':max_depth}
base_model = GridSearchCV(estimator = ensemble.AdaBoostClassifier(base_estimator = DecisionTreeClassifier()),param_grid = params1,scoring = 'roc_auc', cv = 5, n_jobs =4, verbose = 1)
base_model.fit(X_train[predictors], y_train)
n_estimators = [100, 200, 300]
learning_rate = [0.01, 0.05, 0.1, 0.2]
params2 = {'n_estimators':n_estimators, 'learning_rate':learning_rate}
adaboost = GridSearchCV(estimator = ensemble.AdaBoostClassifier(base_estimator =DecisionTreeClassifier(max_depth = 3)),param_grid = params2,scoring = 'roc_auc', cv = 5, n_jobs = 4, verbose = 1)
adaboost.fit(X_train[predictors], y_train)# 使用最佳的参数组合构建AdaBoost模型
AdaBoost2 = ensemble.AdaBoostClassifier(base_estimator = DecisionTreeClassifier(max_depth = 3),n_estimators = 300, learning_rate = 0.01)
# 算法在训练数据集上的拟合
AdaBoost2.fit(X_train[predictors], y_train)
# 算法在测试数据集上的预测
pred2 = AdaBoost2.predict(X_test[predictors])
# 返回模型的预测结果
print('模型的准确率为:\n', metrics.accuracy_score(y_test, pred2))
print('模型的评估报告:\n', metrics.classification_report(y_test, pred2))
参考文献:《从零开始学Python数据分析与挖掘》 by 刘顺祥 (z-lib.org)
利用python进行AdaBoost模型预测相关推荐
- Python:pmml格式文件的简介、安装、使用方法(利用python将机器学习模型转为Java常用的pmml格式文件)之详细攻略
Python:pmml格式文件的简介.安装.使用方法(利用python将机器学习模型转为Java常用的pmml格式文件)之详细攻略 目录 pmml格式文件的简介 1.PMML结构 pmml安装 pmm ...
- python模型预测_【超级干货!】教你用Python做回归模型预测房价
原标题:[超级干货!]教你用Python做回归模型预测房价 欢迎关注天善智能 hellobi.com,我们是专注于商业智能BI,大数据,数据分析领域的垂直社区,学习.问答.求职,一站式搞定! 对商业智 ...
- python数据预测_利用Python编写一个数据预测工具
利用Python编写一个数据预测工具 发布时间:2020-11-07 17:12:20 来源:亿速云 阅读:96 这篇文章运用简单易懂的例子给大家介绍利用Python编写一个数据预测工具,内容非常详细 ...
- ML之FE:基于波士顿房价数据集利用LightGBM算法进行模型预测然后通过3σ原则法(计算残差标准差)寻找测试集中的异常值/异常样本
ML之FE:基于波士顿房价数据集利用LightGBM算法进行模型预测然后通过3σ原则法(计算残差标准差)寻找测试集中的异常值/异常样本 目录 基于波士顿房价数据集利用LiR和LightGBM算法进行模 ...
- 网传天猫双十一数据造假?利用Python对其进行预测分析
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 朱小五 PS:如有需要Python学习资料的小伙伴可以加点击下方链接 ...
- 用Python搭建机器学习模型预测房租价格
毫无疑问,机器学习是当前大数据分析中最热门的话题.这也是一些最令人兴奋的技术领域的基本概念,例如自动驾驶汽车和预测分析.百度上的机器学习搜索在2019年4月创历史新高,自此以来兴趣一直没有下降. 但是 ...
- python用ARIMA模型预测CO2浓度时间序列实现
全文下载链接:http://tecdat.cn/?p=20424 时间序列为预测未来数据提供了方法.根据先前的值,时间序列可用于预测经济,天气的趋势.时间序列数据的特定属性意味着通常需要专门的统计方法 ...
- 利用python实现SNM模型
SNM(SHOT NOISE TRAFFIC MODEL)简介 SNM是在文章"Temporal Locality in Today's Content Caching: Why it Ma ...
- 利用python实现ANN算法预测岩石单轴抗压强度的经验模型代码。设置岩石密度、孔隙度、施密特回弹值、动岩石参数作为输出层...
我可以提供一段Python代码来实现这个经验模型:import numpy as np # 定义输入层 rock_density = np.array([[0.2], [0.3], [0.4]]) p ...
最新文章
- Linux/docker下oracle开启监听,开启自动启动
- 基于Redis的分布式锁和Redlock算法
- SNMP功能开发简介 三 使用DEBUGMSG打印指定的信息
- 从0开始学习 GitHub 系列之「初识 GitHub」
- C#中多线程和定时器是不是有冲突?
- 音视频技术开发周刊 | 135
- 循环灯c语言,单片机c语言循环灯
- Scrum基础知识体系和感想
- JavaScript原生添加移除class的方法
- matlab里两个for怎么跳出循环,急急急!matlab含有两个for循环,程序不知道哪儿错了,求指教!...
- Python 各种运算符 布尔运算 迭代器
- Linux 内核 5.4 将于 11月24 日 发布,Linux 5.4-rc8 已可用于公测
- ODE网络:一场颠覆RNN的革命即将到来
- linux smb上传文件,使用Samba服务器由win平台向linux平台上传文件
- 栈、堆、静态存储区的三分天下
- 如何让win7像win10一样漂亮-win7美化
- 如何获取win10锁屏界面的壁纸
- ITFriend网站内测公测感悟
- Android视频直播源码开发直播平台、点播播放器哪家强?
- MTK Android4.0.3 ICS 添加缅甸语Myanmar
热门文章
- 手机网页应用的交互设计
- pdf转txt java_pdf转换txt怎么操作?pdf文件可以转换成txt文件吗?
- mybatis在实际项目中常见的排坑配置
- System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security
- 微信小程序登录+坐标定位显示km数
- react生命周期详细介绍
- vue中的this.nextTick()
- 【access control】常用访问控制模型比较
- Centos下netstat的使用
- c语言程序设计第五版第三章课后题