机器学习入门 --- 基于随机森林的气温预测(二)数据与特征对随机森林的影响

机器学习入门 — 基于随机森林的气温预测(一)使用随机森林算法完成基本建模任务 中,只用了2016年一个年份的数据来进行实验,本文将增加数据量,把 2011 - 2016 年的数据都拿进来,与原结果进行一个对比

数据展示

# 导入工具包
import pandas as pd
# 读取数据
features = pd.read_csv('data/temps_extended.csv')
features.head()

在这里插入图片描述
本数据表中:

  • year,moth,day,wek分别表示的具体的时间
  • ws_1:昨天的风速
  • prcp_1: 昨天的降水
  • snwd_1:昨天的积雪深度
  • temp_ 2:前天的最高温度值
  • temp_ 1:昨天的最高温度值
  • average: 在历史中,每年这一天的平均最高温度值
  • actual: 这就是我们的标签值了,当天的真实最高温度
  • friend: 朋友的评价

在此可以到,新的数据集中,数据规模发生了变化,数据量扩充到2191条并且加入了新的天气指标:ws_1、prcp_1、snwd_1

画图看一下新特征
# 设置整体布局
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (15,10))
fig.autofmt_xdate(rotation = 45)
# 平均最高气温
ax1.plot(dates, features['average'])
ax1.set_xlabel('')
ax1.set_ylabel('Temperature (F)')
ax1.set_title('Historical Avg Max Temp')
# 风速
ax2.plot(dates, features['ws_1'], 'r-')
ax2.set_xlabel('')
ax2.set_ylabel('Wind Speed (mph)')
ax2.set_title('Prior Wind Speed')
# 降水
ax3.plot(dates, features['prcp_1'], 'r-')
ax3.set_xlabel('Date')
ax3.set_ylabel('Precipitation (in)')
ax3.set_title('Prior Precipitation')
# 积雪
ax4.plot(dates, features['snwd_1'], 'ro')
ax4.set_xlabel('Date')
ax4.set_ylabel('Snow Depth (in)')
ax4.set_title('Prior Snow Depth')

plt.tight_layout(pad=2)

在这里插入图片描述
上面这个图表中,我们能知道了特征数据的走势

下面我们再按季节做分布,看看 昨天的最高温度值与昨天的降水 这两个特征的用途

# 创建季节变量
seasons = []
# 设定好春夏秋冬
for month in features['month']:
    if month in [1, 2, 12]:
        seasons.append('winter')
    elif month in [3, 4, 5]:
        seasons.append('spring')
    elif month in [6, 7, 8]:
        seasons.append('summer')
    elif month in [9, 10, 11]:
        seasons.append('fall')
# 整合数据
reduced_features = features[['temp_1', 'prcp_1', 'average', 'actual']]
reduced_features['season'] = seasons
reduced_features.head()

在这里插入图片描述
下面使用 Seaborn 画相关矩阵图,来查看多个变量之间的联系

Seaborn其实是在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,而且它能高度兼容numpy与pandas数据结构以及scipy与statsmodels等统计模式。

# 导入 seaborn 工具包
import seaborn as sns
sns.set(style="ticks", color_codes=True);
# 定义颜色
palette = sns.xkcd_palette(['dark blue', 'dark green', 'gold', 'orange'])
# 绘制 pairplot
sns.pairplot(reduced_features, hue = 'season', diag_kind = 'kde', palette= palette, plot_kws=dict(alpha = 0.7),
                   diag_kws=dict(shade=True)); 

在这里插入图片描述
通过此矩阵图我们可以看出,temp_1 与 actual 有很强的正比关系

数据预处理

数据的预处理和以前一样

# 导入工具包
import numpy as np
from sklearn.model_selection import train_test_split
# 独热编码处理数据
features = pd.get_dummies(features)
# 设定 features and labels
labels = features['actual']
features = features.drop('actual', axis = 1)
# 将特征转换为列表格式
feature_list = list(features.columns)

features = np.array(features)
labels = np.array(labels)
# 划分数据集
train_features, test_features, train_labels, test_labels = train_test_split(features, labels, 
                                                                            test_size = 0.25, random_state = 42)
这里训练效果做一个对比

旧数据集
先看一下旧数据集做出来的结果

# 导入工具包
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
# 读取数据集
original_features = pd.read_csv('data/temps.csv')
# 独热编码处理数据
original_features = pd.get_dummies(original_features)
# 指定标签
original_labels = np.array(original_features['actual'])
# 指定特征集
original_features= original_features.drop('actual', axis = 1)
# 保存特征名称,转化为list格式
original_feature_list = list(original_features.columns)
# 转化为 np.array
original_features = np.array(original_features)
# 划分数据集
original_train_features, original_test_features, original_train_labels, original_test_labels = train_test_split(original_features,
                                                                                                                original_labels,
                                                                                                                test_size = 0.25,
                                                                                                                random_state = 42)
# 建模
rf = RandomForestRegressor(n_estimators= 1000, random_state=42)
# 训练模型
rf.fit(original_train_features, original_train_labels);
# 预测
predictions = rf.predict(original_test_features)
# 算平均绝对误差
errors = abs(predictions - original_test_labels)
# 算平均绝对百分比误差
mape = 100 * (errors / original_test_labels)
accuracy = 100 - np.mean(mape)
# 输出结果
print('Average absolute error:', round(np.mean(errors), 2))
print('Accuracy:', round(accuracy, 2), '%')
Average absolute error: 3.83
Accuracy: 93.99 %

旧数据集扩量
接下来是使用新的数据集,但是只增加数据量,不添加新的特征进来

from sklearn.ensemble import RandomForestRegressor
# 查找原始特征索引
original_feature_indices = [feature_list.index(feature) for feature in
                                      feature_list if feature not in
                                      ['ws_1', 'prcp_1', 'snwd_1']]
# 使用旧数据索引值在新数据中得到训练数据
original_train_features = train_features[:,original_feature_indices]
# 使用旧数据索引值在新数据中得到测试数据
original_test_features = test_features[:, original_feature_indices]
# 建模
rf = RandomForestRegressor(n_estimators= 100, random_state=42)
# 训练
rf.fit(original_train_features, train_labels);
# 预测结果
baseline_predictions = rf.predict(original_test_features)
# 算平均绝对误差
baseline_errors = abs(baseline_predictions - test_labels)
# 算平均绝对百分比误差
baseline_mape = 100 * np.mean((baseline_errors / test_labels))
baseline_accuracy = 100 - baseline_mape
# 打印
print('Average absolute error:', round(np.mean(baseline_errors), 2))
print('Accuracy:', round(baseline_accuracy, 2), '%')
Average absolute error: 3.76
Accuracy: 93.7 %

根据这两个输出结果的对比,说明了数据量增大对结果起到了一定的促进作用

新数据集

# 导入工具包
from sklearn.ensemble import RandomForestRegressor
# 建模
rf_exp = RandomForestRegressor(n_estimators= 100, random_state=42)
# 训练
rf_exp.fit(train_features, train_labels)
# 预测结果
predictions = rf_exp.predict(test_features)
# 算平均绝对误差
errors = abs(predictions - test_labels)
# 算平均绝对百分比误差
mape = np.mean(100 * (errors / test_labels))
accuracy = 100 - mape
# 算平均绝对百分比误差的新旧数据集差值
improvement_baseline = 100 * abs(mape - baseline_mape) / baseline_mape

#打印
print('Improvement over baseline:', round(improvement_baseline, 2), '%')
print('Average absolute error:', round(np.mean(errors), 4))
print('Accuracy:', round(accuracy, 2), '%')
Improvement over baseline: 0.52 %
Average absolute error: 3.7161
Accuracy: 93.73 %

特征重要性

因为在新的数据集中,我们增加了新的特征进来

# 特征名称
importances = list(rf_exp.feature_importances_)
# 拿到特征数据
feature_importances = [(feature, round(importance, 2)) for feature, importance in zip(feature_list, importances)]
# 排序
feature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)
# 打印
[print('特征: {:20} 重要性: {}'.format(*pair)) for pair in feature_importances]
特征: temp_1               重要性: 0.83
特征: average              重要性: 0.06
特征: ws_1                 重要性: 0.02
特征: temp_2               重要性: 0.02
特征: friend               重要性: 0.02
特征: year                 重要性: 0.01
特征: month                重要性: 0.01
特征: day                  重要性: 0.01
特征: prcp_1               重要性: 0.01
特征: snwd_1               重要性: 0.0
特征: weekday_Fri          重要性: 0.0
特征: weekday_Mon          重要性: 0.0
特征: weekday_Sat          重要性: 0.0
特征: weekday_Sun          重要性: 0.0
特征: weekday_Thurs        重要性: 0.0
特征: weekday_Tues         重要性: 0.0
特征: weekday_Wed          重要性: 0.0

对特征重要性进行可视化

# 设定绘图风格
plt.style.use('fivethirtyeight')
# 指定位置
x_values = list(range(len(importances)))
# 绘图
plt.bar(x_values, importances, orientation = 'vertical', color = 'r', edgecolor = 'k', linewidth = 1.2)
# 指定名称
plt.xticks(x_values, feature_list, rotation='vertical')
# 绘图
plt.ylabel('Importance')
plt.xlabel('Variable')
plt.title('Variable Importances')

在这里插入图片描述
这里我们看到,temp_1 特征最重要,还有一些特征完全不起作用,所以关于在训练中特征,其特征重要性累加后在95%就可以,就是说有多少个特征的特征多样性累加达到95%,使用这些特征就够了

# 对特征重要性排序
sorted_importances = [importance[1] for importance in feature_importances]
sorted_features = [importance[0] for importance in feature_importances]
# 计算累加值,累计重要性
cumulative_importances = np.cumsum(sorted_importances)
# 绘制折线图
plt.plot(x_values, cumulative_importances, 'g-')
# 画一条红虚线 0.95的界限
plt.hlines(y = 0.95, xmin=0, xmax=len(sorted_importances), color = 'r', linestyles = 'dashed')
# X周名称
plt.xticks(x_values, sorted_features, rotation = 'vertical')
# 绘图
plt.xlabel('Variable')
plt.ylabel('Cumulative Importance')
plt.title('Cumulative Importances')

在这里插入图片描述
通过这张图表也可以看出,我们前6项特征的和达到了95%

接下来,我们使用这6项特征再次进行训练

# 选择这6项特征
important_feature_names = [feature[0] for feature in feature_importances[0:6]]
# 找到他们的索引
important_indices = [feature_list.index(feature) for feature in important_feature_names]
# 拿到训练集与测试集
important_train_features = train_features[:, important_indices]
important_test_features = test_features[:, important_indices]
# 建模
rf_exp = RandomForestRegressor(n_estimators= 100, random_state=42)
# 训练
rf_exp.fit(important_train_features, train_labels)
# 预测
predictions = rf_exp.predict(important_test_features)
# 算平均绝对误差
errors = abs(predictions - test_labels)
# 算平均绝对百分比误差
mape = 100 * (errors / test_labels)
accuracy = 100 - np.mean(mape)
# 打印
print('Average absolute error:', round(np.mean(errors), 4))
print('Accuracy:', round(accuracy, 2), '%')
Average absolute error: 3.829
Accuracy: 93.56 %

结果来看,效果反而下降了,其实随机森林的算法本身就会考虑特征的问题,会优先选择有价值的,我们认为的去掉一些,相当于可供候选的就少了,也就会出现这样的现象

计算 Trade-Offs

Run-Time

虽然说模型没有提升,反而精度还有一点点的下降,那我们再看看他们在时间效率层面上有没有进步

计算放入所有特征时建模与测试消耗的时间

# 导入包
import time
# 建立空list
all_features_time = []
# 一次不太准,所以算10次取平均
for _ in range(10):
    start_time = time.time()
    rf_exp.fit(train_features, train_labels)
    all_features_predictions = rf_exp.predict(test_features)
    end_time = time.time()
    all_features_time.append(end_time - start_time)
all_features_time = np.mean(all_features_time)
print('使用所有特征时建模与测试的平均消耗时间:', round(all_features_time, 2), '秒')
使用所有特征时建模与测试的平均消耗时间: 0.72 秒

计算放入所有特征时建模与测试消耗的时间

# 导入包
import time
# 建立空list
reduced_features_time = []
# 一次不太准,所以算10次取平均
for _ in range(10):
    start_time = time.time()
    rf_exp.fit(important_train_features, train_labels)
    reduced_features_predictions = rf_exp.predict(important_test_features)
    end_time = time.time()
    reduced_features_time.append(end_time - start_time)
reduced_features_time = np.mean(reduced_features_time)
print('使用所有特征时 建模与测试的平均消耗时间:', round(reduced_features_time, 2), '秒')
使用所有特征时 建模与测试的平均消耗时间: 0.5 秒

我们看到,虽然精度降低了,但是建模与测试消耗的时间减少了0.22秒

Accuracy vs Run-Time
#用预测值来计算评估结果
all_accuracy =  100 * (1- np.mean(abs(all_features_predictions - test_labels) / test_labels))
reduced_accuracy = 100 * (1- np.mean(abs(reduced_features_predictions - test_labels) / test_labels))
# 创建df来存结果
comparison = pd.DataFrame({'features': ['all (17)', 'reduced (5)'], 
                           'run_time': [round(all_features_time, 2), round(reduced_features_time, 2)],
                           'accuracy': [round(all_accuracy, 2), round(reduced_accuracy, 2)]})
comparison[['features', 'accuracy', 'run_time']]

在这里插入图片描述

relative_accuracy_decrease = 100 * (all_accuracy - reduced_accuracy) / all_accuracy
print('相对准确率下降:', round(relative_accuracy_decrease, 3), '%')
relative_runtime_decrease = 100 * (all_features_time - reduced_features_time) / all_features_time
print('相对时间效率下降:', round(relative_runtime_decrease, 3), '%')
相对准确率下降: 0.187 %
相对时间效率下降: 30.792 %

这两种结果展示,可以看到准确率并没有太大的差别,下降了0.187 %,但是运行时间差别还是比较大的,下降了30.792 %,所以实际中我们也得综合来考虑下性能问题

总结

对只有一年的数据量的数据集、完整的新数据集、按照95%阈值选择的部分重要特征的数据集进行比较

# 导入包
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
# 读入旧数据
original_features = pd.read_csv('data/temps.csv')
# 独热编码处理数据
original_features = pd.get_dummies(original_features)
# 指定标签
original_labels = np.array(original_features['actual'])
# 特征集
original_features= original_features.drop('actual', axis = 1)
# 获取特征列表
original_feature_list = list(original_features.columns)
# 转换成np.array形式
original_features = np.array(original_features)
# 数据集划分
original_train_features, original_test_features, original_train_labels, original_test_labels = train_test_split(original_features,
                                                                                                                original_labels,
                                                                                                                test_size = 0.25,
                                                                                                                random_state = 42)
# 拿到旧数据集的特征索引
original_feature_indices = [feature_list.index(feature) for feature in
                                      feature_list if feature not in
                                      ['ws_1', 'prcp_1', 'snwd_1']]
# 创建旧数据集的特征的测试集
original_test_features = test_features[:, original_feature_indices]
# 设定空list
original_features_time = []
# 训练和测试 循环10次
for _ in range(10):
    start_time = time.time()
    rf.fit(original_train_features, original_train_labels)
    original_features_predictions = rf.predict(original_test_features)
    end_time = time.time()
    original_features_time.append(end_time - start_time)
# 计算平均时间
original_features_time = np.mean(original_features_time)
# 计算MAE
original_mae = np.mean(abs(original_features_predictions - test_labels))
exp_all_mae = np.mean(abs(all_features_predictions - test_labels))
exp_reduced_mae = np.mean(abs(reduced_features_predictions - test_labels))
# 计算旧数据的accuracy
original_accuracy = 100 * (1 - np.mean(abs(original_features_predictions - test_labels) / test_labels))
# 创建df来存结果
model_comparison = pd.DataFrame({'model': ['original', 'exp_all', 'exp_reduced'], 
                                 'error (degrees)':  [original_mae, exp_all_mae, exp_reduced_mae],
                                 'accuracy': [original_accuracy, all_accuracy, reduced_accuracy],
                                 'run_time (s)': [original_features_time, all_features_time, reduced_features_time]})
model_comparison = model_comparison[['model', 'error (degrees)', 'accuracy', 'run_time (s)']]

在这里插入图片描述

# 最后做绘图总结
# 设置总体布局
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, figsize = (8,16), sharex = True)
# X轴名称定义
x_values = [0, 1, 2]
labels = list(model_comparison['model'])
plt.xticks(x_values, labels)
# 定义字体大小
fontdict = {'fontsize': 18}
fontdict_yaxis = {'fontsize': 14}
# 比较 Error
ax1.bar(x_values, model_comparison['error (degrees)'], color = ['b', 'r', 'g'], edgecolor = 'k', linewidth = 1.5)
ax1.set_ylim(bottom = 3.5, top = 4.5)
ax1.set_ylabel('Error (degrees) (F)', fontdict = fontdict_yaxis)
ax1.set_title('Model Error Comparison', fontdict= fontdict)
# 比较 Accuracy
ax2.bar(x_values, model_comparison['accuracy'], color = ['b', 'r', 'g'], edgecolor = 'k', linewidth = 1.5)
ax2.set_ylim(bottom = 92, top = 94)
ax2.set_ylabel('Accuracy (%)', fontdict = fontdict_yaxis)
ax2.set_title('Model Accuracy Comparison', fontdict= fontdict)
# 比较 Run Time
ax3.bar(x_values, model_comparison['run_time (s)'], color = ['b', 'r', 'g'], edgecolor = 'k', linewidth = 1.5)
ax3.set_ylim(bottom = 0, top = 1)
ax3.set_ylabel('Run Time (sec)', fontdict = fontdict_yaxis)
ax3.set_title('Model Run-Time Comparison', fontdict= fontdict)

在这里插入图片描述
original 代表旧数据,就是只有一年的数据量的数据集
exp_all 代表完整的新数据集
exp_reduced 代表按照95%阈值选择的部分重要特征的数据集

结果比较明显,数据量和特征越多,效果也会越好,但是时间效率也会降低

  • 11
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: 随机森林是一种基于决策树机器学习算法,常用于回归和分类问题。气温预测是一个回归问题,因此可以使用随机森林算法来进行预测随机森林气温预测数据代码.zip是一个包含着使用随机森林算法进行气温预测的代码的压缩文件。解压后,你会看到一些代码文件和数据文件。 其中,代码文件可能会包含以下内容: 1. 数据预处理代码:这部分代码用于读取和处理原始气温数据,包括数据的清洗、特征提取和标签处理。 2. 模型训练代码:这部分代码用于使用随机森林算法对预处理后的数据进行训练,生成一个模型。 3. 模型评估代码:这部分代码用于评估训练好的模型的性能,包括模型的准确率、均方误差等指标。 4. 模型应用代码:这部分代码用于输入新的数据,利用训练好的模型进行气温预测数据文件可能包含以下内容: 1. 原始气温数据:这部分数据通常是以表格形式存储的,包括日期时间和气温的记录。 2. 预处理后的气温数据:这部分数据是经过清洗和处理后的,可以直接用于模型训练和预测。 使用这些代码和数据,你可以按照以下步骤进行气温预测: 1. 运行数据预处理代码,将原始气温数据进行清洗和处理,得到预处理后的气温数据。 2. 运行模型训练代码,使用预处理后的气温数据进行训练,生成一个随机森林模型。 3. 运行模型评估代码,评估训练好的模型的性能。 4. 运行模型应用代码,输入新的气温数据,利用训练好的模型进行气温预测。 希望以上解答能帮到你,如果需要更详细的说明,请提供更多相关信息。 ### 回答2: 随机森林气温预测数据代码.zip是一个压缩包,里面包含了用随机森林算法预测气温的相关代码。 随机森林是一种集成学习算法,它通过构建多个决策树进行预测,并将这些决策树预测结果进行综合,以此来提高预测的准确性。 在这个压缩包中,可能包含以下内容: 1. 数据预处理代码:随机森林算法对数据预测结果受到数据质量的影响,因此通常需要对数据进行清洗、转换和处理。预处理代码可以包括数据清洗、缺失值处理、特征选择等步骤。 2. 模型训练代码:该代码用于训练随机森林模型。训练代码包括了选择模型参数、分割数据集为训练集和测试集、训练模型等步骤。 3. 模型评估和预测代码:该代码用于评估训练得到的随机森林模型的效果,并用该模型进行新数据预测。评估代码可以包括统计指标计算和绘图展示等步骤,预测代码可以用来预测数据气温。 使用这个压缩包的步骤可能如下: 1. 解压缩压缩包。 2. 按照压缩包内的README或者文档说明,查看数据预处理的代码,并根据需要进行数据预处理。 3. 按照压缩包内的README或者文档说明,查看模型训练的代码,并根据需要调整模型参数并训练模型。 4. 按照压缩包内的README或者文档说明,查看模型评估和预测的代码,并根据需要进行模型的评估和预测。 需要注意的是,随机森林气温预测数据代码.zip的具体内容可能因为作者和用途的不同而有所差异,所以在实际使用过程中,可以参考压缩包内的说明文档或者联系开发者,以获取更准确的使用指导。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值