Kaggle官方课程链接:Random Forests
本专栏旨在Kaggle官方课程的汉化,让大家更方便地看懂。
Random Forests
使用更复杂的机器学习算法。
介绍
决策树给你留下了一个艰难的决定。一棵有很多叶子的深树会被过度拟合,因为每一个预测都来自它叶子上少数房子的历史数据。但是,叶子很少的浅树表现不佳,因为它无法在原始数据中捕捉到尽可能多的区别。
即使是当今最复杂的建模技术也面临着欠拟合和过拟合之间的紧张关系。但是,许多模型都有聪明的想法,可以带来更好的性能。我们将以随机森林为例。
随机森林使用许多树,并通过对每个组成树的预测进行平均来进行预测。它通常比单个决策树具有更好的预测准确性,并且在默认参数下运行良好。如果你继续建模,你可以学习更多性能更好的模型,但其中许多模型对获得正确的参数很敏感。
例子
您已经多次看到加载数据的代码。在数据加载结束时,我们有以下变量:
- 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。
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_errorforest_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
结论
可能还有进一步改进的空间,但与250000的最佳决策树错误相比,这是一个很大的改进。有一些参数允许您更改随机森林的性能,就像我们更改单个决策树的最大深度一样。但随机森林模型最好的特点之一是,即使没有这种调整,它们通常也能合理地工作。
Your Turn
尝试自己使用随机森林模型,看看它对你的模型有多大的改进。