介绍

决策树让你面临一个难以决定的问题。一个带有很多叶子的深树会过度拟合,因为每个预测只来自于其叶子上的几栋房屋的历史数据。但是,叶子较少的浅树性能表现不佳,因为它无法捕捉原始数据中的许多差异。

即使是今天最先进的建模技术也面临着欠拟合和过拟合之间的紧张关系。但是,许多模型都有巧妙的想法,可以带来更好的性能。我们将以随机森林为例。

随机森林使用多棵树,并通过平均每个组件树的预测来进行预测。它通常比单个决策树具有更好的预测准确性,并且在默认参数下工作得很好。如果你继续建模,你可以学习更多性能更好的模型,但其中许多模型对于获得正确的参数非常敏感。

例子

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

  • 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_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

总结

可能还有进一步改进的空间,但这比最佳决策树错误(250,000)要好得多。有一些参数允许您改变随机森林的性能,就像我们改变单个决策树的最大深度一样。但是,随机森林模型最好的特性之一是,即使没有这种调优,它们通常也能合理地工作。


标题:kaggle机器学习入门(五)随机森林
作者:Departure
地址:https://www.unreachablecity.club/articles/2023/04/15/1681520620415.html