Более двух объясняющих переменных

Промежуточная регрессия в R

Richie Cotton

Data Evangelist at DataCamp

Из прошлого урока

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

scatter-color-fish-length-height-mass-inferno.png

Промежуточная регрессия в R

Разбивка по видам

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

scatter-fish-length-height-mass-species.png

Промежуточная регрессия в R

Уровни взаимодействий

Без взаимодействий

lm(mass_g ~ length_cm + height_cm + species + 0, data = fish)

Двойные взаимодействия между парами переменных

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + 0, 
  data = fish
)

Тройное взаимодействие между всеми тремя переменными

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + length_cm:height_cm:species + 0, 
  data = fish
)
Промежуточная регрессия в R

Все взаимодействия

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + length_cm:height_cm:species + 0, 
  data = fish
)
lm(
  mass_g ~ length_cm * height_cm * species + 0, 
  data = fish
)
Промежуточная регрессия в R

Только двойные взаимодействия

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + 0, 
  data = fish
)
lm(
  mass_g ~ (length_cm + height_cm + species) ^ 2 + 0, 
  data = fish
)
lm(
  mass_g ~ I(length_cm) ^ 2 + height_cm + species + 0, 
  data = fish
)
1 Возведение объясняющих переменных в степень рассматривается в курсе «Введение в регрессию в R», глава 2, «Преобразование переменных»
Промежуточная регрессия в R

Процесс построения прогнозов

mdl_mass_vs_all <- lm(mass_g ~ length_cm * height_cm * species * 0, data = fish)

explanatory_data <- expand_grid(
  length_cm = seq(5, 60, 6),
  height_cm = seq(2, 20, 2),
  species = unique(fish$species)
)

prediction_data <- explanatory_data %>% 
  mutate(mass_g = predict(mdl_mass_vs_all, explanatory_data))
Промежуточная регрессия в R

Визуализация прогнозов

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

scatter-fish-length-height-mass-species-pred.png

Промежуточная регрессия в R

Давайте потренируемся!

Промежуточная регрессия в R

Preparing Video For Download...