모델링 전체 워크플로

R에서 tidymodels로 모델링하기

David Svancer

Data Scientist

데이터 리샘플링

훈련/테스트 데이터셋 생성

  • initial_split()
    • 데이터 분할 객체 생성
  • training()
    • 훈련 데이터셋 생성
  • testing()
    • 테스트 데이터셋 생성
leads_split <- initial_split(leads_df, 
                             strata = purchased)

leads_training <- leads_split %>% training()
leads_test <- leads_split %>% testing()
R에서 tidymodels로 모델링하기

모델 지정

parsnip으로 모델 지정

  • logistic_reg()
    • 로지스틱 회귀 모델 일반 인터페이스
  • set_engine()
    • 'glm' 엔진
  • set_mode()
    • purchased는 명목형 결과 변수
    • 모드는 'classification'이어야 함
logistic_model <- logistic_reg() %>%

set_engine('glm') %>%
set_mode('classification')
Logistic Regression Model 
Specification (classification)

Computational engine: glm
R에서 tidymodels로 모델링하기

특성 공학

recipes로 특성 공학 단계 지정

  • recipe()
    • 모델 공식과 훈련 데이터
  • step_*() 함수
    • 순차 전처리 단계
leads_recipe <- recipe(purchased ~ .,
                       data = leads_training) %>%

step_corr(all_numeric(), threshold = 0.9) %>% step_normalize(all_numeric()) %>% step_dummy(all_nominal(), -all_outcomes())
leads_recipe
Data Recipe
Inputs:
      role #variables
   outcome          1
 predictor          6

Operations:
Correlation filter on all_numeric()
Centering and scaling for all_numeric()
Dummy variables from all_nominal(), -all_outcomes()
R에서 tidymodels로 모델링하기

레시피 학습

훈련 데이터로 특성 공학 단계 학습

  • prep()
    • recipe 객체를 prep()에 전달
    • 학습 데이터로 leads_training 추가
leads_recipe_prep <- leads_recipe %>% 
  prep(training = leads_training)
leads_recipe_prep
Data Recipe
Inputs:
      role #variables
   outcome          1
 predictor          6
Training data contained 996 data points 
and no missing data.

Operations:
Correlation filter removed pages_per_visit [trained]
Centering and scaling for total_visits ... [trained]
Dummy variables from lead_source, us_location [trained]
R에서 tidymodels로 모델링하기

훈련 데이터 전처리

학습된 recipe를 훈련 데이터에 적용하고, 모델 적합용 결과를 저장

leads_training_prep <- leads_recipe_prep %>% 
  bake(new_data = NULL)

leads_training_prep
# A tibble: 996 x 11
total_visits  total_time   ... lead_source_email  lead_source_organic_search ...  us_location_west
     <dbl>      <dbl>                <dbl>                      <dbl>                    <dbl>        
 1    0.611      0.958      ...       0                          0            ...         1
 2    0.103     -0.747      ...       1                          0            ...         0
 3    0.611     -0.278      ...       0                          1            ...         1
 4   -0.151     -0.842      ...       0                          0            ...         1
 5   -0.659      1.19       ...       1                          0            ...         0 
# ... with 991 more rows
R에서 tidymodels로 모델링하기

테스트 데이터 전처리

학습된 recipe를 테스트 데이터에 적용하고, 평가용 결과를 저장

leads_test_prep <- leads_recipe_prep %>% 
  bake(new_data = leads_test)

leads_test_prep
# A tibble: 332 x 11
 total_visits  total_time  ...  lead_source_email  lead_source_organic_search ...  us_location_west
     <dbl>      <dbl>                <dbl>                      <dbl>                    <dbl>        
 1    0.864     -0.984     ...        0                          0            ...         1
 2   -0.151      1.33      ...        0                          0            ...         0
 3   -0.405     -0.843     ...        0                          1            ...         1
 4   -0.659     -1.14      ...        1                          0            ...         0
 5    1.12       0.725     ...        0                          0            ...         1   
# ... with 327 more rows
R에서 tidymodels로 모델링하기

모델 적합과 예측

fit()으로 로지스틱 회귀 모델 학습

  • 전처리된 훈련 데이터 leads_training_prep 사용

 

predict()로 예측 생성

  • 결과 클래스와 추정 확률 예측
  • 전처리된 테스트 데이터 leads_test_prep 사용
logistic_fit <- logistic_model %>% 
  fit(purchased ~ .,
      data = leads_training_prep)

 

class_preds <- predict(logistic_fit, 
                       new_data = leads_test_prep,
                       type = 'class')

prob_preds <- predict(logistic_fit, 
                      new_data = leads_test_prep,
                      type = 'prob')
R에서 tidymodels로 모델링하기

예측 결과 결합

yardstick 지표용 결과 데이터셋에 예측 결합

  • 테스트 데이터에서 실제 결과 변수 purchased 선택
  • bind_cols()로 예측 결합
leads_results <- leads_test %>% 
  select(purchased) %>%

bind_cols(class_preds, prob_preds)
leads_results
# A tibble: 332 x 4
   purchased .pred_class .pred_yes .pred_no
   <fct>     <fct>           <dbl>    <dbl>
 1 no        no             0.257     0.743
 2 yes       yes            0.896     0.104
 3 no        no             0.0852    0.915
 4 no        no             0.183     0.817
 5 yes       yes            0.776     0.224
# ... with 327 more rows
R에서 tidymodels로 모델링하기

모델 평가

yardstick으로 모델 성능 평가

  • 결과 데이터는 모든 yardstick 지표 함수에 사용 가능
  • 혼동 행렬, 민감도, 특이도 등 지표
leads_results %>% 
  conf_mat(truth = purchased, 
           estimate = .pred_class)

 

          Truth
Prediction yes  no
       yes  77  34
       no   43 178
R에서 tidymodels로 모델링하기

Ayo berlatih!

R에서 tidymodels로 모델링하기

Preparing Video For Download...