import numpy as np
import pandas as pdimport matplotlib.pyplot as plt
%matplotlib inlineSEED = 222
np.random.seed(SEED)df = pd.read_csv('input.csv')
#切分训练集和测试集
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_scoredef get_train_test(test_size = 0.95):y = 1 * (df.cand_pty_affiliation == "REP")X = df.drop(["cand_pty_affiliation"], axis = 1)X = pd.get_dummies(X, sparse = True)#对样本的特征进行独热编码“one-hot encoding”X.drop(X.columns[X.std() == 0], axis = 1, inplace = True)#去掉标准差=0 即该特征所有样本都一样的列return train_test_split(X,y,test_size = test_size, random_state = SEED)xtrain, xtest, ytrain, ytest = get_train_test()print("\nExample data:")
df.head()

cand_pty_affiliation:我们要预测的指标,共和党或者民主党
entity_tp:个人还是组织
classification:领域
rpt_tp:贡献的大小
cycle:捐赠在哪年
transaction_amt:捐献金额
df.cand_pty_affiliation.value_counts(normalize = True).plot(kind  = "bar", title = "Share of No. donations")
plt.show()
#这里看一下原始数据正例和负例的比例,这里对应的是民主党和共和党 


import pydotplus
#导入结构化图形绘制工具
from IPython.display import Image
#导入图片显示的库,能够打开图片文件在jupyter中进行显示
from sklearn.metrics import roc_auc_score
from sklearn.tree import DecisionTreeClassifier, export_graphviz
#导入决策树模型和绘制决策树.dot文件的库def print_graph(clf, feature_names):"打印决策树"graph = export_graphviz(clf,label = 'root',proportion = True,impurity = False,out_file = None,feature_names = feature_names,class_names = {0: "D", 1: "R"},filled = True,rounded = True)graph = pydotplus.graph_from_dot_data(graph)#graph_from_dot_data(数据)按dot格式数据定义的加载图。数据假定为点格式。它将被解析后,#将返回一个点类,代表图。return Image(graph.create_png())t1 = DecisionTreeClassifier(max_depth = 1, random_state = SEED)
#构建决策树模型
t1.fit(xtrain, ytrain)
#对已经切分的训练集和测试集进行决策树模型拟合
p = t1.predict_proba(xtest)[:,1]
#对拟合后的t1进行预测,这里返回的是预测值为共和党、民主党这个二维数据的第二维的全部数据,这里是数据为共和党的概率
print("Decision tree ROC-AUC score: %.3f" % roc_auc_score(ytest, p))
print_graph(t1, xtrain.columns)

这里最后预测结果都是民主党,结果都是一样的没啥用,接下来对预剪枝参数进行调整 t2 = DecisionTreeClassifier(max_depth = 3, random_state = SEED)
#将决策树深度调整为3其余的参数不变得到新的决策树
t2.fit(xtrian, ytrain)
p = t2.predict_proba(xtest)[:, 1]print("Decision tree ROC-AUC score: %.3f" % roc_auc_score(ytest, p))
print_graph(t2, xtrain.columns)

47.3%的样本落到了最左边, 还有35.9% 落在了基本最右边. 这看起来模型基本已经过拟合了。我们来调整下策略,去掉个对结果有着最大影响的因素再来看看!drop = ['transaction_amt']
#去掉应最大的特征“捐献金额”
xtrain_slim = xtrain.drop(drop, 1)
xtest_slim = xtest.drop(drop, 1)t3 = DecisionTreeClassifier(max_depth = 3, random_state = SEED)
t3.fit(xtrain_slim, ytrain)
p = t3.predict_proba(xtest_slim)[:,1]print("Decision tree ROC-AUC score: %.3f" % roc_auc_score(ytest, p))
print_graph(t3, xtrain_slim.columns)

p1 = t2.predict_proba(xtest)[:, 1]
p2 = t3.predict_proba(xtest_slim)[:,1]
p = np.mean([p1,p2],axis = 0)
print("Average of decision tree ROC-AUC score: %.3f" % roc_auc_score(ytest, p))

整了个平均还真比原来高了! 这么一说,应该是选择不同的特征会产生不同的结果,然后用不同的结果再进行组合得到了一个升华!那我们多选几组不就是随机森林了嘛!

from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(n_estimators = 10,max_features = 3,random_state = SEED
)
#estimators 随机森林树的个数,就是搞了多少个决策树
#max_features 每个决策树所需要的考虑的决策特征的个数rf.fit(xtrain,ytrain)
p = rf.predict_proba(xtest)[:,1]
print("Average of decision tree ROC-AUC score: %.3f" % roc_auc_score(ytest, p))

#这里把sklearn的算法全部押上
from sklearn.svm import SVC, LinearSVC
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.kernel_approximation import Nystroem
from sklearn.kernel_approximation import RBFSampler
from sklearn.pipeline import make_pipelinedef get_models():"构建起一个包含了上述算法的一个集合"nb = GaussianNB()svc = SVC(C = 100, probability = True)knn = KNeighborsClassifier(n_neighbors = 3)lr = LogisticRegression(C = 100, random_state = SEED)nn = MLPClassifier((80,10),early_stopping = False, random_state = SEED)gb = GradientBoostingClassifier(n_estimators = 10, max_features =3, random_state = SEED)rf = RandomForestClassifier(n_estimators = 10, max_features =3, random_state = SEED)models = {'svm':svc,'knn':knn,'naive bayes':nb,'mlp-nn':nn,'random forest': rf,'gbm':gb,'logistic': lr,}return modelsdef train_predict(model_list):"使用上述模型算法多测试集和训练集数据进行拟合并获得其预测的概率值"P = np.zeros((ytest.shape[0], len(model_list)))#构建一个和0矩阵,行和样本数一样,列的数目是用到的sklearn算法的总数P = pd.DataFrame(P)print("Fitting models.")cols = list()#通过一个for循环对之前构建的算法的字典进行调用,先拟合模型,然后将预测的概率结果赋值到P矩阵中对应的位置4#并依次保存算法的name到cols列表中,最后作为P的属性(就是DataFrame的第一列)for i, (name, m) in enumerate(models.items()):print("%s..." % name, end=" ", flush=False)m.fit(xtrain, ytrain)P.iloc[:, i] = m.predict_proba(xtest)[:, 1]cols.append(name)print("done")P.columns = colsprint("Done.\n")return Pdef score_models(P, y):"对模型预测结果与测试集数据进行比较利用ROC-AUC评价指标进行打分"print("Scoring models.")for m in P.columns:score = roc_auc_score(y, P.loc[:, m])print("%-26s: %.3f" % (m, score))print("Done.\n")models = get_models()
#调用get_models获得所有的模型集合组成的一个字典models
P = train_predict(models)
#依次利用每个算法模型进行拟合预测获得P矩阵中包含的每种模型算法的预测结果
score_models(P,ytest)
#使用ROC-AUC评价指标对P矩阵中模型预测结果与实际测试集进行比较

#导入混淆矩阵可视化的库
from mlens.visualization import corrmat

corrmat(P.corr(), inflate = False)
plt.show()

预测的结果很多都是高度相关的!

print("Ensemble ROC-AUC score: %.3f" % roc_auc_score(ytest, P.mean(axis = 1)))

from sklearn.metrics import roc_curvedef plot_roc_curve(ytest, P_base_learners, P_ensemble, labels, ens_label):"""Plot the roc curve for base learners and ensemble."""plt.figure(figsize=(10, 8))plt.plot([0, 1], [0, 1], 'k--')cm = [plt.cm.rainbow(i)for i in np.linspace(0, 1.0, P_base_learners.shape[1] + 1)]for i in range(P_base_learners.shape[1]):p = P_base_learners[:, i]fpr, tpr, _ = roc_curve(ytest, p)plt.plot(fpr, tpr, label=labels[i], c=cm[i + 1])#绘制单个算法模型的曲线结果fpr, tpr, _ = roc_curve(ytest, P_ensemble)plt.plot(fpr, tpr, label=ens_label, c=cm[0])#绘制集成算法的曲线plt.xlabel('False positive rate')plt.ylabel('True positive rate')plt.title('ROC curve')plt.legend(frameon=False)plt.show()plot_roc_curve(ytest, P.values, P.mean(axis=1), list(P.columns), "ensemble")

Python机器学习 集成算法实例相关推荐

  1. python实现冒泡排序完整算法_利用python实现冒泡排序算法实例代码

    利用python实现冒泡排序算法实例代码 冒泡排序 冒泡排序(英语:Bubble Sort)是一种简单的排序算法.它重复地遍历要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来.遍历数 ...

  2. 10- 天猫用户复购预测 (机器学习集成算法) (项目十) *

    项目难点 merchant:  商人 重命名列名:  user_log.rename(columns={'seller_id':'merchant_id'}, inplace=True) 数据类型转换 ...

  3. python --机器学习(基本算法详解)SciPy、Numpy、Matplotlib

    介绍 数据集 在计算机中,数据集指的是任何数据集合.它可以是从数组到完整数据库的任何内容. 一个数组的例子: [99,86,87,88,111,86,103,87,94,78,77,85,86] 一个 ...

  4. 2019最新《小象学院Python机器学习和算法高级版项目实战》

    ├─00.课程介绍 │      <机器学习·升级版II>常见问题FAQ - 小象问答-hadoop,spark,storm,R,hi.jpg │      <机器学习>升级版 ...

  5. python机器学习 | SVM算法介绍及实现

    本篇博客具体学习参考: 1 [机器学习]支持向量机SVM及实例应用 2 [ML]支持向量机(SVM)从入门到放弃再到掌握 这两篇文章讲得特别清楚,数学推导(第一篇)也能看明白,强烈推荐学习~~ 本篇博 ...

  6. 05- 泰坦尼克号海难生死预测 (机器学习集成算法) (项目五)

    Kaggle:  一个数据建模和数据分析竞赛平台 sns画柱状图:  sns.barplot(data=train,x='Pclass',y='Survived') 查看数据分布(survived 和 ...

  7. 09- 京东客户购买意向预测 (机器学习集成算法) (项目九) *

    项目难点 根据用户在网站的操作(浏览, 加购, 删除, 购买, 收藏, 点击), 预测用户是否购买产品 . 主要使用 Xgboost 建模 pd.get_dummies 相当于onehot编码,常用与 ...

  8. Python机器学习--回归算法--线性回归

    线性回归算法的类型 有监督学习的回归算法[标签是连续数据类型] 线性回归基础 研究父子身高关系 研究父辈身高(自变量x)如何决定子辈身高(因变量y) 建立方程表征关系:y = kx+b-------- ...

  9. Python机器学习--回归算法--线性回归算法

    线性回归算法 线性回归算法类型: 线性回归算法属于有监督学习的回归算法,可以处理标签为连续数据类型的数据. 线性回归算法原理: 通过寻找特征和标签之间的关系,生成一个线性方程,通过线性方程预测未知标签 ...

最新文章

  1. 使用Jittor实现Conditional GAN
  2. android 模板 ui布局,Android UI布局
  3. hexo博客更新主题后上传Git操作
  4. STM32 进阶教程 11 - RAM中运行程序
  5. Windows 10 RedStone2值得期待的五大功能猜想
  6. python打开文件要wordcloud吗,使用python创建wordcloud
  7. ICML2021 | ALIGN:大力出奇迹,谷歌用18亿的图像-文本对训练了一个这样的模型
  8. laytpl语法_浅谈laytpl 模板空值显示null的解决方法及简单的js表达式
  9. 基于卷积神经网络模型的MSTAR高分辨率图像数据集识别实践
  10. oracle rac 学习(转载)
  11. 超星尔雅学习通情商与智慧人生 答案 满分版
  12. python模块安装位置_查看python模块的安装路径
  13. python编程视频剪辑_MoviePy常用剪辑类及Python视频剪辑自动化
  14. 分类,等级,或者有序变量如何进行多因素Cox回归 变量的类型决定了最终结果的reference
  15. 如何学习理财知识,零基础怎么学习理财
  16. 2022-2028年中国酯基季铵盐行业市场全面调研及投资前景预测报告
  17. html5 基本布局+新标签+新选择器 + 线性渐变
  18. SCRM升级--企业微信数字营销解决方案
  19. 牧原面试(销售部-统计分析)总结
  20. 数据结构(一)求矩阵中的鞍点

热门文章

  1. C++ 3D物理引擎库BulletPhysics基本使用
  2. 沙朗javascript总结一下(一)---基础知识
  3. 窥探Swift之别样的枚举类型
  4. 逗号分割符--字段中含逗号等情况的解析方法Java实现
  5. Qt信号槽中槽函数为虚函数的一些感想
  6. js防止表单的重复提交
  7. 写在国产接口管理工具ApiPost 5.2.5发布后的一些话
  8. PHP泡泡龙源码,JS泡泡龙游戏网页版+完整代码
  9. python在csv模块添加新列_如何在CSV文件的开头添加新列?
  10. keras指定gpu_keras不使用gpu,但tensorflow