本文介绍在Python环境中,实现随机森林(Random Forest,RF)回归与各自变量重要性分析与排序的过程。

  其中,关于基于MATLAB实现同样过程的代码与实战,大家可以点击查看MATLAB实现随机森林(RF)回归与自变量影响程度分析这篇文章。

  本文分为两部分,第一部分为代码的分段讲解,第二部分为完整代码。

1 代码分段讲解

1.1 模块与数据准备

  首先,导入所需要的模块。在这里,需要pydotgraphviz这两个相对不太常用的模块,即使我用了Anaconda,也需要单独下载、安装。具体下载与安装,如果同样是在用Anaconda,大家就参考Python pydot与graphviz库在Anaconda环境的配置即可。

  1. import pydot
  2. import numpy as np
  3. import pandas as pd
  4. import scipy.stats as stats
  5. import matplotlib.pyplot as plt
  6. from sklearn import metrics
  7. from openpyxl import load_workbook
  8. from sklearn.tree import export_graphviz
  9. from sklearn.ensemble import RandomForestRegressor

  接下来,我们将代码接下来需要用的主要变量加以定义。这一部分大家先不用过于在意,浏览一下继续向下看即可;待到对应的变量需要运用时我们自然会理解其具体含义。

  1. train_data_path='G:/CropYield/03_DL/00_Data/AllDataAll_Train.csv'
  2. test_data_path='G:/CropYield/03_DL/00_Data/AllDataAll_Test.csv'
  3. write_excel_path='G:/CropYield/03_DL/05_NewML/ParameterResult_ML.xlsx'
  4. tree_graph_dot_path='G:/CropYield/03_DL/05_NewML/tree.dot'
  5. tree_graph_png_path='G:/CropYield/03_DL/05_NewML/tree.png'
  6. random_seed=44
  7. random_forest_seed=np.random.randint(low=1,high=230)

  接下来,我们需要导入输入数据。

  在这里需要注意,本文对以下两个数据处理的流程并没有详细涉及与讲解(因为在写本文时,我已经做过了同一批数据的深度学习回归,本文就直接用了当时做深度学习时处理好的输入数据,因此以下两个数据处理的基本过程就没有再涉及啦),大家直接查看下方所列出的其它几篇博客即可。

  • 初始数据划分训练集与测试集

  • 类别变量的独热编码(One-hot Encoding)

  针对上述两个数据处理过程,首先,数据训练集与测试集的划分在机器学习、深度学习中是不可或缺的作用,这一部分大家可以查看Python TensorFlow深度学习回归代码:DNNRegressor2.4部分,或Python TensorFlow深度神经网络回归:keras.Sequential2.3部分;其次,关于类别变量的独热编码,对于随机森林等传统机器学习方法而言可以说同样是非常重要的,这一部分大家可以查看Python实现类别变量的独热编码(One-hot Encoding)

  在本文中,如前所述,我们直接将已经存在.csv中,已经划分好训练集与测试集且已经对类别变量做好了独热编码之后的数据加以导入。在这里,我所导入的数据第一行是表头,即每一列的名称。关于.csv数据导入的代码详解,大家可以查看多变量两两相互关系联合分布图的Python绘制数据导入部分。

  1. # Data import
  2. '''
  3. column_name=['EVI0610','EVI0626','EVI0712','EVI0728','EVI0813','EVI0829','EVI0914','EVI0930','EVI1016',
  4. 'Lrad06','Lrad07','Lrad08','Lrad09','Lrad10',
  5. 'Prec06','Prec07','Prec08','Prec09','Prec10',
  6. 'Pres06','Pres07','Pres08','Pres09','Pres10',
  7. 'SIF161','SIF177','SIF193','SIF209','SIF225','SIF241','SIF257','SIF273','SIF289',
  8. 'Shum06','Shum07','Shum08','Shum09','Shum10',
  9. 'Srad06','Srad07','Srad08','Srad09','Srad10',
  10. 'Temp06','Temp07','Temp08','Temp09','Temp10',
  11. 'Wind06','Wind07','Wind08','Wind09','Wind10',
  12. 'Yield']
  13. '''
  14. train_data=pd.read_csv(train_data_path,header=0)
  15. test_data=pd.read_csv(test_data_path,header=0)

1.2 特征与标签分离

  特征与标签,换句话说其实就是自变量与因变量。我们要将训练集与测试集中对应的特征与标签分别分离开来。

  1. # Separate independent and dependent variables
  2. train_Y=np.array(train_data['Yield'])
  3. train_X=train_data.drop(['ID','Yield'],axis=1)
  4. train_X_column_name=list(train_X.columns)
  5. train_X=np.array(train_X)
  6. test_Y=np.array(test_data['Yield'])
  7. test_X=test_data.drop(['ID','Yield'],axis=1)
  8. test_X=np.array(test_X)

  可以看到,直接借助drop就可以将标签'Yield'从原始的数据中剔除(同时还剔除了一个'ID',这个是初始数据的样本编号,后面就没什么用了,因此随着标签一起剔除)。同时在这里,还借助了train_X_column_name这一变量,将每一个特征值列所对应的标题(也就是特征的名称)加以保存,供后续使用。

1.3 RF模型构建、训练与预测

  接下来,我们就需要对随机森林模型加以建立,并训练模型,最后再利用测试集加以预测。在这里需要注意,关于随机森林的几个重要超参数(例如下方的n_estimators)都是需要不断尝试找到最优的。关于这些超参数的寻优,在MATLAB中的实现方法大家可以查看MATLAB实现随机森林(RF)回归与自变量影响程度分析1.1部分;而在Python中的实现方法,我们将在下一篇博客中介绍。

  1. # Build RF regression model
  2. random_forest_model=RandomForestRegressor(n_estimators=200,random_state=random_forest_seed)
  3. random_forest_model.fit(train_X,train_Y)
  4. # Predict test set data
  5. random_forest_predict=random_forest_model.predict(test_X)
  6. random_forest_error=random_forest_predict-test_Y

  其中,利用RandomForestRegressor进行模型的构建,n_estimators就是树的个数,random_state是每一个树利用Bagging策略中的Bootstrap进行抽样(即有放回的袋外随机抽样)时,随机选取样本的随机数种子;fit进行模型的训练,predict进行模型的预测,最后一句就是计算预测的误差。

1.4 预测图像绘制、精度衡量指标计算与保存

  首先,进行预测图像绘制,其中包括预测结果的拟合图与误差分布直方图。关于这一部分代码的解释,大家可以查看Python TensorFlow深度学习回归代码:DNNRegressor2.9部分。

  1. # Draw test plot
  2. plt.figure(1)
  3. plt.clf()
  4. ax=plt.axes(aspect='equal')
  5. plt.scatter(test_Y,random_forest_predict)
  6. plt.xlabel('True Values')
  7. plt.ylabel('Predictions')
  8. Lims=[0,10000]
  9. plt.xlim(Lims)
  10. plt.ylim(Lims)
  11. plt.plot(Lims,Lims)
  12. plt.grid(False)
  13. plt.figure(2)
  14. plt.clf()
  15. plt.hist(random_forest_error,bins=30)
  16. plt.xlabel('Prediction Error')
  17. plt.ylabel('Count')
  18. plt.grid(False)

  以上两幅图的绘图结果如下所示。

  接下来,进行精度衡量指标的计算与保存。在这里,我们用皮尔逊相关系数决定系数RMSE作为精度的衡量指标,并将每一次模型运行的精度衡量指标结果保存在一个Excel文件中。这一部分大家同样查看Python TensorFlow深度学习回归代码:DNNRegressor2.9部分即可。

  1. # Verify the accuracy
  2. random_forest_pearson_r=stats.pearsonr(test_Y,random_forest_predict)
  3. random_forest_R2=metrics.r2_score(test_Y,random_forest_predict)
  4. random_forest_RMSE=metrics.mean_squared_error(test_Y,random_forest_predict)**0.5
  5. print('Pearson correlation coefficient is {0}, and RMSE is {1}.'.format(random_forest_pearson_r[0],
  6. random_forest_RMSE))
  7. # Save key parameters
  8. excel_file=load_workbook(write_excel_path)
  9. excel_all_sheet=excel_file.sheetnames
  10. excel_write_sheet=excel_file[excel_all_sheet[0]]
  11. excel_write_sheet=excel_file.active
  12. max_row=excel_write_sheet.max_row
  13. excel_write_content=[random_forest_pearson_r[0],random_forest_R2,random_forest_RMSE,random_seed,random_forest_seed]
  14. for i in range(len(excel_write_content)):
  15. exec("excel_write_sheet.cell(max_row+1,i+1).value=excel_write_content[i]")
  16. excel_file.save(write_excel_path)

1.5 决策树可视化

  这一部分我们借助DOT这一图像描述语言,进行随机森林算法中决策树的绘制。

  1. # Draw decision tree visualizing plot
  2. random_forest_tree=random_forest_model.estimators_[5]
  3. export_graphviz(random_forest_tree,out_file=tree_graph_dot_path,
  4. feature_names=train_X_column_name,rounded=True,precision=1)
  5. (random_forest_graph,)=pydot.graph_from_dot_file(tree_graph_dot_path)
  6. random_forest_graph.write_png(tree_graph_png_path)

  其中,estimators_[5]是指整个随机森林算法中的第6棵树(下标是从0开始的),换句话说我们就是从很多的树(具体树的个数就是前面提到的超参数n_estimators)中抽取了找一个来画图,做一个示范。如下图所示。

  可以看到,单单是这一棵树就已经非常非常庞大了。我们将上图其中最顶端(也就是最上方的节点——根节点)部分放大,就可以看见每一个节点对应的信息。如下图

  在这里提一句,上图根节点中有一个samples=151,但是我的样本总数是315个,为什么这棵树的样本个数不是全部的样本个数呢?

  其实这就是随机森林的内涵所在:随机森林的每一棵树的输入数据(也就是该棵树的根节点中的数据),都是随机选取的(也就是上面我们说的利用Bagging策略中的Bootstrap进行随机抽样),最后再将每一棵树的结果聚合起来(聚合这个过程就是Aggregation,我们常说的Bagging其实就是BootstrapAggregation的合称),形成随机森林算法最终的结果。

1.6 变量重要性分析

  在这里,我们进行变量重要性的分析,并以图的形式进行可视化。

  1. # Calculate the importance of variables
  2. random_forest_importance=list(random_forest_model.feature_importances_)
  3. random_forest_feature_importance=[(feature,round(importance,8))
  4. for feature, importance in zip(train_X_column_name,random_forest_importance)]
  5. random_forest_feature_importance=sorted(random_forest_feature_importance,key=lambda x:x[1],reverse=True)
  6. plt.figure(3)
  7. plt.clf()
  8. importance_plot_x_values=list(range(len(random_forest_importance)))
  9. plt.bar(importance_plot_x_values,random_forest_importance,orientation='vertical')
  10. plt.xticks(importance_plot_x_values,train_X_column_name,rotation='vertical')
  11. plt.xlabel('Variable')
  12. plt.ylabel('Importance')
  13. plt.title('Variable Importances')

  得到图像如下所示。这里是由于我的特征数量(自变量数量)过多,大概有150多个,导致横坐标的标签(也就是自变量的名称)都重叠了;大家一般的自变量个数都不会太多,就不会有问题~

  以上就是全部的代码分段介绍~

2 完整代码

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sun Mar 21 22:05:37 2021
  4. @author: fkxxgis
  5. """
  6. import pydot
  7. import numpy as np
  8. import pandas as pd
  9. import scipy.stats as stats
  10. import matplotlib.pyplot as plt
  11. from sklearn import metrics
  12. from openpyxl import load_workbook
  13. from sklearn.tree import export_graphviz
  14. from sklearn.ensemble import RandomForestRegressor
  15. # Attention! Data Partition
  16. # Attention! One-Hot Encoding
  17. train_data_path='G:/CropYield/03_DL/00_Data/AllDataAll_Train.csv'
  18. test_data_path='G:/CropYield/03_DL/00_Data/AllDataAll_Test.csv'
  19. write_excel_path='G:/CropYield/03_DL/05_NewML/ParameterResult_ML.xlsx'
  20. tree_graph_dot_path='G:/CropYield/03_DL/05_NewML/tree.dot'
  21. tree_graph_png_path='G:/CropYield/03_DL/05_NewML/tree.png'
  22. random_seed=44
  23. random_forest_seed=np.random.randint(low=1,high=230)
  24. # Data import
  25. '''
  26. column_name=['EVI0610','EVI0626','EVI0712','EVI0728','EVI0813','EVI0829','EVI0914','EVI0930','EVI1016',
  27. 'Lrad06','Lrad07','Lrad08','Lrad09','Lrad10',
  28. 'Prec06','Prec07','Prec08','Prec09','Prec10',
  29. 'Pres06','Pres07','Pres08','Pres09','Pres10',
  30. 'SIF161','SIF177','SIF193','SIF209','SIF225','SIF241','SIF257','SIF273','SIF289',
  31. 'Shum06','Shum07','Shum08','Shum09','Shum10',
  32. 'Srad06','Srad07','Srad08','Srad09','Srad10',
  33. 'Temp06','Temp07','Temp08','Temp09','Temp10',
  34. 'Wind06','Wind07','Wind08','Wind09','Wind10',
  35. 'Yield']
  36. '''
  37. train_data=pd.read_csv(train_data_path,header=0)
  38. test_data=pd.read_csv(test_data_path,header=0)
  39. # Separate independent and dependent variables
  40. train_Y=np.array(train_data['Yield'])
  41. train_X=train_data.drop(['ID','Yield'],axis=1)
  42. train_X_column_name=list(train_X.columns)
  43. train_X=np.array(train_X)
  44. test_Y=np.array(test_data['Yield'])
  45. test_X=test_data.drop(['ID','Yield'],axis=1)
  46. test_X=np.array(test_X)
  47. # Build RF regression model
  48. random_forest_model=RandomForestRegressor(n_estimators=200,random_state=random_forest_seed)
  49. random_forest_model.fit(train_X,train_Y)
  50. # Predict test set data
  51. random_forest_predict=random_forest_model.predict(test_X)
  52. random_forest_error=random_forest_predict-test_Y
  53. # Draw test plot
  54. plt.figure(1)
  55. plt.clf()
  56. ax=plt.axes(aspect='equal')
  57. plt.scatter(test_Y,random_forest_predict)
  58. plt.xlabel('True Values')
  59. plt.ylabel('Predictions')
  60. Lims=[0,10000]
  61. plt.xlim(Lims)
  62. plt.ylim(Lims)
  63. plt.plot(Lims,Lims)
  64. plt.grid(False)
  65. plt.figure(2)
  66. plt.clf()
  67. plt.hist(random_forest_error,bins=30)
  68. plt.xlabel('Prediction Error')
  69. plt.ylabel('Count')
  70. plt.grid(False)
  71. # Verify the accuracy
  72. random_forest_pearson_r=stats.pearsonr(test_Y,random_forest_predict)
  73. random_forest_R2=metrics.r2_score(test_Y,random_forest_predict)
  74. random_forest_RMSE=metrics.mean_squared_error(test_Y,random_forest_predict)**0.5
  75. print('Pearson correlation coefficient is {0}, and RMSE is {1}.'.format(random_forest_pearson_r[0],
  76. random_forest_RMSE))
  77. # Save key parameters
  78. excel_file=load_workbook(write_excel_path)
  79. excel_all_sheet=excel_file.sheetnames
  80. excel_write_sheet=excel_file[excel_all_sheet[0]]
  81. excel_write_sheet=excel_file.active
  82. max_row=excel_write_sheet.max_row
  83. excel_write_content=[random_forest_pearson_r[0],random_forest_R2,random_forest_RMSE,random_seed,random_forest_seed]
  84. for i in range(len(excel_write_content)):
  85. exec("excel_write_sheet.cell(max_row+1,i+1).value=excel_write_content[i]")
  86. excel_file.save(write_excel_path)
  87. # Draw decision tree visualizing plot
  88. random_forest_tree=random_forest_model.estimators_[5]
  89. export_graphviz(random_forest_tree,out_file=tree_graph_dot_path,
  90. feature_names=train_X_column_name,rounded=True,precision=1)
  91. (random_forest_graph,)=pydot.graph_from_dot_file(tree_graph_dot_path)
  92. random_forest_graph.write_png(tree_graph_png_path)
  93. # Calculate the importance of variables
  94. random_forest_importance=list(random_forest_model.feature_importances_)
  95. random_forest_feature_importance=[(feature,round(importance,8))
  96. for feature, importance in zip(train_X_column_name,random_forest_importance)]
  97. random_forest_feature_importance=sorted(random_forest_feature_importance,key=lambda x:x[1],reverse=True)
  98. plt.figure(3)
  99. plt.clf()
  100. importance_plot_x_values=list(range(len(random_forest_importance)))
  101. plt.bar(importance_plot_x_values,random_forest_importance,orientation='vertical')
  102. plt.xticks(importance_plot_x_values,train_X_column_name,rotation='vertical')
  103. plt.xlabel('Variable')
  104. plt.ylabel('Importance')
  105. plt.title('Variable Importances')

  至此,大功告成。

Python实现随机森林RF并对比自变量的重要性的更多相关文章

  1. 用Python实现随机森林算法,深度学习

    用Python实现随机森林算法,深度学习 拥有高方差使得决策树(secision tress)在处理特定训练数据集时其结果显得相对脆弱.bagging(bootstrap aggregating 的缩 ...

  2. python实现随机森林、逻辑回归和朴素贝叶斯的新闻文本分类

    实现本文的文本数据可以在THUCTC下载也可以自己手动爬虫生成, 本文主要参考:https://blog.csdn.net/hao5335156/article/details/82716923 nb ...

  3. 随机森林RF、XGBoost、GBDT和LightGBM的原理和区别

    目录 1.基本知识点介绍 2.各个算法原理 2.1 随机森林 -- RandomForest 2.2 XGBoost算法 2.3 GBDT算法(Gradient Boosting Decision T ...

  4. Python中随机森林的实现与解释

    使用像Scikit-Learn这样的库,现在很容易在Python中实现数百种机器学习算法.这很容易,我们通常不需要任何关于模型如何工作的潜在知识来使用它.虽然不需要了解所有细节,但了解机器学习模型是如 ...

  5. 【机器学习】随机森林RF

    随机森林(RF, RandomForest)包含多个决策树的分类器,并且其输出的类别是由个别树输出的类别的众数而定.通过自助法(boot-strap)重采样技术,不断生成训练样本和测试样本,由训练样本 ...

  6. Bagging与随机森林(RF)算法原理总结

    Bagging与随机森林算法原理总结 在集成学习原理小结中,我们学习到了两个流派,一个是Boosting,它的特点是各个弱学习器之间存在依赖和关系,另一个是Bagging,它的特点是各个弱学习器之间没 ...

  7. 随机森林RF

    bagging 随机森林顾名思义,是用随机的方式建立一个森林,森林里面有很多的决策树组成,随机森林的每一棵决策树之间是没有关联的.在得到森林之后,当有一个新的输 入样本进入的时候,就让森林中的每一棵决 ...

  8. python的随机森林模型调参

    一.一般的模型调参原则 1.调参前提:模型调参其实是没有定论,需要根据不同的数据集和不同的模型去调.但是有一些调参的思想是有规律可循的,首先我们可以知道,模型不准确只有两种情况:一是过拟合,而是欠拟合 ...

  9. Python之随机森林实战

    代码实现: # -*- coding: utf-8 -*- """ Created on Tue Sep 4 09:38:57 2018 @author: zhen &q ...

  10. python spark 随机森林入门demo

    class pyspark.mllib.tree.RandomForest[source] Learning algorithm for a random forest model for class ...

随机推荐

  1. python学习——查找计算机中的文件

    # import os # # path = 'C:/Users/admin/Desktop/images' # files = os.listdir(path) # # for f in files ...

  2. kubeedge的云边协同通道

    1. CloudHub安全认证流程 2. EdgeHub安全认证流程 3. Edged节点纳管

  3. Go语言核心36讲40

    我相信,经过上一次的学习,你已经对strings.Builder和strings.Reader这两个类型足够熟悉了. 我上次还建议你去自行查阅strings代码包中的其他程序实体.如果你认真去看了,那 ...

  4. 详解Native Memory Tracking之追踪区域分析

    摘要:本篇图文将介绍追踪区域的内存类型以及 NMT 无法追踪的内存. 本文分享自华为云社区<[技术剖析]17. Native Memory Tracking 详解(3)追踪区域分析(二)> ...

  5. 简单使用Nginx反向代理和负载均衡

    配置文件主要是三点: events . http . server 配置反向代理和负载均衡策略 #配置tomcat的IP地址和访问端口||负载均衡:权重就是比例 upstream guotong { ...

  6. springboot +mybatis (@autowried 注入mapper :爆红)

    问题描述:Could not autowire. No beans of XXXXmapper' type found 问题相关页面: 解决方式一:@mapper  接口计入@Repository 解 ...

  7. java面试题-线程

    简述线程.程序.进程的基本概念.以及他们之间关系是什么? 系统运行程序到停止就是一个进程创建到消亡的过程,而线程则是进程的更小单位 线程有哪些基本状态? 初始,运行中,等待,阻塞,超时,终止1 关注公 ...

  8. 纷繁复杂见真章,华为云产品需求管理利器CodeArts Req解读

    摘要:到底什么是需求?又该如何做好需求管理? 本文分享自华为云社区<纷繁复杂见真章,华为云产品需求管理利器 CodeArts Req 解读>,作者:华为云头条 . 2022 年 8 月,某 ...

  9. python Flask 操作数据库

    Flask数据库 转载:Flask数据库 - 苦行僧95 - 博客园 (cnblogs.com) Flask-SQLAlchemy Flask-SQLAlchemy是在Flask中操作关系型数据库的拓 ...

  10. python进阶之路5之流程控制(垃圾回收机制)

    垃圾回收机制 """ 有一些语言,内存空间的申请和释放都需要程序员自己写代码才可以完成 但是python却不需要 通过垃圾回收机制自动管理 ""&qu ...