본문 바로가기
Data, AI, Tech. & Career

Feature Engineering 기법

by InfosGalaxy 2025. 3. 5.
반응형

Feature Engineering의 주요 기법과 예시

Feature Engineering은 머신러닝 모델의 성능을 극대화하기 위해 데이터를 변환하고 최적화하는 과정입니다. 본 문서에서는 주요 Feature Engineering 기법과 함께 구체적인 예시를 소개합니다.

Feature Engineering

1. 데이터 정제 및 전처리

데이터의 품질이 좋지 않다면 머신러닝 모델의 성능도 낮아질 수밖에 없습니다. 데이터 정제 과정은 결측치 처리, 이상치 탐지 및 제거, 중복 데이터 제거 등의 작업을 포함합니다.

 

결측치 처리:

  • 평균값 또는 중앙값으로 채우기
  • KNN Imputer를 활용하여 주변 데이터 기반으로 보완하기
  • 특정 조건을 기반으로 결측치를 예측하여 채우기
from sklearn.impute import SimpleImputer
import numpy as np

# 평균값으로 결측치 채우기
imputer = SimpleImputer(strategy='mean')
data = np.array([[1, 2, np.nan], [4, np.nan, 6], [7, 8, 9]])
imputed_data = imputer.fit_transform(data)

 

이상치 탐지:

  • Z-score 또는 IQR(Interquartile Range) 기법 활용
import numpy as np
from scipy import stats

# Z-score 이상치 탐지
data = np.array([10, 12, 15, 18, 100, 21, 22])
z_scores = np.abs(stats.zscore(data))
outliers = data[z_scores > 3]

 

중복 데이터 제거:

  • Pandas의 drop_duplicates() 사용
import pandas as pd

# 중복 행 제거
df = pd.DataFrame({'A': [1, 2, 2, 3], 'B': [4, 5, 5, 6]})
df = df.drop_duplicates()

 

2. 특징 선택 (Feature Selection)

모든 특성이 모델 성능에 기여하는 것은 아닙니다. 불필요한 특성을 제거하면 모델의 복잡도를 줄이고 과적합을 방지할 수 있습니다.

 

분산이 낮은 특성 제거 (Variance Thresholding)

from sklearn.feature_selection import VarianceThreshold

# 분산이 낮은 특성 제거
selector = VarianceThreshold(threshold=0.1)
reduced_data = selector.fit_transform(data)

 

상관관계를 활용한 중복 특성 제거

import pandas as pd
import numpy as np

# 데이터프레임 생성
np.random.seed(0)
df = pd.DataFrame(np.random.rand(100, 5), columns=['A', 'B', 'C', 'D', 'E'])

# 상관관계 분석
drop_features = [col for col in df.columns if any(df[col].corr(df[other]) > 0.9 for other in df.columns if col != other)]
df.drop(columns=drop_features, inplace=True)

 

Lasso Regression을 활용한 특성 선택

from sklearn.linear_model import Lasso

lasso = Lasso(alpha=0.1)
lasso.fit(X, y)
selected_features = X.columns[lasso.coef_ != 0]

 

3. 특징 추출 (Feature Extraction)

고차원의 데이터를 보다 유용한 저차원 표현으로 변환하는 과정입니다.

 

PCA(주성분 분석)를 활용한 차원 축소

from sklearn.decomposition import PCA

pca = PCA(n_components=2)
reduced_data = pca.fit_transform(X)

 

Word2Vec을 활용한 텍스트 데이터 임베딩

from gensim.models import Word2Vec

sentences = [['machine', 'learning', 'is', 'fun'], ['deep', 'learning', 'is', 'powerful']]
model = Word2Vec(sentences, vector_size=100, window=5, min_count=1, workers=4)
word_vector = model.wv['learning']

 

4. 특징 생성 (Feature Creation)

새로운 특징을 만들어 모델이 더 많은 패턴을 학습할 수 있도록 합니다.

 

날짜 데이터에서 요일, 월, 계절 정보 추출

import pandas as pd

df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
df['day_of_week'] = df['date'].dt.dayofweek
df['season'] = df['month'] % 12 // 3 + 1

 

카테고리 변수를 One-Hot Encoding으로 변환

from sklearn.preprocessing import OneHotEncoder

ohe = OneHotEncoder()
encoded_features = ohe.fit_transform(df[['category_feature']]).toarray()

 

수치형 변수를 조합하여 새로운 변수 생성

df['speed'] = df['distance'] / df['time']

 

5. 스케일링과 정규화

모델 학습의 속도를 높이고, 일부 알고리즘(KNN, SVM 등)의 성능을 개선하기 위해 데이터의 크기를 조정하는 과정입니다.

 

Min-Max Scaling (0-1 범위 정규화)

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(X)

Standard Scaling (평균 0, 분산 1 정규화)

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
normalized_data = scaler.fit_transform(X)

 

Feature Engineering은 모델의 성능을 최적화하는 중요한 과정입니다. 위에서 소개한 기법들을 적절히 활용하면 데이터의 품질을 높이고, 모델의 성능을 극대화할 수 있습니다.

반응형