開始使用免費開始

計算 R-squared

現在你已經計算出模型預測的 RMSE,接下來要評估模型與資料的擬合程度:也就是它解釋了多少變異。你可以使用 \(R^2\) 來完成。

假設 \(y\) 是真實結果,\(p\) 是模型的預測, \(res = y - p\) 是預測的殘差。

則資料的總平方和(total sum of squares,$tss$,亦稱「總變異」)為:

$$ tss = \sum{(y - \overline{y})^2} $$

其中 \(\overline{y}\) 是 \(y\) 的平均值。

模型的殘差平方和(residual sum of squares),\(rss\) 為: $$ rss = \sum{res^2} $$

$R^2$(R-squared),也就是模型「解釋變異」的比例,為:

$$ 1 - \frac{rss}{tss} $$

計算出 \(R^2\) 之後,你會把自己的結果與 glance() 回報的 \(R^2\) 進行比較(docs)。glance() 會回傳只有 1 列的資料框;對於線性迴歸模型,其中一個欄位就是此模型在訓練資料上的 $R^2$。

unemployment 資料框已為你載入,且包含你在前一個練習計算的 predictionsresiduals 欄位。unemployment_model 也可供你使用。

本練習屬於課程

R 中的監督式學習:回歸

檢視課程

練習說明

  • 計算 female_unemployment 的平均數並指派給變數 fe_mean
  • 計算總平方和,並指派給變數 tss
  • 計算殘差平方和,並指派給變數 rss
  • 計算 $R^2$。擬合得好嗎(\(R^2\) 是否接近 1)?
  • 使用 glance() 從模型取得 $R^2$。它和你計算的一樣嗎?

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# unemployment is available
summary(unemployment)

# unemployment_model is available
summary(unemployment_model)

# Calculate and print the mean female_unemployment: fe_mean
(fe_mean <- ___)

# Calculate and print the total sum of squares: tss
(tss <- ___((___ - ___)^2))

# Calculate and print residual sum of squares: rss
(rss <- ___)

# Calculate and print the R-squared: rsq
(rsq <- ___)

# Get R-squared from glance and print it
(rsq_glance <- ___(___)$___)
編輯並執行程式碼