天气最高温度预测任务

我们要完成三项任务:

  • 使用随机森林算法完成基本建模任务

基本任务需要我们处理数据,观察特征,完成建模并进行可视化展示分析

  • 观察数据量与特征个数对结果影响

在保证算法一致的前提下,加大数据个数,观察结果变换。重新考虑特征工程,引入新特征后观察结果走势。

  • 对随机森林算法进行调参,找到最合适的参数

掌握机器学习中两种经典调参方法,对当前模型进行调节

# 数据读取
import pandas as pd
features = pd.read_csv('data/temps.csv')
features.head()


数据表中

  • year,moth,day,week分别表示的具体的时间
  • temp_2:前天的最高温度值
  • temp_1:昨天的最高温度值
  • average:在历史中,每年这一天的平均最高温度值
  • actual:这就是我们的标签值了,当天的真实最高温度
  • friend:这一列可能是凑热闹的,你的朋友猜测的可能值,咱们不管它就好了
print('数据维度:',features.shape)
features.describe()

数据维度: (348, 9)

其中包括了各个列的数量,如果有缺失数据,数量就有所减少,这里因为并不存在缺失值,所以各个列的数量值就都是348了,均值,标准差,最大最小值等指标在这里就都显示出来了。
对于时间数据,我们也可以进行一些转换,目的就是有些工具包在绘图或者计算的过程中,需要标准的时间格式:

# 处理时间数据
import datetime
# 分别得到年月日
years = features['year']
months = features['month']
days = features['day']
# 转化成datetime格式
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[:5])

[datetime.datetime(2016, 1, 1, 0, 0), datetime.datetime(2016, 1, 2, 0, 0), datetime.datetime(2016, 1, 3, 0, 0), datetime.datetime(2016, 1, 4, 0, 0), datetime.datetime(2016, 1, 5, 0, 0)]

数据展示

# 准备画图
import matplotlib.pyplot as plt
%matplotlib inline
# 指定默认风格
plt.style.use('fivethirtyeight')
# 创建子图与设置布局
fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2,ncols=2,figsize = (10,10))
fig.autofmt_xdate(rotation = 45)
# 标签值
ax1.plot(dates,features['actual'])
ax1.set_xlabel('')
ax1.set_ylabel('Temperature')
ax1.set_title('Max Temp')
# 昨天
ax2.plot(dates,features['actual'])
ax2.set_xlabel('')
ax2.set_ylabel('Temperature')
ax2.set_title('Previous Max Temp')
# 前天
ax3.plot(dates,features['temp_2'])
ax3.set_xlabel('Date')
ax3.set_ylabel('Temperature')
ax3.set_title('Two Days Prior Max Temp')
# 我的黑驴朋友
ax4.plot(dates,features['friend'])
ax4.set_xlabel('Date')
ax4.set_ylabel('Temperature')
ax4.set_title('Donkey Estimate')

数据预处理

One-Hot Encoding

原始数据:

week
Mon
Tue
Wed
Thu
Fri

编码转换后:

Mon Tue Wed Thu Fri
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
# 独热编码
print(features.dtypes)
features = pd.get_dummies(features)
print('Shape of features after one-hot encoding:',features.shape)
features.head(5)

year int64
month int64
day int64
week object
temp_2 int64
temp_1 int64
average float64
actual int64
friend int64
dtype: object
Shape of features after one-hot encoding: (348, 15)

标签与数据格式转换

# 数据与标签
import numpy as np
#标签
labels = np.array(features['actual'])
# 在特征中去掉标签
features = features.drop('actual',axis=1)
# 名字单独保存一份,以备后患
features_list = list(features.columns)
# 转换成合适的格式
features = np.array(features)

训练集与测试集

# 数据集划分
from sklearn.model_selection import train_test_split
train_features,test_features,train_labels,test_labels = train_test_split(features,labels,test_size=0.25,random_state=42)
print('训练集特征维度:',train_features.shape)
print('训练集标签维度:',train_labels.shape)
print('测试集特征维度:',test_features.shape)
print('测试集标签维度:',test_labels.shape)

训练集特征维度: (261, 14)
训练集标签维度: (261,)
测试集特征维度: (87, 14)
测试集标签维度: (87,)

建立一个基础的随机森林模型

万事俱备,我们可以来建立随机森林模型啦,首先导入工具包,先建立1000个树试试吧,其他参数先用默认值,之后我们会再深入到调参任务中:

# 导入算法
from sklearn.ensemble import RandomForestRegressor
# 建模
rf = RandomForestRegressor(n_estimators = 1000,random_state=42)
# 训练
rf.fit(train_features,train_labels)

测试

# 预测结果
predictions = rf.predict(test_features)
# 计算误差
errors = abs(predictions - test_labels)
# mean absolute percentage error(MAPE)
mape = 100 * (errors / test_labels)
print('MAPE:',np.mean(mape))

MAPE指标

可视化展示树

先安装:graphviz

# 导入所需工具包
from sklearn.tree import export_graphviz
import pydot
# 拿到其中地一棵树
tree = rf.estimators_[5]
# 导出成dot文件
export_graphviz(tree,out_file = 'tree.dot',feature_names = features_list,rounded = True,precision = 1)
# 绘图
(graph,) = pydot.graph_from_dot_file('tree.dot')
# 展示
graph.write_png('tree.png')


还是小一点吧。。。

# 限制一下树模型
rf_small = RandomForestRegressor(n_estimators=10, max_depth = 3, random_state=42)
rf_small.fit(train_features, train_labels)# 提取一颗树
tree_small = rf_small.estimators_[5]# 保存
export_graphviz(tree_small, out_file = 'small_tree.dot', feature_names = feature_list, rounded = True, precision = 1)(graph, ) = pydot.graph_from_dot_file('small_tree.dot')graph.write_png('small_tree.png');

特征重要性

# 得到特征重要度
importances = list(rf.feature_importances_)
# 转换格式
feature_importances = [(feature,round(importance,2))for feature,importance in zip(features_list,importances)]
# 排序
feature_importances = sorted(feature_importances,key = lambda x:x[1],reverse = True)
# 对应进行打印
[print('Variable:{:20} Importance:{}'.format(*pair)) for pair in feature_importances]

Variable:temp_1 Importance:0.7
Variable:average Importance:0.19
Variable:day Importance:0.03
Variable:temp_2 Importance:0.02
Variable:friend Importance:0.02
Variable:month Importance:0.01
Variable:year Importance:0.0
Variable:week_Fri Importance:0.0
Variable:week_Mon Importance:0.0
Variable:week_Sat Importance:0.0
Variable:week_Sun Importance:0.0
Variable:week_Thurs Importance:0.0
Variable:week_Tues Importance:0.0
Variable:week_Wed Importance:0.0

用最重要的特征再来试试

# 选择最重要的那两个特征来试一试
rf_most_important = RandomForestRegressor(n_estimators = 1000,random_state = 42)
# 拿到这两个特征
important_indices = [features_list.index('temp_1'),features_list.index('average')]
train_important = train_features[:,important_indices]
test_important = test_features[:,important_indices]
# 重新训练模型
rf_most_important.fit(train_important,train_labels)
# 预测结果
predictions = rf_most_important.predict(test_important)
errors = abs(predictions-test_labels)
# 评估结果
mape = np.mean(100 * (errors / test_labels))
print('mape',mape)

mape 6.229055723613811

# 转换成list格式
x_values = list(range(len(importances)))
# 绘图
plt.bar(x_values,importances)
# x轴名字
plt.xticks(x_values,features_list,rotation = 'vertical')
# 图名与标签
plt.ylabel('Importance')
plt.xlabel('Variable')
plt.title('Variable Importances')

预测值与真实值之间的差异

# 日期数据
months = features[:,features_list.index('month')]
days = features[:,features_list.index('day')]
years = features[:,features_list.index('year')]
# 转换成日期格式
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]
# 创建一个表格来存日期和对应的数值
true_data = pd.DataFrame(data = {'date':dates,'actual':labels})
# 同理,再创建一个来存日期和对应的模型预测值
months = test_features[:,features_list.index('month')]
days = test_features[:,features_list.index('day')]
years = test_features[:,features_list.index('year')]
test_dates = [str(int(year))+'-'+str(int(month))+'-'+str(int(day)) for year,month,day in zip(years,months,days)]
test_dates = [datetime.datetime.strptime(date,'%Y-%m-%d') for date in test_dates]
predictions_data = pd.DataFrame(data = {'date':test_dates,'prediction':predictions})
# 真实值
plt.plot(true_data['date'],true_data['actual'],'b-',label = 'actual')
# 预测值
plt.plot(predictions_data['date'],predictions_data['prediction'],'ro',label = 'prediction')
plt.xticks(rotation = '60')
plt.legend()
# 图名
plt.xlabel('Date')
plt.ylabel('Maximum Temperature (F)')
plt.title('Actual and Predicted Values')


看起来还可以,这个走势我们的模型已经基本能够掌握了,接下来我们要再深入到数据中了,考虑几个问题:
1.如果可以利用的数据量增大,会对结果产生什么影响呢?
2.加入新的特征会改进模型效果吗?此时的时间效率又会怎样?

唐宇迪机器学习课程笔记:随机森林相关推荐

  1. 唐宇迪机器学习课程笔记:逻辑回归之信用卡检测任务

    信用卡欺诈检测 基于信用卡交易记录数据建立分类模型来预测哪些交易记录是异常的哪些是正常的. 任务流程: 加载数据,观察问题 针对问题给出解决方案 数据集切分 评估方法对比 逻辑回归模型 建模结果分析 ...

  2. 唐宇迪机器学习课程数据集_最受欢迎的数据科学和机器学习课程-2020年8月

    唐宇迪机器学习课程数据集 There are a lot of great online resources and websites on data science and machine lear ...

  3. 唐宇迪机器学习之离职预测

    最近在看唐宇迪机器学习视频,这个视频我觉得很不错,可是我资源有限,有的视频没有配套的资料.数据集或者是代码,但还是可以看视频了解其中的一些知识点. 项目介绍 该项目是通过员工对公司的满意程度.公司对员 ...

  4. 唐宇迪机器学习实战课程笔记(全)

    1. 线性回归 1.1线性回归理论 1.2线性回归实战 2.训练调参基本功(线性回归.岭回归.Lasso回归) 2.1 线性回归模型实现 2.2不同GD策略对比 2.3多项式曲线回归 2.4过拟合和欠 ...

  5. python数据项目分析实战技法_《Python数据分析与机器学习实战-唐宇迪》读书笔记第9章--随机森林项目实战——气温预测(1/2)...

    第9章--随机森林项目实战--气温预测(1/2) 第8章已经讲解过随机森林的基本原理,本章将从实战的角度出发,借助Python工具包完成气温预测任务,其中涉及多个模块,主要包含随机森林建模.特征选择. ...

  6. python天气数据分析论文_《Python数据分析与机器学习实战-唐宇迪》读书笔记第9章--随机森林项目实战——气温预测(2/2)...

    第9章--随机森林项目实战--气温预测(2/2) 第8章已经讲解过随机森林的基本原理,本章将从实战的角度出发,借助Python工具包完成气温预测任务,其中涉及多个模块,主要包含随机森林建模.特征选择. ...

  7. python画一片树叶的故事_《Python数据分析与机器学习实战-唐宇迪》读书笔记第7章--决策树...

    第7章决策树 决策树算法是机器学习中最经典的算法之一.大家可能听过一些高深的算法,例如在竞赛中大杀四方的Xgboost.各种集成策略等,其实它们都是基于树模型来建立的,掌握基本的树模型后,再去理解集成 ...

  8. YOLO-V4 论文学习+唐宇迪博士课程学习笔记

    论文主要贡献: 1.利用单GPU即可训练一个目标检测器. 2.验证了Bag-of-Freebies 和 Bag-of-Specials方法在训练目标检测器当中的作用. 3.对包括CBN.PAN.SAM ...

  9. 唐宇迪​​机器学习实战——梯度下降求解逻辑回归(理论基础+源代码实现)

    问题的提出 符号问题,这里的lg就是指log2,你的理解是正确的!在计算机科学中有些符号的使用跟我们在数学中使用的有区别.比如有时候log用来表示自然对数(以e为底数).希望对你有帮助! 首先计算机科 ...

  10. 唐宇迪强化学习笔记之项目实战(flabby bird)

    强化学习: 学习系统没有像很多其它形式的机器学习方法一样被告知应该做出什么行为,必须在尝试了之后才能发现哪些行为会导致奖励的最大化,当前的行为可能不仅仅会影响即时奖励,还会影响下一步的奖励以及后续的所 ...

最新文章

  1. python调用c#注意事项_python 调用c# 超级直接示例
  2. 如何使用阿里云服务器
  3. S4:装饰模式 Decorator
  4. 设计模式--Builder
  5. [crypto]-05.1-PKCS PKCS#1 PKCS#7 PKCS#11的介绍
  6. bzoj 2705: [SDOI2012]Longge的问题——欧拉定理
  7. delphi 函数内创建对象 释放_JavaScript 的函数底层运行机制
  8. Dapr微服务应用开发系列5:发布订阅构建块
  9. jq取第一个子元素为select_【转】jquery如何获取第一个或最后一个子元素?
  10. Java面试你必须要知道的那些知识,面试建议
  11. Linux下查看txt文档
  12. R语言快速入门课——结合各种生物信息学及医学案例,使R语言快速入门——R软件及Rstudio下载(同步课程正在更新中)
  13. RS232RS485协议原理和应用
  14. CRUISE软件测试工程师,CruiseControl.NET配置
  15. Charles4.1最新版破解
  16. 360 error.html,360浏览器出错了怎么办
  17. Html5用Canvas制作绘图板最终
  18. java论文word_JAVA课程实践报告 基于web的点餐系统毕业设计word格式
  19. python爬虫网易云音乐评论最多的歌_Python3实战之爬虫抓取网易云音乐的热门评论...
  20. js动态生成html表格

热门文章

  1. 拳王公社:网络操盘手必备的400款新媒体运营工具大全!
  2. 【基础知识】~ 集成电路设计流程,以及各阶段所使用的EDA工具
  3. python解题工程力学_工程力学学习指导与解题指南(普通高等教育十三五规划教材)...
  4. Excel函数实战技巧精粹(二)常用函数之VLOOKUP全解
  5. css只设置背景图片半透明,css 设置背景色或图片半透明的方法(图文)
  6. 互联网公司的敏捷开发是怎么回事?这一份软件工程书单送给你!
  7. linux安装java步骤
  8. cmd ntsd命令
  9. 史蒂夫·乔布斯传txt下载
  10. 从零开始学androidNotification通知.四十四.