在这个案例中:

1. datetime.datetime.strptime(data, '%Y-%m-%d') # 由字符串格式转换为日期格式

2. pd.get_dummies(features)  # 将数据中的文字标签转换为one-hot编码形式,增加了特征的列数

3. rf.feature_importances 探究了随机森林样本特征的重要性,对其进行排序后条形图

4.fig.autofmt_xdate(rotation=60)  # 对图中的X轴标签进行60的翻转

代码:

第一步:数据读取,通过.describe() 查看数据是否存在缺失值的情况

第二步:对年月日特征进行字符串串接,使用datetime.datetime.strptime(), 获得日期格式作为X轴的标签

第三步:对里面的几个温度特征做条形图,fig.autofmt_xdate(rotation=60)设置日期标签的旋转角度,plt.style.use('fivethirtyeight') 设置画风

第四步:使用pd.get_dummies(features) 将特征中文字类的标签转换为one-hot编码形式,增加了特征的维度

第五步:提取数据的特征和样本标签,转换为np.array格式

第六步:使用train_test_split 将特征和标签分为训练集和测试集

第七步:构建随机森林模型进行模型的训练和预测

第八步:进行随机森林的可视化

第九步:使用rf.feature_importances_计算出各个特征的重要性,进行排序,然后做条形图

第十步:根据第九步求得的特征重要性的排序结果,我们选用前两个特征建立模型和预测

第十一步:对模型的预测结果画直线图plot和散点图scatter,对于plot我们需要根据时间进行排序

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import datetime
  5.  
  6. # 第一步提取数据
  7. features = pd.read_csv('data/temps.csv')
  8. print(features.shape)
  9. print(features.columns)
  10. # 使用feature.describe() # 观察数据是否存在缺失值
  11. print(features.describe())
  12.  
  13. # 第二步:我们将year,month,day特征组合成一个dates特征,作为画图的标签值比如2016-02-01
  14.  
  15. years = features['year']
  16. months = features['month']
  17. days = features['day']
  18.  
  19. # datetime.datetime.strptime() 将字符串转换为日期类型
  20. dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
  21. dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
  22. print(dates[0:5])
  23.  
  24. # 第三步进行画图操作
  25. # 设置画图风格
  26. plt.style.use('fivethirtyeight')
  27.  
  28. # 使用plt.subplots画出多副图
  29. fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2, figsize=(12, 12))
  30. # 使得标签进行角度翻转
  31. fig.autofmt_xdate(rotation=60)
  32.  
  33. ax1.plot(dates, features['temp_2'], linewidth=4)
  34. ax1.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('pred two temperature')
  35.  
  36. ax2.plot(dates, features['temp_1'], linewidth=4)
  37. ax2.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('pred temperature')
  38.  
  39. ax3.plot(dates, features['actual'], linewidth=4)
  40. ax3.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('today temperature')
  41.  
  42. ax4.plot(dates, features['friend'], linewidth=4)
  43. ax4.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('friend temperature')
  44.  
  45. plt.show()

  1. # 第四步:pd.get_dummies() 来对特征中不是数字的特征进行one-hot编码
  2. features = pd.get_dummies(features)
  3.  
  4. # 第五步:把数据分为特征和标签
  5.  
  6. y = np.array(features['actual'])
  7. X = features.drop('actual', axis=1)
  8. feature_names = list(X.columns)
  9. X = np.array(X)
  10.  
  11. # 第六步: 使用train_test_split 对数据进行拆分
  12. from sklearn.model_selection import train_test_split
  13.  
  14. train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.25, random_state=42)
  15.  
  16. # 第七步:建立随机森林的模型进行预测
  17. from sklearn.ensemble import RandomForestRegressor
  18.  
  19. rf = RandomForestRegressor(n_estimators=1000)
  20. rf.fit(train_X, train_y)
  21. pred_y = rf.predict(test_X)
  22.  
  23. # MSE指标通过真实值-预测值的绝对值求平均值
  24. MSE = round(abs(pred_y - test_y).mean(), 2)
  25.  
  26. # MAPE指标通过 1 - abs(误差)/真实值来表示
  27. error = abs(pred_y - test_y)
  28.  
  29. MAPE = round(np.mean((1 - error / test_y) * 100), 2)
  30.  
  31. print(MSE, MAPE)
  32.  
  33. # 第八步进行随机森林的可视化展示
  34.  
  35. # from sklearn.tree import export_graphviz
  36. # import pydot #pip install pydot
  37. #
  38. # # Pull out one tree from the forest
  39. # tree = model.estimators_[5]
  40. #
  41. # # Export the image to a dot file
  42. # export_graphviz(tree, out_file = 'tree.dot', feature_names = feature_names, rounded = True, precision = 1)
  43. #
  44. # # Use dot file to create a graph
  45. # (graph, ) = pydot.graph_from_dot_file('tree.dot')
  46. # graph.write_png('tree.png');
  47. # print('The depth of this tree is:', tree.tree_.max_depth)
  48. #
  49. # # 限制树的深度重新画图
  50. # rf_small = RandomForestRegressor(n_estimators=10, max_depth = 3, random_state=42)
  51. # rf_small.fit(train_x,train_y)
  52. #
  53. # # Extract the small tree
  54. # tree_small = rf_small.estimators_[5]
  55. #
  56. # # Save the tree as a png image
  57. # export_graphviz(tree_small, out_file = 'small_tree.dot', feature_names = feature_names, rounded = True, precision = 1)
  58. #
  59. # (graph, ) = pydot.graph_from_dot_file('small_tree.dot')
  60. #
  61. # graph.write_png('small_tree.png')
  62.  
  63. #第九步:探讨随机森林特征的重要性
  64. features_importances = rf.feature_importances_
  65. features_importance_pairs = [(feature_name, features_importance) for feature_name, features_importance in
  66. zip(feature_names, features_importances)]
  67. # 对里面的特征进行排序操作
  68. features_importance_pairs = sorted(features_importance_pairs, key=lambda x: x[1], reverse=True)
  69. features_importance_name = [name[0] for name in features_importance_pairs]
  70. features_importance_val = [name[1] for name in features_importance_pairs]
  71.  
  72. figure = plt.figure()
  73. plt.bar(range(len(features_importance_name)), features_importance_val, orientation='vertical')
  74. plt.xticks(range(len(features_importance_name)), features_importance_name, rotation='vertical')
  75. plt.show()

  1. # 第十步:通过上述的作图,我们可以发现前两个特征很重要,因此我们只选用前两个特征作为训练数据
  2.  
  3. X = features.drop('actual', axis=1)
  4. y = np.array(features['actual'])
  5.  
  6. train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.25, random_state=42)
  7.  
  8. train_x_two = train_x[['temp_1', 'average']].values
  9. test_x_two = test_x[['temp_1', 'average']].values
  10.  
  11. rf = RandomForestRegressor(n_estimators=1000)
  12. rf.fit(train_x_two, train_y)
  13. pred_y = rf.predict(test_x_two)
  14.  
  15. # MSE指标通过真实值-预测值的绝对值求平均值
  16. MSE = round(abs(pred_y - test_y).mean(), 2)
  17.  
  18. # MAPE指标通过 1 - abs(误差)/真实值来表示
  19. error = abs(pred_y - test_y)
  20.  
  21. MAPE = round(np.mean((1 - error / test_y) * 100), 2)
  22. print(MSE, MAPE)
  23.  
  24. # 我们发现只使用两个特征也是具有差不多的结果,因此我们可以通过减少特征来增加反应的时间
  25.  
  26. fig = plt.figure()
  27.  
  28. years = test_x['year']
  29. months = test_x['month']
  30. days = test_x['day']
  31.  
  32. dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
  33. dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
  34. print(dates[0:5])
  35.  
  36. # 对真实的数据进行排序,因为需要画plot图
  37. dates_test_paris = [(date, test_) for date, test_ in zip(dates, test_y)]
  38. dates_test_paris = sorted(dates_test_paris, key=lambda x: x[0], reverse=True)
  39. dates_test_data = [x[0] for x in dates_test_paris]
  40. dates_test_val = [x[1] for x in dates_test_paris]
  41.  
  42. plt.plot(dates_test_data, dates_test_val, label='actual')
  43. plt.scatter(dates, pred_y, label='pred')
  44. plt.xticks(rotation='')
  45. plt.legend()
  46. plt.show()

机器学习入门-随机森林温度预测的案例 1.datetime.datetime.datetime(将字符串转为为日期格式) 2.pd.get_dummies(将文本标签转换为one-hot编码) 3.rf.feature_importances_(研究样本特征的重要性) 4.fig.autofmt_xdate(rotation=60) 对标签进行翻转的更多相关文章

  1. 机器学习入门-随机森林温度预测-增加样本数据 1.sns.pairplot(画出两个关系的散点图) 2.MAE(平均绝对误差) 3.MAPE(准确率指标)

    在上一个博客中,我们构建了随机森林温度预测的基础模型,并且研究了特征重要性. 在这个博客中,我们将从两方面来研究数据对预测结果的影响 第一方面:特征不变,只增加样本的数据 第二方面:增加特征数,增加样 ...

  2. 机器学习入门-随机森林预测温度-不同参数对结果的影响调参 1.RandomedSearchCV(随机参数组的选择) 2.GridSearchCV(网格参数搜索) 3.pprint(顺序打印) 4.rf.get_params(获得当前的输入参数)

    使用了RamdomedSearchCV迭代100次,从参数组里面选择出当前最佳的参数组合 在RamdomedSearchCV的基础上,使用GridSearchCV在上面最佳参数的周围选择一些合适的参数 ...

  3. 100天搞定机器学习|Day56 随机森林工作原理及调参实战(信用卡欺诈预测)

    本文是对100天搞定机器学习|Day33-34 随机森林的补充 前文对随机森林的概念.工作原理.使用方法做了简单介绍,并提供了分类和回归的实例. 本期我们重点讲一下: 1.集成学习.Bagging和随 ...

  4. 使用基于Apache Spark的随机森林方法预测贷款风险

    使用基于Apache Spark的随机森林方法预测贷款风险   原文:Predicting Loan Credit Risk using Apache Spark Machine Learning R ...

  5. Python机器学习笔记——随机森林算法

    随机森林算法的理论知识 随机森林是一种有监督学习算法,是以决策树为基学习器的集成学习算法.随机森林非常简单,易于实现,计算开销也很小,但是它在分类和回归上表现出非常惊人的性能,因此,随机森林被誉为“代 ...

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

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

  7. 100天搞定机器学习|Day33-34 随机森林

    前情回顾 机器学习100天|Day1数据预处理 100天搞定机器学习|Day2简单线性回归分析 100天搞定机器学习|Day3多元线性回归 100天搞定机器学习|Day4-6 逻辑回归 100天搞定机 ...

  8. paper 84:机器学习算法--随机森林

    http://www.cnblogs.com/wentingtu/archive/2011/12/13/2286212.html中一些内容 基础内容: 这里只是准备简单谈谈基础的内容,主要参考一下别人 ...

  9. 机器学习技法-随机森林(Random Forest)

    课程地址:https://class.coursera.org/ntumltwo-002/lecture 重要!重要!重要~ 一.随机森林(RF) 1.RF介绍 RF通过Bagging的方式将许多个C ...

随机推荐

  1. linux下 mysql主从备份

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/czh0423/article/details/26720539 一.准备 用两台server做測试: ...

  2. pyotherside 试用

    pyotherside 试用 这是啥?用python写qt 步骤:安装qt: http://www.qt.io/download-open-source/#section-2安装python3:下载源 ...

  3. javacv 340使用 人脸检测例子【转载】

    Java下使用opencv进行人脸检测 工作需要,研究下人脸识别,发现opencv比较常用,尽管能检测人脸,但识别率不高,多数是用来获取摄像头的视频流的,提取里面的视频帧,实现人脸识别时通常会和其他框 ...

  4. asp.net Repeater使用例子,包括分页

    <style type="text/css">    .tab{border-collapse:collapse; margin:0 auto;}    .tab th ...

  5. g++编译后中文显示乱码解决方案

    环境:Windows 10 专业版 GCC版本:5.3.0 测试代码: #include <iostream> using namespace std; int main(int argc ...

  6. wxWidgets:消息处理流程

    首先解释下EventHandler. wxWidgets中EventHandler并不是简单的指消息(事件)处理函数,而是一个用于处理窗口系统消息的类.收到消息后,wxEventHandler会调用e ...

  7. AppScan代理扫描app/H5安全测试(没试过,记录在此)

    标签: 1.首先设置AppScan代理,设置如下:

  8. 杂项:flex (adobe flex)

    ylbtech-杂项:Flex (Adobe Flex) Flex指Adobe Flex,基于其专有的Macromedia Flash平台,它是涵盖了支持RIA(Rich Internet Appli ...

  9. Win7_64位 CHM打不开

    (2)在命令行运行regsvr32 itss.dll (3)在命令行运行regsvr32 hhctrl.ocx (4)开始--运行--输入“regedit”,打开注册表,找到以下分支: HKEY_LO ...

  10. 设置redis 密码

    redis配置密码 1.通过配置文件进行配置 yum方式安装的redis配置文件通常在/etc/redis.conf中,打开配置文件找到 [plain] view plain copy require ...