開始使用免費開始

擬合模型來預測單車租借次數

在這個練習中,你將建立一個模型,根據天氣、日期類型(假日、工作日或週末)以及一天中的時間,來預測每小時被租借的單車數量。你會使用 7 月份的資料來訓練模型。

這個資料框包含下列欄位:

  • cnt:該小時租借的單車數量(輸出變數)
  • hr:一天中的小時(0-23,為因子)
  • holiday:TRUE/FALSE
  • workingday:若既非假日也非週末則為 TRUE,否則為 FALSE
  • weathersit:類別型,「Clear to partly cloudy」/「Light Precipitation」/「Misty」
  • temp:標準化後的攝氏氣溫
  • atemp:標準化後的體感攝氏氣溫
  • hum:標準化後的相對溼度
  • windspeed:標準化後的風速
  • instant:時間索引──自資料集開始以來的小時數(不作為變數)
  • mnthyr:月份與年份索引(不作為變數)

記得在使用 glm()docs)擬合計數型模型時,必須指定 family = poissonfamily = quasipoisson

由於輸入變數很多,為了方便,我們會先用變數指定輸出與輸入, 再用 paste()docs)組合出代表模型公式的字串。

bikesJuly 資料框已可使用。輸出變數與輸入變數的名稱也分別載入為 outcomevars

本練習屬於課程

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 <- ___)
編輯並執行程式碼