為單車租借建立一個隨機森林模型
在這個練習中,你會再次建立一個模型,根據天氣、日型(假日、工作日或週末)以及一天中的時間,來預測每小時的單車租借數。你會使用 7 月份的資料來訓練模型。
你將使用 ranger 套件來擬合隨機森林模型。對於本練習,呼叫 ranger()(docs)的重點參數為:
formuladatanum.trees:森林中的樹數量。respect.unordered.factors:指定如何處理無序的因子變數。我們建議在迴歸時將此設為「order」。seed:因為這是隨機演算法,你需要設定隨機種子以取得可重現結果。
由於輸入變數很多,為了方便,我們會在變數 outcome 和 vars 中指定輸出與輸入,並使用 paste()(docs)來組合出代表模型公式的字串。
資料框 bikesJuly 已經預先載入。範例程式碼已指定輸出與輸入變數的名稱。
本練習屬於課程
R 中的監督式學習:回歸
練習說明
- 填空以建立公式
fmla,將cnt表示為輸入變數的函數。並將其印出。 - 載入
ranger套件。 - 使用
ranger對bikesJuly資料擬合模型:bike_model_rf。ranger()的第一個引數是公式fmla。- 使用 500 棵樹,且設定
respect.unordered.factors = "order"。 - 將隨機種子設為
seed以確保結果可重現。 - 印出模型。R-squared 是多少?
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# bikesJuly is available
str(bikesJuly)
# Random seed to reproduce results
seed
# The outcome column
(outcome <- "cnt")
# The input variables
(vars <- c("hr", "holiday", "workingday", "weathersit", "temp", "atemp", "hum", "windspeed"))
# Create the formula string for bikes rented as a function of the inputs
(fmla <- paste(___, "~", paste(___, collapse = " + ")))
# Load the package ranger
___
# Fit and print the random forest model
(bike_model_rf <- ranger(___, # formula
___, # data
num.trees = ___,
respect.unordered.factors = ___,
seed = ___))