Introduction

决策树会给你带来艰难的决策。一棵深且有大量叶子节点的决策树会过拟合,因为每个预测都仅基于其叶子节点上少数房屋的历史数据。而一棵浅且叶子节点少的决策树则会表现不佳,因为它无法捕捉到原始数据中尽可能多的差异。

即使是当今最复杂的建模技术也面临着欠拟合和过拟合之间的矛盾。但是,许多模型都巧妙地运用了一些技巧,可以提升性能。我们将以随机森林为例。

随机森林使用多棵树,并通过对每棵树的预测取平均值来进行预测。它的预测准确率通常远高于单棵决策树,并且在默认参数下也能很好地工作。如果持续建模,你可以学习到更多性能更佳的模型,但其中许多模型对获取正确的参数非常敏感。

Example

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

  • train_X
  • val_X
  • train_y
  • val_y
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

Conclusion

虽然仍有进一步改进的空间,但这比最佳决策树 25 万的误差值已经有了很大的提升。有一些参数可以让你改变随机森林的性能,就像我们改变单个决策树的最大深度一样。但随机森林模型最棒的特性之一是,即使没有这些调整,它们通常也能合理地工作。

Your Turn

亲自尝试**使用随机森林模型**,看看它对你的模型有多大帮助。