擬合模型來預測單車租借次數
在這個練習中,你將建立一個模型,根據天氣、日期類型(假日、工作日或週末)以及一天中的時間,來預測每小時被租借的單車數量。你會使用 7 月份的資料來訓練模型。
這個資料框包含下列欄位:
cnt:該小時租借的單車數量(輸出變數)hr:一天中的小時(0-23,為因子)holiday:TRUE/FALSEworkingday:若既非假日也非週末則為 TRUE,否則為 FALSEweathersit:類別型,「Clear to partly cloudy」/「Light Precipitation」/「Misty」temp:標準化後的攝氏氣溫atemp:標準化後的體感攝氏氣溫hum:標準化後的相對溼度windspeed:標準化後的風速instant:時間索引──自資料集開始以來的小時數(不作為變數)mnth與yr:月份與年份索引(不作為變數)
記得在使用 glm()(docs)擬合計數型模型時,必須指定 family = poisson 或 family = quasipoisson。
由於輸入變數很多,為了方便,我們會先用變數指定輸出與輸入,
再用 paste()(docs)組合出代表模型公式的字串。
bikesJuly 資料框已可使用。輸出變數與輸入變數的名稱也分別載入為 outcome 與 vars。
本練習屬於課程
R 中的監督式學習:回歸
練習說明
- 填空以建立公式
fmla,將cnt表示為輸入變數的函數。印出它。 - 計算
bikesJuly$cnt的平均數(mean())與變異數(var())。- 你應該用 poisson 還是 quasipoisson 迴歸?
- 使用
glm()對bikesJuly擬合一個模型:bike_model。 - 使用
glance()檢視模型的擬合統計量。將glance()的輸出指定給變數perf。 - 計算模型的偽 R 平方。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# bikesJuly is available
str(bikesJuly)
# The outcome column
outcome
# The inputs to use
vars
# Create the formula string for bikes rented as a function of the inputs
(fmla <- paste(___, "~", paste(___, collapse = " + ")))
# Calculate the mean and variance of the outcome
(mean_bikes <- ___)
(var_bikes <- ___)
# Fit the model
bike_model <- ___
# Call glance
(perf <- ___)
# Calculate pseudo-R-squared
(pseudoR2 <- ___)