6、机器学习之随机森林

使用更复杂的机器学习算法。

本课程所需数据集夸克网盘下载链接:https://pan.quark.cn/s/9b4e9a1246b2
提取码:uDzP

1、简介

决策树给你留下了一个困难的选择。一个深度很大、有很多叶子的树会因为每个预测都来自其叶子上仅有的几个房屋的历史数据而过拟合。但是一个浅树,叶子较少,表现会较差,因为它未能捕捉原始数据中的许多细微差异。

即使是今天最先进的建模技术也面临欠拟合和过拟合之间的棘手问题。然而,许多模型有一些巧妙的思想,可以带来更好的性能。我们将以随机森林为例进行说明。

随机森林使用多个决策树,并通过对每个组成树的预测进行平均来进行预测。它通常比单个决策树具有更好的预测准确性,并且在使用默认参数时表现良好。如果你继续建模,可以学到更多性能更好的模型,但其中许多对于参数的设置比较敏感。

2、实例

您已经看过几次加载数据的代码了。在数据加载结束时,我们有以下变量:

  • train_X

  • val_X

  • train_y

  • val_y

  • y

In [1]:

import pandas as pd
    
# Load data
melbourne_file_path = '../input/melbourne-housing-snapshot/melb_data.csv'
melbourne_data = pd.read_csv(melbourne_file_path) 
# Filter rows with missing values
melbourne_data = melbourne_data.dropna(axis=0)
# Choose target and features
y = melbourne_data.Price
melbourne_features = ['Rooms', 'Bathroom', 'Landsize', 'BuildingArea', 
                        'YearBuilt', 'Lattitude', 'Longtitude']
X = melbourne_data[melbourne_features]

from sklearn.model_selection import train_test_split

# split data into training and validation data, for both features and target
# The split is based on a random number generator. Supplying a numeric value to
# the random_state argument guarantees we get the same split every time we
# run this script.
train_X, val_X, train_y, val_y = train_test_split(X, y,random_state = 0)

我们构建随机森林模型的方法与在 scikit-learn 中构建决策树的方式类似,只是这次我们使用 RandomForestRegressor 类而不是 DecisionTreeRegressor

In [2]:

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

forest_model = RandomForestRegressor(random_state=1)
forest_model.fit(train_X, train_y)
melb_preds = forest_model.predict(val_X)
print(mean_absolute_error(val_y, melb_preds))

191669.7536453626

3、结论

很可能还有进一步改进的空间,但这已经相比最佳决策树误差为 250,000 有了很大的提升。有一些参数可以像我们改变单个决策树的最大深度那样,改变随机森林的性能。但随机森林模型最好的特点之一是,它们通常即使在没有进行调优的情况下也能表现得相当不错。

进入机器学习比赛的世界,不断进步,看看你的进步。机器学习比赛是提高你的数据科学技能和衡量你进步的好方法。

相关推荐

  1. 6机器学习随机森林

    2024-01-19 17:36:01       59 阅读
  2. 机器学习模型随即森林

    2024-01-19 17:36:01       35 阅读
  3. 机器学习随机森林算法

    2024-01-19 17:36:01       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-19 17:36:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-19 17:36:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-19 17:36:01       87 阅读
  4. Python语言-面向对象

    2024-01-19 17:36:01       96 阅读

热门阅读

  1. 1818:红与黑【解析】-------深度优先搜索

    2024-01-19 17:36:01       43 阅读
  2. springboot项目引入onlyoffice多人协同编辑文档

    2024-01-19 17:36:01       63 阅读
  3. 五个常见的 jQuery 面试题

    2024-01-19 17:36:01       46 阅读
  4. SVN 常用命令

    2024-01-19 17:36:01       51 阅读
  5. 【Bug】.net6 cap总线+rabbitmq延时消息收不到

    2024-01-19 17:36:01       64 阅读
  6. 力扣(leetcode)第821题字符的最短距离(Python)

    2024-01-19 17:36:01       57 阅读