smote ( Synthetic Minority Over-sampling Technique )

개념
smote는 소수 클래스의 데이터를 합성하여 새로운 데이터를 생성하는 방식의 오버 샘플링 기법이다. knn 기반으로 새로운 데이터를 생성하여 데이터의 다양성을 증가시킨다
알고리즘
1. 소수 클래스의 데이터 샘플을 선택
2. 선택된 샘플의 knn을 찾음
3. 이웃 중 하나를 랜덤하게 선택하여 기존 데이터와의 차이를 계산
4. 랜덤한 값을 곱하고 기존 데이터에 더하여 새로운 데이터를 생성함
장점
- 기존 데이터를 단순 복제하는 것이 아니라, 새로운 데이터를 생성하여 모델의 일반화 성능을 향상시킴
- 다양한 데이터 분포를 유지하면서 소수 클래스의 샘플 수를 증가시킴
단점
- 생성된 샘플이 실제 데이터가 아니므로, 원본 데이터의 분포를 왜곡할 가능성이 있음
- 노이즈가 있는 데이터의 경우, 노이즈까지 증폭될 위험이 있음
예시 코드
from imblearn.orer_sampling import SMOTE
#sampling_strategy='auto'는 소수 클래스를 다수 클래스 만큼 생성한다
smote = SMOTE(random_state=42)
#적용
X_smote, y_smote = smote.fit_resample(X,y)
#늘어난것 확인
print(f"적용 후 데이터 {X_smote.shape}")
print(f"적용 후 클래스 수 {counter(y_smote)"})
smotenc
smote 방식으로 샘플을 만들고 그룹핑 후 가까운 클래스의 category value를 붙임
위의 smote와 달리 범주형 피쳐를 넣을 수 있다. 다만 가진 데이터에 범주형 피쳐만 있다면 사용할 수 없다
numeric variable의 값을 이용해 증식 시키기 때문이다

from imblearn.over_sampling import SMOTENC
#내가 가진 리스트
category_features = ['지역', '고객등급'] # 각각 3, 5번째 컬럼이라고 가정
#머신이 알아 듣는 리스트 (위치 번호)
category_indices = [3, 5] (예시)
#적용 예시
category_indices = [X_train.columns.get_loc(c) for c in category_features if c in X_train]
#category_features가['지역', '고객등급']라면 'category_indices는 3, 5(컬럼 순서)가 됨
smote = SMOTENC(categorical_features=category_indices, random_state=42)
-> 데이터를 받으면 3, 5 컬럼은 범주형이야.
category_indices = [X_train.columns.get_loc(c) for c in category_features if c in X_train]은 리스트 컴프리헨션을 보고 나서 적용해보고 싶어서 썼으나 더 쉽게 표현 할 수 있다.
코드를 쉽게 풀어 쓸 수 있는 방법은 두가지가 있는데 첫번째는 for문이고 두번째는 boolean이다
#for문
#빈 리스트로 만들기
category_indices = []
#category_features 리스트를 하나씩 반복
for c in category_features :
#만약 컬럼(c)가 X_train에 존재하면
if c in X_train.columns:
#그 컬럼의 위치(index)를 찾아서
index = X_train.columns.get_loc(c)
#빈 리스트에 추가
category_indices.append(index)
boolean 마스크
#X_train 전체 목록이 'category_features'에 포함되는지 확인 한 후 T/F값을
is_categorical = X_train.columns.isin(category_features)
# T/f값을 smotenc에 전달
smote=SMOTENC(categorical_features=is_categorical, random_state=42)
smote-tomek
smote로 소수 데이터를 증식 시킨 뒤 tomek links를 통해 서로 다른 클래이스이면서 가까운 샘플 쌍을 노이즈로 간주하여 제거하는 방식이다. tomek links가 노이즈를 제거하기 때문에 최종 샘플 수는 1:1로 맞춘 후 감소하게 된다
from imblearn.combine import SMOTETomek
smote_tomek = SMOTETomek.fit_resample(X,y)
X_st, y_st = smote_tomek.fit_reasmple(X,y)
print(f"적용 후 데이터 {X_st.shape}")
print(F"적용 후 클래스 {y_st.shape}")
-참고 한 사이트-
https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.SMOTENC.html
SMOTENC — Version 0.14.0
[1] (1,2) N. V. Chawla, K. W. Bowyer, L. O.Hall, W. P. Kegelmeyer, “SMOTE: synthetic minority over-sampling technique,” Journal of artificial intelligence research, 321-357, 2002.
imbalanced-learn.org
https://towardsdatascience.com/smote-synthetic-data-augmentation-for-tabular-data-1ce28090debc/
'공부 정리 > 라이브러리' 카테고리의 다른 글
| pipeline의 개념과 활용 (0) | 2025.10.27 |
|---|