在上一个博客中,我们构建了随机森林温度预测的基础模型,并且研究了特征重要性。

在这个博客中,我们将从两方面来研究数据对预测结果的影响

第一方面:特征不变,只增加样本的数据

第二方面:增加特征数,增加样本的数据

1.sns.pairplot 画出两个变量的关系图,用于研究变量之间的线性相关性,sns.pattle([color]) 用于设置调色板, 有点像scatter_matrix

2.MSE   round(abs(pred - test_y).mean(), 2)  研究预测值与真实值之差的平均值

3.MAPE  round(100 -abs(pred-test_y)/test_y*100, 2)  (1 - 误差与真实值的比值)的平均值

代码:

第一步:载入数据

第二步:使用datetime.datetime.strptime() 将年月日进行组合,构造出日期的标签

第三步: 对数据中的温度特征进行画图

第四步:对新增的特征进行画图

第五步:sns.pairplot进行两两变量的关系画图,使用sns.pattle()生成颜色的调色板

第六步:建立随机森林模型,研究新增加的数据对预测精度的影响,不加入新增的特征

第七步:建立随机森林模型,研究新增加的数据对预测精度的影响,加入新增的特征

import datetime
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd # 第一步:导入数据
features = pd.read_csv('data/temps_extended.csv')
print(features.describe())
print(features.columns) # 第二步:使用datetime.datetime.strptime将字符串转换为日期类型
years = features['year']
months = features['month']
days = features['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] # 第三步对温度特征进行画图操作 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('pre two max') ax2.plot(dates, features['temp_1'], linewidth=4)
ax2.set_xlabel(''); ax2.set_ylabel('temperature'); ax2.set_title('pre max') ax3.plot(dates, features['actual'], linewidth=4)
ax3.set_xlabel(''); ax3.set_ylabel('temperature'); ax3.set_title('today max') ax4.plot(dates, features['friend'], linewidth=4)
ax4.set_xlabel(''); ax4.set_ylabel('temperature'); ax4.set_title('friend max') plt.show() # 第四步:对新增的特征和平均温度进行作图 fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2, figsize=(12, 12))
fig.autofmt_xdate(rotation=60) ax1.plot(dates, features['average'])
ax1.set_xlabel(''); ax1.set_ylabel('temperature'); ax1.set_title('average') ax2.plot(dates, features['ws_1'], 'r-')
ax2.set_xlabel(''); ax2.set_ylabel('temperature'); ax2.set_title('WS') ax3.plot(dates, features['prcp_1'], 'r-')
ax3.set_xlabel(''); ax3.set_ylabel('temperature'); ax3.set_title('Prcp') ax4.plot(dates, features['snwd_1'], 'ro')
ax4.set_xlabel(''); ax4.set_ylabel('temperature'); ax4.set_title('Snwd') plt.show()

  

# 第五步:使用sns.pairplot画两两关系的散点图
# 新增加季节特征,用做画图时的区分
season = []
for month in months:
if month in [12, 1, 2]:
season.append('window')
elif month in [3, 4, 5]:
season.append('spring')
elif month in [6, 7, 8]:
season.append('summer')
else:
season.append('Autumn') feature_matrix = features[['prcp_1', 'temp_1', 'average', 'actual']]
feature_matrix['season'] = season import seaborn as sns sns.set(style='ticks', color_codes=True) palette = sns.xkcd_palette(['dark blue', 'dark green', 'gold', 'orange'])
# hue表示通过什么进行分类
sns.pairplot(feature_matrix, hue='season', palette=palette, plot_kws=dict(alpha=0.7), diag_kind='kde',
diag_kws=dict(shade=True))
plt.show()

# 第六步使用增加的数据进行随机森林的建模,不添加新增的特征
feature_names = list(features.columns)
feature_indices = [feature_names.index(feature_name) for feature_name in feature_names
if feature_names not in ['ws_1', 'prcp_1', 'snwd_1']]
print(feature_indices)
# 使用pd.get_dummies 将week的文本标签转换为one-hot编码
features = pd.get_dummies(features)
# 提取特征和标签
X = features.iloc[:, feature_indices]
y = np.array(features['actual'])
X = X.drop('actual', axis=1)
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.3, random_state=42)
# 构建随机森林模型进行预测
from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(n_estimators=1000, random_state=42)
rf.fit(train_x, train_y)
pred_y = rf.predict(test_x) # 使用MAE指标
MAE = round(abs(pred_y - test_y).mean(), 2) # 使用MAPE指标
MAPE = round(((1-abs(pred_y-test_y)/test_y)*100).mean(), 2) print(MAE, MAPE) # 探讨原来数据的MAE和MAPE
# 使用pd.get_dummies 将week的文本标签转换为one-hot编码
features = pd.read_csv('data/temps.csv')
features = pd.get_dummies(features)
# 提取特征和标签
y = np.array(features['actual'])
X = features.drop('actual', axis=1)
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.3, random_state=42)
# 构建随机森林模型进行预测
from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(n_estimators=1000, random_state=42)
rf.fit(train_x, train_y)
pred_y = rf.predict(test_x) # 使用MAE指标
MAE = round(abs(pred_y - test_y).mean(), 2) # 使用MAPE指标
MAPE = round(((1-abs(pred_y-test_y)/test_y)*100).mean(), 2) print(MAE, MAPE) # 第七步: 探讨将新增加的指标也加入对数据结果的影响
features = pd.read_csv('data/temps_extended.csv')
features = pd.get_dummies(features)
# 提取特征和标签
y = np.array(features['actual'])
X = features.drop('actual', axis=1)
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.3, random_state=42)
# 构建随机森林模型进行预测
from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(n_estimators=1000, random_state=42)
rf.fit(train_x, train_y)
pred_y = rf.predict(test_x) # 使用MAE指标
MAE = round(abs(pred_y - test_y).mean(), 2) # 使用MAPE指标
MAPE = round(((1-abs(pred_y-test_y)/test_y)*100).mean(), 2) print(MAE, MAPE)

原始数据的MAE,MAPE 3.87 93.96

只增加数据量的MAE, MAPE  3.73 93.72

增加数据量增加特征的MAE,MAPE  3.71 93.76

从上面可以看出增加数据量和样本特征对结果还是能产生正面的影响

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

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

    在这个案例中: 1. datetime.datetime.strptime(data, '%Y-%m-%d') # 由字符串格式转换为日期格式 2. pd.get_dummies(features)  ...

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

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

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

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

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

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

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

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

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

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

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

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

  8. 【机器学习】随机森林(Random Forest)

    随机森林是一个最近比较火的算法 它有很多的优点: 在数据集上表现良好 在当前的很多数据集上,相对其他算法有着很大的优势 它能够处理很高维度(feature很多)的数据,并且不用做特征选择 在训练完后, ...

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

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

随机推荐

  1. day31 python学习 并发编程之多进程理论部分

    一 什么是进程 进程:正在进行的一个过程或者说一个任务.而负责执行任务则是cpu. 举例(单核+多道,实现多个进程的并发执行): 二 进程与程序的区别 程序仅仅只是一堆代码而已,而进程指的是程序的运行 ...

  2. WINDOWS FTP命令详解

    FTP命令是Internet用户使用最频繁的命令之一,不论是在DOS还是UNIX操作系统下使用FTP,都会遇到大量的FTP内部命令.熟悉并灵活应用FTP的内部命令,可以大大方便使用者,并收到事半功倍之 ...

  3. 投行的码工 Dead-end job

    发信人: icestonesy (无忧), 信区: Quant 标  题: 投行的码工怎么样? 发信站: BBS 未名空间站 (Sat May 16 23:25:00 2015, 美东) 最近看到不少 ...

  4. 百度,谷歌,360,搜狗,神马等蜘蛛IP段

    https://www.imydl.com/wzjs/5971.html 记得3月份的时候明月分享过一篇[站长必备:百度.谷歌.搜狗.360等蜘蛛常见IP地址]的文章,好像一直都受到了众多站长们的关注 ...

  5. php 图片剪切

    <?php /** * 图像裁剪 * @param $source_path 原图路径 * @param $target_width 需要裁剪的宽 * @param $target_height ...

  6. 【jmeter】jmeter之-聚合点

    集合点:简单来理解一下,虽然我们的“性能测试”理解为“多用户并发测试”,但真正的并发是不存在的,为了更真实的实现并发这感念,我们可以在需要压力的地方设置集合点, 还拿那个用户和密码的地方,每到输入用户 ...

  7. Robots.txt 编写

    搜索引擎Robots协议,是放置在网站根目录下robots.txt文本文件,在文件中可以设定搜索引擎蜘蛛爬行规则.设置搜索引擎蜘蛛Spider抓取内容规则.下面Seoer惜缘举例robots写法规则与 ...

  8. 一小时入门webpack

    webpack现在已经成为了大众化的项目必要脚手架,基本上现在的很多项目都需要webpack,由于webpack的出现glup和grunt已经完败,今天我们来说一下webpack如何使用. 首先我们需 ...

  9. 关于分布式锁Java常用技术方案

    前言:       由于在平时的工作中,线上服务器是分布式多台部署的,经常会面临解决分布式场景下数据一致性的问题,那么就要利用分布式锁来解决这些问题.      所以自己结合实际工作中的一些经验和网上 ...

  10. java操作Excel之POI(2)

    一.设置单元格对齐方式: /** * 设置单元格对齐方式 */ public static void main(String[] args) throws Exception { Workbook w ...