当前位置:   article > 正文

Python机器学习 集成算法实例_集成学习算法python代码

集成学习算法python代码
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. %matplotlib inline
  5. SEED = 222
  6. np.random.seed(SEED)
  7. df = pd.read_csv('input.csv')
  8. #切分训练集和测试集
  9. from sklearn.model_selection import train_test_split
  10. from sklearn.metrics import roc_auc_score
  11. def get_train_test(test_size = 0.95):
  12. y = 1 * (df.cand_pty_affiliation == "REP")
  13. X = df.drop(["cand_pty_affiliation"], axis = 1)
  14. X = pd.get_dummies(X, sparse = True)
  15. #对样本的特征进行独热编码“one-hot encoding”
  16. X.drop(X.columns[X.std() == 0], axis = 1, inplace = True)
  17. #去掉标准差=0 即该特征所有样本都一样的列
  18. return train_test_split(X,y,test_size = test_size, random_state = SEED)
  19. xtrain, xtest, ytrain, ytest = get_train_test()
  20. print("\nExample data:")
  21. df.head()

 

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

 

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

 

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

 

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

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

 

 

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

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

 

  1. #这里把sklearn的算法全部押上
  2. from sklearn.svm import SVC, LinearSVC
  3. from sklearn.naive_bayes import GaussianNB
  4. from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
  5. from sklearn.neighbors import KNeighborsClassifier
  6. from sklearn.linear_model import LogisticRegression
  7. from sklearn.neural_network import MLPClassifier
  8. from sklearn.kernel_approximation import Nystroem
  9. from sklearn.kernel_approximation import RBFSampler
  10. from sklearn.pipeline import make_pipeline
  11. def get_models():
  12. "构建起一个包含了上述算法的一个集合"
  13. nb = GaussianNB()
  14. svc = SVC(C = 100, probability = True)
  15. knn = KNeighborsClassifier(n_neighbors = 3)
  16. lr = LogisticRegression(C = 100, random_state = SEED)
  17. nn = MLPClassifier((80,10),early_stopping = False, random_state = SEED)
  18. gb = GradientBoostingClassifier(n_estimators = 10, max_features =3, random_state = SEED)
  19. rf = RandomForestClassifier(n_estimators = 10, max_features =3, random_state = SEED)
  20. models = {'svm':svc,
  21. 'knn':knn,
  22. 'naive bayes':nb,
  23. 'mlp-nn':nn,
  24. 'random forest': rf,
  25. 'gbm':gb,
  26. 'logistic': lr,
  27. }
  28. return models
  29. def train_predict(model_list):
  30. "使用上述模型算法多测试集和训练集数据进行拟合并获得其预测的概率值"
  31. P = np.zeros((ytest.shape[0], len(model_list)))
  32. #构建一个和0矩阵,行和样本数一样,列的数目是用到的sklearn算法的总数
  33. P = pd.DataFrame(P)
  34. print("Fitting models.")
  35. cols = list()
  36. #通过一个for循环对之前构建的算法的字典进行调用,先拟合模型,然后将预测的概率结果赋值到P矩阵中对应的位置4
  37. #并依次保存算法的name到cols列表中,最后作为P的属性(就是DataFrame的第一列)
  38. for i, (name, m) in enumerate(models.items()):
  39. print("%s..." % name, end=" ", flush=False)
  40. m.fit(xtrain, ytrain)
  41. P.iloc[:, i] = m.predict_proba(xtest)[:, 1]
  42. cols.append(name)
  43. print("done")
  44. P.columns = cols
  45. print("Done.\n")
  46. return P
  47. def score_models(P, y):
  48. "对模型预测结果与测试集数据进行比较利用ROC-AUC评价指标进行打分"
  49. print("Scoring models.")
  50. for m in P.columns:
  51. score = roc_auc_score(y, P.loc[:, m])
  52. print("%-26s: %.3f" % (m, score))
  53. print("Done.\n")
  54. models = get_models()
  55. #调用get_models获得所有的模型集合组成的一个字典models
  56. P = train_predict(models)
  57. #依次利用每个算法模型进行拟合预测获得P矩阵中包含的每种模型算法的预测结果
  58. score_models(P,ytest)
  59. #使用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)))

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/600495
推荐阅读
相关标签
  

闽ICP备14008679号