Introduction
决策树会让您做出艰难的决定。 有很多树叶的深树将会过拟合,因为每个预测都来自其叶子上只有少数房屋的历史数据。 但是叶子很少的浅树会表现不佳,因为它无法捕获原始数据中的许多区别。
即使在今天,最成熟的建模技术也面临着过拟合和欠拟合之间的这种紧张关系。 但是,许多模型都有聪明的想法,可以带来更好的性能。 我们将以随机森林为例。
随机森林使用许多树,并通过平均每个组树的预测来进行预测。 它通常比单个决策树具有更好的预测准确性,并且与默认参数一起使用效果很好。 如果您继续建模,您可以学习更多具有更好性能的模型,但其中许多模型对获取正确的参数很敏感。
Example
您已经多次看到加载数据的代码,加载后我们有以下变量:
- train_X
- val_X
- train_y
- val_y
【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。
【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))
202888.18157951365
Conclusion
可能还有进一步改进的空间,但这比250,000的最佳决策树误差有了很大的改进。 有些参数允许您更改随机森林的性能,就像我们更改单个决策树的最大深度一样。 但随机森林模型的最佳特征之一是,即使没有这种调整,它们通常也能合理地工作。
您很快就会学习XGBoost模型,它可以在使用正确的参数进行调整时提供更好的性能(但需要一些技巧才能获得正确的模型参数)。
Your Turn
尝试使用随机森林模型看看对您自己模型的改善。