两个数值型自变量

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 中级回归

二维散点图,颜色表示响应变量

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

按颜色编码的散点图:鱼的长度、高度、质量

R 中级回归

Viridis 色标

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

散点图:长度、高度、质量(Inferno 配色)

R 中级回归

含两个数值型自变量的建模

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
  )

散点图与预测点:长度、高度、质量(含交互,Inferno)

R 中级回归

Passons à la pratique !

R 中级回归

Preparing Video For Download...