6.Random Forests
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_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)) 202888.18157951365Conclusion
可能還有進一步改進的空間,但這比250,000的最佳決策樹誤差有了很大的改進。 有些參數允許您更改隨機森林的性能,就像我們更改單個決策樹的最大深度一樣。 但隨機森林模型的最佳特征之一是,即使沒有這種調整,它們通常也能合理地工作。
您很快就會學習XGBoost模型,它可以在使用正確的參數進行調整時提供更好的性能(但需要一些技巧才能獲得正確的模型參數)。
Your Turn
嘗試使用隨機森林模型看看對您自己模型的改善。
總結
以上是生活随笔為你收集整理的6.Random Forests的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pav.exe - pav是什么进程 有
- 下一篇: 图解算法学习笔记(三):递归