在这个案例中:

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我们需要根据时间进行排序

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime # 第一步提取数据
features = pd.read_csv('data/temps.csv')
print(features.shape)
print(features.columns)
# 使用feature.describe() # 观察数据是否存在缺失值
print(features.describe()) # 第二步:我们将year,month,day特征组合成一个dates特征,作为画图的标签值比如2016-02-01 years = features['year']
months = features['month']
days = features['day'] # datetime.datetime.strptime() 将字符串转换为日期类型
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
print(dates[0:5]) # 第三步进行画图操作
# 设置画图风格
plt.style.use('fivethirtyeight') # 使用plt.subplots画出多副图
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2, figsize=(12, 12))
# 使得标签进行角度翻转
fig.autofmt_xdate(rotation=60) ax1.plot(dates, features['temp_2'], linewidth=4)
ax1.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('pred two temperature') ax2.plot(dates, features['temp_1'], linewidth=4)
ax2.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('pred temperature') ax3.plot(dates, features['actual'], linewidth=4)
ax3.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('today temperature') ax4.plot(dates, features['friend'], linewidth=4)
ax4.set_xlabel(''), ax1.set_ylabel('temperature'), ax1.set_title('friend temperature') plt.show()

# 第四步:pd.get_dummies() 来对特征中不是数字的特征进行one-hot编码
features = pd.get_dummies(features) # 第五步:把数据分为特征和标签 y = np.array(features['actual'])
X = features.drop('actual', axis=1)
feature_names = list(X.columns)
X = np.array(X) # 第六步: 使用train_test_split 对数据进行拆分
from sklearn.model_selection import train_test_split train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.25, random_state=42) # 第七步:建立随机森林的模型进行预测
from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(n_estimators=1000)
rf.fit(train_X, train_y)
pred_y = rf.predict(test_X) # MSE指标通过真实值-预测值的绝对值求平均值
MSE = round(abs(pred_y - test_y).mean(), 2) # MAPE指标通过 1 - abs(误差)/真实值来表示
error = abs(pred_y - test_y) MAPE = round(np.mean((1 - error / test_y) * 100), 2) print(MSE, MAPE) # 第八步进行随机森林的可视化展示 # from sklearn.tree import export_graphviz
# import pydot #pip install pydot
#
# # Pull out one tree from the forest
# tree = model.estimators_[5]
#
# # Export the image to a dot file
# export_graphviz(tree, out_file = 'tree.dot', feature_names = feature_names, rounded = True, precision = 1)
#
# # Use dot file to create a graph
# (graph, ) = pydot.graph_from_dot_file('tree.dot')
# graph.write_png('tree.png');
# print('The depth of this tree is:', tree.tree_.max_depth)
#
# # 限制树的深度重新画图
# rf_small = RandomForestRegressor(n_estimators=10, max_depth = 3, random_state=42)
# rf_small.fit(train_x,train_y)
#
# # Extract the small tree
# tree_small = rf_small.estimators_[5]
#
# # Save the tree as a png image
# export_graphviz(tree_small, out_file = 'small_tree.dot', feature_names = feature_names, rounded = True, precision = 1)
#
# (graph, ) = pydot.graph_from_dot_file('small_tree.dot')
#
# graph.write_png('small_tree.png') #第九步:探讨随机森林特征的重要性
features_importances = rf.feature_importances_
features_importance_pairs = [(feature_name, features_importance) for feature_name, features_importance in
zip(feature_names, features_importances)]
# 对里面的特征进行排序操作
features_importance_pairs = sorted(features_importance_pairs, key=lambda x: x[1], reverse=True)
features_importance_name = [name[0] for name in features_importance_pairs]
features_importance_val = [name[1] for name in features_importance_pairs] figure = plt.figure()
plt.bar(range(len(features_importance_name)), features_importance_val, orientation='vertical')
plt.xticks(range(len(features_importance_name)), features_importance_name, rotation='vertical')
plt.show()

# 第十步:通过上述的作图,我们可以发现前两个特征很重要,因此我们只选用前两个特征作为训练数据

X = features.drop('actual', axis=1)
y = np.array(features['actual']) train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.25, random_state=42) train_x_two = train_x[['temp_1', 'average']].values
test_x_two = test_x[['temp_1', 'average']].values rf = RandomForestRegressor(n_estimators=1000)
rf.fit(train_x_two, train_y)
pred_y = rf.predict(test_x_two) # MSE指标通过真实值-预测值的绝对值求平均值
MSE = round(abs(pred_y - test_y).mean(), 2) # MAPE指标通过 1 - abs(误差)/真实值来表示
error = abs(pred_y - test_y) MAPE = round(np.mean((1 - error / test_y) * 100), 2)
print(MSE, MAPE) # 我们发现只使用两个特征也是具有差不多的结果,因此我们可以通过减少特征来增加反应的时间 fig = plt.figure() years = test_x['year']
months = test_x['month']
days = test_x['day'] dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
print(dates[0:5]) # 对真实的数据进行排序,因为需要画plot图
dates_test_paris = [(date, test_) for date, test_ in zip(dates, test_y)]
dates_test_paris = sorted(dates_test_paris, key=lambda x: x[0], reverse=True)
dates_test_data = [x[0] for x in dates_test_paris]
dates_test_val = [x[1] for x in dates_test_paris] plt.plot(dates_test_data, dates_test_val, label='actual')
plt.scatter(dates, pred_y, label='pred')
plt.xticks(rotation='')
plt.legend()
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. graphql 数据导入工具

    graphql 是比 比较方便的工具,但是数据导入也是一个比较重要的工具类似prisma 包含一个seed 的功能,类似docker我们使用mysql 数据库的initdb.d,但是那个基本上就 是添 ...

  2. Oracle删除归档文件

    归档文件过大,会导致数据库出现异常,无法登陆. 1.D盘下新建一个delete_arch.txt文件 connect target / run { DELETE ARCHIVELOG ALL COMP ...

  3. 使用 php 7.3.0 官网的压缩包安装 FastAdmin

    使用 php 7.3.0 官网的压缩包安装 FastAdmin 直接从 php.net 官网下载了一 php7.3.0 的压缩包,解压到 c:/temp/php73 目录. 将 c:/temp/php ...

  4. 从操作系统rm数据文件后,利用句柄与rman恢复的过程。(已验证)

    以下操作代码的流程是配的,但是相应的文件名,啥的   必须改动. 故障现象 数据文件被误删除 具体情况 接到反馈说,数据文件data20120512.dbf被误删除,需要恢复 数据库提示 ERROR ...

  5. vue-cli 中的静态资源处理

    你会注意到在项目结构上我们有静态资源两个目录:src/assets 和 static/.它们之间有什么区别? 1. 通过webpack处理的资源 要回答这个问题,我们首先需要了解webpack如何处理 ...

  6. 解决webpack不是内部命令

    在指定路径下安装webpack npm install webpack --save-dev 但是报”不是内部命令错误" 解决方法:安装全局webpack   npm install web ...

  7. Angular 4 路由守卫

    路由守卫 只有当用户已经登录并拥有某些权限时才能进入某些路由 一个有多个表单组成的向导,如注册流程,用户只有在当前组件的组件中填写了满足要求的信息才可以导航到下一个路由 当用户未执行保存操作而试图离开 ...

  8. script 标签的defer,async的作用,及拓展浏览器多线程,DOMContentLoaded

    前端优化有一点就是优化js的执行时机,一般做法是将script放置于body的结束标签,以避免加载执行js 文件导致页面渲染阻塞的问题这种做法确实能防止页面阻塞,但是在页面渲染完成之后才去加载js文件 ...

  9. TroubleShoot: Enable Developer Mode in Windows 10 Insider Preview Build 10074

    There is a known issue in Windows 10 Insider Preview build 10074 (see here). Developers cannot enabl ...

  10. 知识点查缺补漏贴03:单机最大进程数,线程数和Socket连接数

    前言: 参加Unix/Linux相关高级研发职位时,是否经常会被文档,单机允许最大进程数.线程数和Socket连接数,而你却感到束手无措呢?本文给你一个最为详细的答案. 一.最大进程数 运行Linux ...