안녕하세요. 이번 포스팅에서는 PCA, PLS, ICA, UMAP와 같은 차원 축소 기법을 어떻게 적용하는지 알아보려고 합니다. 사실 기본적인 Tidy Modeling의 개념은 15에서 마무리 된 것으로 보이고요. 나머지 챕터는 모델링에 있어서 필요한 기법들을 깊게 살펴보는 느낌에 가깝더라고요. 17~19 챕터랑 21 챕터는 요약에서 생략할지 고민이 되긴하네요...
16 Dimensionality Reduction | Tidy Modeling with R
The tidymodels framework is a collection of R packages for modeling and machine learning using tidyverse principles. This book provides a thorough introduction to how to use tidymodels, and an outline of good methodology and statistical practice for phases
www.tmwr.org
우선 차원 축소는 고차원의 데이터를 저차원의 데이터로 변환하는 것인데요. 쉽게 말하면 데이터 셋이 p개의 변수를 가지고 있으면 일부의 변수를 선택하든, 변수끼리 이러쿵 저러쿵 변형해서 p보다 적은 수의 변수로 변환하는 과정을 의미합니다. 변수가 많으면 모델링 할 때 항상 좋은 것은 아니기도 하고 변수의 수가 데이터 수보다 많으면 적합이 안되는 모델이 있어서 차원 축소는 모델링에서 중요한 역할을 담당하고 있습니다. 덤으로 시각화를 통해서 데이터의 관계를 이해하기도 좋고요!
- PCA : linear method + unsupervised method / step_pca
- PLS : PCA에서 주성분들과 반응변수의 공분산을 최대로 하는 변수로 supervised method / step_pls
- ICA : 다변량의 신호를 통계적으로 독립적인 성분들로 분리하는 방법 / step_ica
- UMAP : t-SNE method / embed::step_umap
실습은 본문과 같이 beans 데이터를 사용할 것이고, 아래와 같이 데이터 분할을 진행하였습니다.
### 16. Dimensionality Reduction
# >> feature engineering & EDA에 활용 가능
# >> 데이터의 수보다 설명변수가 많은 경우
# >> 다중공선성이 존재하는 경우 효과적
library(tidymodels)
library(tidyverse)
library(usemodels)
library(beans)
bean_split <- beans::beans %>% rsample::initial_validation_split(strata = class, prop = c(0.6, 0.15))
bean_train <- training(bean_split)
bean_test <- testing(bean_split)
bean_validation <- validation(bean_split)
bean_train_val <- validation_set(bean_split) # rset object to use tune_grid
우선, 차원 축소 기법을 적용하기에 앞서 변수들간의 상관관계를 확인해 봅시다.
그래프를 보면 많은 변수들의 상관계수가 높다는 것을 확인할 수 있습니다.
## Principal Component Analysis (PCA) - linear method & unsupervised
## Visulization - 1
library(corrplot)
tmwr_cols <- colorRampPalette(c("#91CBD765", "#CA225E"))
bean_train %>%
keep(is.numeric) %>%
cor() %>% corrplot(col = tmwr_cols(200),
tl.col = "black",
method = "ellipse")
## Visualization - 2
library(GGally)
bean_train %>% GGally::ggpairs(title = "bean train data visulization")
bean_train %>% select(-class) %>%
GGally::ggcorr(label = T, legend.position = "bottom", label_size = 2, label_round = 2, label_color = "grey20")
시각화를 통해 일부 변수는 비대칭 분포를 가지고 있으며 규모(Scale)에서 큰 차이가 있기 때문에 아래와 같은 전처리기-레시피 객체를 생성하였습니다.
library(bestNormalize)
bean_recipe <- recipe(class ~ ., data = bean_train) %>%
step_zv(all_predictors()) %>%
step_orderNorm(all_numeric_predictors()) %>%
step_normalize(all_numeric_predictors())
- step_zv : 단일 값을 가지는 변수를 제거하는 전처리기
- step_orderNorm : ORQ(Ordered Quantile Normalization) 변환 적용
- step_normalize : 표준화(평균이 0이고 분산이 1인 정규분포화) 적용
레시피 객체를 만들었으면 시각화를 위해 아래와 같은 사용자 지정 함수를 생성하여 여러 차원 축소 기법을 적용한 결과를 비교해 봅시다.
### Feature Extraction Techiques
library(ggforce)
plot_validation_results <- function(recipe, data = bean_validation, title=NULL){
recipe %>%
prep() %>%
bake(new_data = data) %>%
ggplot(mapping=aes(x=.panel_x, y=.panel_y,
color = class, fill = class)) +
geom_point(alpha=0.4, size = 0.5) +
geom_autodensity(alpha = 0.3) +
facet_matrix(vars(-class), layer.diag=2) +
scale_color_brewer(palette = "Dark2") +
scale_fill_brewer(palette = "Dark2") +
theme(legend.position = "top") +
ggtitle(title)}
PCA, PLS, ICA, UMAP을 적용한 결과를 비교해 봅시다.
# PCA
bean_recipe_trained %>%
step_pca(all_numeric_predictors(), num_comp = 4) %>%
plot_validation_results(title = "Principal Component Analysis")
# PLS
bean_recipe_trained %>%
step_pls(all_numeric_predictors(), outcome = "class", num_comp = 4) %>%
plot_validation_results(title = "Partial Least Squares")
# ICA
bean_recipe_trained %>%
step_ica(all_numeric_predictors(), num_comp = 4) %>%
plot_validation_results(title = "Independent Component Analysis")
# UMAP
library(embed)
bean_recipe_trained %>%
step_umap(all_numeric_predictors(), num_comp = 4) %>%
plot_validation_results(title = "UMAP")
- PCA를 적용했을 때(좌측 상단), 제1 주성분과 제2 주성분을 사용해 어느정도 분리할 수 있을 것으로 보입니다.
- PLS를 적용했을 때(우측 상단) 역시 두 개의 성분을 이용하여 콩의 종류를 분리할 수 있을 것으로 보입니다.
- ICA를 적용했을 때(좌측 하단) PCA/PLS와 다르게 ICA 성분을 이용해 구분하기가 어려워 보입니다.
- UMAP을 적용했을 때(우측 하단) 엄청나게 분리를 잘 하는 모습을 보입니다.
참고로 앞서 사용한 Recipe 객체에 적용할 수 있는 두가지 유용한 함수가 있습니다.
- prep(recipe, training) : training 데이터를 recipe 객체에 적용 (step 함수에 어떤 변수가 적용될지, 훈련 여부를 포함한 레시피 객체 반환)
- bake(recipe, new_data) : new_data에 recipe를 적용한 결과를 티블로 반환 (step 함수가 적용된 데이터)
본문에서는 여러가지 모델과 차원 축소 기법을 사용하여 최적의 모델을 선택하는 과정이 나와있으나, 저번 포스팅의 내용과 비슷하므로 생략하겠습니다. 감사합니다.
'Data Science > Modeling' 카테고리의 다른 글
[Tidymodels] Bagging Model with IBM Churn data (2) | 2024.04.03 |
---|---|
[Tidy Modeling with R] 15. Many Models with Workflow sets (0) | 2024.01.01 |
[Tidy Modeling With R] 14. Iterative Search with XGBoost (2) | 2023.12.26 |
[Tidy Modeling With R] 13. Grid Search with XGBoost (2) | 2023.12.22 |
[Tidy Modeling with R] 12. 하이퍼파라미터 튜닝 (0) | 2023.10.11 |