兩個數值型解釋變數

R 的迴歸分析中級

Richie Cotton

Data Evangelist at DataCamp

視覺化 3 個數值變數

  • 3D 散佈圖
  • 2D 散佈圖,以反應變數著色
R 的迴歸分析中級

魚類資料集的另一個欄位

species mass_g length_cm height_cm
Bream 1000 33.5 18.96
Bream 925 36.2 18.75
Roach 290 24.0 8.88
Roach 390 29.5 9.48
Perch 1100 39.0 12.80
Perch 1000 40.2 12.60
Pike 1250 52.0 10.69
Pike 1650 59.0 10.81
R 的迴歸分析中級

3D 散佈圖

library(plot3D)

scatter3D(fish$length_cm, fish$height_cm, fish$mass_g)
library(plot3D)
library(magrittr)

fish %$%
  scatter3D(length_cm, height_cm, mass_g)
R 的迴歸分析中級

3D 散佈圖

library(plot3D)
library(magrittr)

fish %$%
  scatter3D(length_cm, height_cm, mass_g)

3D 散佈圖:魚的長度、高度、重量

R 的迴歸分析中級

2D 散佈圖,以顏色表示反應

ggplot(
  fish, 
  aes(length_cm, height_cm, color = mass_g)
) +
  geom_point()

2D 散佈圖(以重量著色):長度 × 高度

R 的迴歸分析中級

Viridis 色階

ggplot(
  fish, 
  aes(length_cm, height_cm, color = mass_g)
) +
  geom_point() +
  scale_color_viridis_c(option = "inferno")

Viridis 色階(inferno)散佈圖

R 的迴歸分析中級

含 2 個數值解釋變數的模型

mdl_mass_vs_both <- lm(mass_g ~ length_cm + height_cm, data = fish)
Call:
lm(formula = mass_g ~ length_cm + height_cm, data = fish)

Coefficients:
(Intercept)    length_cm    height_cm  
    -622.16        28.97        26.34
R 的迴歸分析中級

預測流程

explanatory_data <- expand_grid(
  length_cm = seq(5, 60, 5),
  height_cm = seq(2, 20, 2)
)

prediction_data <- explanatory_data %>% 
  mutate(
    mass_g = predict(mdl_mass_vs_both, explanatory_data)
  )
R 的迴歸分析中級

繪製預測結果

ggplot(
  fish, 
  aes(length_cm, height_cm, color = mass_g)
) +
  geom_point() +
  scale_color_viridis_c(option = "inferno") +
  geom_point(
    data = prediction_data, shape = 15, size = 3
  )

預測點疊圖(inferno 色階)

R 的迴歸分析中級

加入交互作用項

mdl_mass_vs_both_inter <- lm(mass_g ~ length_cm * height_cm, data = fish)
Call:
lm(formula = mass_g ~ length_cm * height_cm, data = fish)

Coefficients:
        (Intercept)            length_cm            height_cm  length_cm:height_cm  
           159.1144               0.3001             -78.1234               3.5455
R 的迴歸分析中級

預測流程(含交互作用)

explanatory_data <- expand_grid(
  length_cm = seq(5, 60, 5),
  height_cm = seq(2, 20, 2)
)

prediction_data <- explanatory_data %>% 
  mutate(
    mass_g = predict(mdl_mass_vs_both_inter, explanatory_data)
  )
R 的迴歸分析中級

繪製預測結果

ggplot(
  fish, 
  aes(length_cm, height_cm, color = mass_g)
) +
  geom_point() +
  scale_color_viridis_c(option = "inferno") +
  geom_point(
    data = prediction_data, shape = 15, size = 3
  )

預測點疊圖(含交互作用)

R 的迴歸分析中級

一起來練習吧!

R 的迴歸分析中級

Preparing Video For Download...