두 개의 수치형 설명 변수

R 중급 회귀

Richie Cotton

Data Evangelist at DataCamp

수치형 변수 3개 시각화

  • 3D 산점도
  • 응답을 색으로 표시한 2D 산점도
R 중급 회귀

fish 데이터셋에 또 다른 열 추가

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-물고기-길이-높이-질량.png

R 중급 회귀

2D 산점도, 응답을 색으로 표시

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

산점도-색상-물고기-길이-높이-질량.png

R 중급 회귀

Viridis 색상 스케일

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

산점도-색상-물고기-길이-높이-질량-inferno.png

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-예측.png

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-예측-상호작용.png

R 중급 회귀

연습해 봅시다!

R 중급 회귀

Preparing Video For Download...