콘텐츠 대표 이미지 - 데이터 전처리의 모든 것: 실전에서 바로 쓰는 파이썬 팁과 트릭 🧙‍♂️
# 데이터 전처리 기법: 실전 팁과 트릭 🚀

데이터 전처리의 모든 것: 실전에서 바로 쓰는 파이썬 팁과 트릭 🧙‍♂️

안녕? 오늘은 데이터 분석과 머신러닝의 성패를 좌우하는 데이터 전처리 기법에 대해 함께 알아볼 거야. 데이터 과학자들 사이에서는 "전체 작업의 80%는 데이터 전처리다"라는 말이 있을 정도로 중요한 과정이지. 😉

이 글에서는 Python을 활용한 실전 데이터 전처리 기법을 처음부터 끝까지 다룰 거야. 초보자부터 중급자까지 모두 유용하게 활용할 수 있는 내용으로 준비했어. 마치 친한 친구가 옆에서 알려주는 것처럼 쉽고 재미있게 설명할게! 👨‍💻

데이터 전처리 워크플로우 데이터 수집 데이터 정제 특성 엔지니어링 데이터 변환 원시 데이터 확보 결측치/이상치 처리 새로운 특성 생성 정규화/표준화 전처리 품질 = 모델 성능 "Garbage In, Garbage Out" 좋은 데이터가 좋은 결과를 만든다

📚 목차

  1. 데이터 전처리의 중요성
  2. 데이터 탐색 및 이해하기
  3. 결측치 처리 기법
  4. 이상치 탐지 및 처리
  5. 데이터 정규화와 표준화
  6. 범주형 데이터 인코딩
  7. 특성 엔지니어링 기법
  8. 차원 축소 기법
  9. 데이터 불균형 처리
  10. 효율적인 데이터 전처리 파이프라인 구축
  11. 실전 프로젝트: 전처리 종합 실습

1. 데이터 전처리의 중요성 🔍

데이터 전처리는 왜 그렇게 중요할까? 간단히 말하자면, 좋은 데이터가 좋은 모델을 만든다는 원칙 때문이야. 아무리 복잡하고 정교한 알고리즘을 사용해도 입력 데이터가 엉망이라면 결과도 엉망이 되지. 이걸 "Garbage In, Garbage Out" 원칙이라고 부르기도 해. 🗑️

실제로 많은 데이터 과학자들이 프로젝트 시간의 대부분을 데이터 전처리에 쓰고 있어. 재능넷에서 데이터 분석 관련 재능을 거래할 때도 전처리 능력이 핵심 역량으로 평가되는 이유가 바로 이 때문이지. 전처리를 잘하면 모델 성능이 크게 향상되고, 분석 결과의 신뢰성도 높아진단다. 👍

데이터 전처리가 필요한 이유

  1. 결측치와 이상치 제거: 불완전하거나 왜곡된 데이터는 분석 결과를 크게 훼손시킬 수 있어.
  2. 데이터 형식 통일: 다양한 소스에서 수집된 데이터는 형식이 제각각이라 통일이 필요해.
  3. 모델 요구사항 충족: 많은 알고리즘은 특정 형태의 입력 데이터를 요구해.
  4. 계산 효율성 향상: 적절히 전처리된 데이터는 모델 학습 속도를 크게 향상시켜.
  5. 특성 간 스케일 조정: 서로 다른 단위의 특성들을 비교 가능하게 만들어줘.

이제 본격적으로 Python을 활용한 데이터 전처리 기법들을 하나씩 살펴볼게. 각 단계마다 실제 코드 예제와 함께 설명할 거니까 따라오면서 직접 실습해보면 더 효과적일 거야! 💻

2. 데이터 탐색 및 이해하기 🔎

데이터 전처리를 시작하기 전에 가장 먼저 해야 할 일은 데이터를 제대로 이해하는 거야. 이 단계를 EDA(Exploratory Data Analysis, 탐색적 데이터 분석)라고 부르지. 데이터의 특성, 분포, 관계 등을 파악하면 어떤 전처리가 필요한지 감이 올 거야. 📊

기본 라이브러리 불러오기


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# 경고 메시지 무시 설정
import warnings
warnings.filterwarnings('ignore')

# 그래프 스타일 설정
plt.style.use('ggplot')
sns.set(style="whitegrid")
    

데이터 기본 정보 확인하기

먼저 데이터의 기본 구조와 특성을 파악해보자. 🧐


# 데이터 로드 (예: Titanic 데이터셋)
df = pd.read_csv('titanic.csv')

# 데이터 상위 5행 확인
print(df.head())

# 데이터 기본 정보 확인
print(df.info())

# 수치형 데이터 통계 요약
print(df.describe())

# 범주형 데이터 통계 요약
print(df.describe(include=['O']))
    

df.info()는 각 컬럼의 데이터 타입과 결측치 수를 보여주고, df.describe()는 수치형 데이터의 통계적 특성(평균, 표준편차, 최소/최대값 등)을 보여줘. 이 정보들을 통해 데이터의 전반적인 특성을 파악할 수 있어. 👀

데이터 시각화로 분포 파악하기

시각화는 데이터의 패턴과 이상치를 직관적으로 파악하는 데 큰 도움이 돼. 😎


# 수치형 변수 분포 확인
plt.figure(figsize=(15, 10))
for i, column in enumerate(['Age', 'Fare']):
    plt.subplot(2, 2, i+1)
    sns.histplot(df[column].dropna(), kde=True)
    plt.title(f'{column} Distribution')

# 범주형 변수 분포 확인
plt.subplot(2, 2, 3)
sns.countplot(x='Pclass', data=df)
plt.title('Passenger Class Distribution')

plt.subplot(2, 2, 4)
sns.countplot(x='Sex', data=df)
plt.title('Gender Distribution')

plt.tight_layout()
plt.show()
    

변수 간 관계 파악하기

변수들 사이의 관계를 이해하면 특성 엔지니어링이나 모델링에 큰 도움이 돼. 🔄


# 상관관계 히트맵
numeric_df = df.select_dtypes(include=[np.number])
plt.figure(figsize=(12, 10))
sns.heatmap(numeric_df.corr(), annot=True, cmap='coolwarm', linewidths=0.5)
plt.title('Correlation Heatmap')
plt.show()

# 생존 여부에 따른 나이 분포 비교
plt.figure(figsize=(10, 6))
sns.boxplot(x='Survived', y='Age', data=df)
plt.title('Age Distribution by Survival')
plt.show()
    

이런 탐색 과정을 통해 어떤 변수에 결측치가 많은지, 어떤 변수의 분포가 치우쳐 있는지, 이상치는 어디에 있는지 등을 파악할 수 있어. 이제 이 정보를 바탕으로 구체적인 전처리 작업을 시작해보자! 🚀

3. 결측치 처리 기법 🧩

결측치(Missing Values)는 데이터셋에서 값이 없는 부분을 말해. 이런 결측치는 분석이나 모델링에 문제를 일으킬 수 있어서 적절히 처리해줘야 해. 🔧

결측치 확인하기


# 결측치 개수 확인
print(df.isnull().sum())

# 결측치 비율 확인
print(df.isnull().mean() * 100)

# 결측치 시각화
plt.figure(figsize=(12, 6))
sns.heatmap(df.isnull(), cbar=False, cmap='viridis')
plt.title('Missing Value Heatmap')
plt.show()
    

결측치 처리 방법

결측치를 처리하는 방법은 여러 가지가 있어. 상황에 맞게 적절한 방법을 선택하는 게 중요해! 👇

  1. 삭제(Deletion): 결측치가 있는 행이나 열을 제거
  2. 대체(Imputation): 결측치를 다른 값으로 대체
  3. 예측(Prediction): 다른 변수를 사용해 결측치 예측

1) 결측치 삭제하기


# 결측치가 있는 행 삭제
df_dropped_rows = df.dropna()

# 결측치가 50% 이상인 열 삭제
threshold = len(df) * 0.5
df_dropped_cols = df.dropna(axis=1, thresh=threshold)

# 특정 열에 결측치가 있는 행만 삭제
df_dropped_specific = df.dropna(subset=['Age'])
    

주의! 삭제 방법은 간단하지만, 데이터의 양이 크게 줄어들거나 중요한 정보가 손실될 수 있어. 결측치 비율이 낮을 때만 사용하는 게 좋아. ⚠️

2) 결측치 대체하기


# 평균값으로 대체
df_mean = df.copy()
df_mean['Age'].fillna(df['Age'].mean(), inplace=True)

# 중앙값으로 대체
df_median = df.copy()
df_median['Age'].fillna(df['Age'].median(), inplace=True)

# 최빈값으로 대체
df_mode = df.copy()
df_mode['Embarked'].fillna(df['Embarked'].mode()[0], inplace=True)

# 앞/뒤 값으로 채우기 (시계열 데이터에 유용)
df_ffill = df.copy()
df_ffill.fillna(method='ffill', inplace=True)  # 앞의 값으로 채우기
df_bfill = df.copy()
df_bfill.fillna(method='bfill', inplace=True)  # 뒤의 값으로 채우기
    

3) 고급 결측치 대체 기법


# 그룹별 통계로 대체하기
df_group = df.copy()
df_group['Age'] = df_group.groupby('Pclass')['Age'].transform(
    lambda x: x.fillna(x.median())
)

# KNN 기반 결측치 대체
from sklearn.impute import KNNImputer

# 수치형 변수만 선택
numeric_cols = ['Age', 'SibSp', 'Parch', 'Fare']
numeric_df = df[numeric_cols].copy()

# KNN 대체
imputer = KNNImputer(n_neighbors=5)
imputed_array = imputer.fit_transform(numeric_df)
df_knn = df.copy()
df_knn[numeric_cols] = imputed_array
    

4) 결측 여부를 나타내는 새 특성 만들기

결측 자체가 의미 있는 정보일 수 있을 때 유용한 방법이야. 🧠


# 결측 여부를 나타내는 새 특성 추가
df_indicator = df.copy()
df_indicator['Age_missing'] = df_indicator['Age'].isnull().astype(int)
df_indicator['Cabin_missing'] = df_indicator['Cabin'].isnull().astype(int)

# 결측치 대체 후 사용
df_indicator['Age'].fillna(df_indicator['Age'].median(), inplace=True)
    

결측치 처리 방법은 데이터의 특성과 분석 목적에 따라 달라질 수 있어. 여러 방법을 시도해보고 모델 성능을 비교하는 것이 좋은 접근법이야. 재능넷에서 데이터 분석 서비스를 제공하는 전문가들도 이런 다양한 접근법을 시도해보며 최적의 방법을 찾아내지. 🔍

4. 이상치 탐지 및 처리 🕵️‍♂️

이상치(Outliers)는 다른 데이터와 크게 다른 값을 가진 데이터 포인트를 말해. 이런 이상치는 통계 분석이나 모델링에 큰 영향을 미칠 수 있어서 적절히 처리해야 해. 📉

이상치 탐지 방법

1) 시각화를 통한 이상치 탐지


# 박스플롯으로 이상치 확인
plt.figure(figsize=(12, 6))
sns.boxplot(x='Pclass', y='Fare', data=df)
plt.title('Fare Distribution by Passenger Class')
plt.show()

# 산점도로 이상치 확인
plt.figure(figsize=(10, 6))
sns.scatterplot(x='Age', y='Fare', hue='Survived', data=df)
plt.title('Age vs Fare with Survival')
plt.show()
    

2) 통계적 방법으로 이상치 탐지

Z-점수 방법: 데이터가 평균에서 얼마나 떨어져 있는지 표준편차 단위로 측정해. |Z| > 3인 데이터를 이상치로 간주하는 경우가 많아. 🧮


# Z-점수 계산
from scipy import stats

z_scores = stats.zscore(df['Fare'].dropna())
abs_z_scores = np.abs(z_scores)
outliers_z = (abs_z_scores > 3)
print(f'Z-score 방법으로 탐지된 이상치 개수: {outliers_z.sum()}')

# 이상치 인덱스 확인
outlier_indices = np.where(abs_z_scores > 3)[0]
print(f'이상치 인덱스: {outlier_indices}')
    

IQR(사분위수 범위) 방법: 박스플롯의 원리를 이용한 방법으로, Q1 - 1.5*IQR 미만이거나 Q3 + 1.5*IQR 초과인 값을 이상치로 간주해. 📏


# IQR 방법으로 이상치 탐지
Q1 = df['Fare'].quantile(0.25)
Q3 = df['Fare'].quantile(0.75)
IQR = Q3 - Q1

lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

outliers_iqr = ((df['Fare'] < lower_bound) | (df['Fare'] > upper_bound))
print(f'IQR 방법으로 탐지된 이상치 개수: {outliers_iqr.sum()}')
    

3) 기계학습 기반 이상치 탐지

복잡한 데이터셋에서는 단순한 통계적 방법보다 기계학습 기반 방법이 더 효과적일 수 있어. 🤖


# Isolation Forest로 이상치 탐지
from sklearn.ensemble import IsolationForest

# 수치형 변수만 선택
numeric_cols = ['Age', 'SibSp', 'Parch', 'Fare']
X = df[numeric_cols].dropna()

# 모델 학습 및 예측
iso_forest = IsolationForest(contamination=0.05, random_state=42)
outliers_if = iso_forest.fit_predict(X)
outliers_if = (outliers_if == -1)  # -1은 이상치를 의미

print(f'Isolation Forest로 탐지된 이상치 개수: {outliers_if.sum()}')
    

# DBSCAN으로 이상치 탐지
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler

# 데이터 스케일링
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# DBSCAN 적용
dbscan = DBSCAN(eps=0.5, min_samples=5)
clusters = dbscan.fit_predict(X_scaled)
outliers_dbscan = (clusters == -1)  # -1은 이상치(노이즈)를 의미

print(f'DBSCAN으로 탐지된 이상치 개수: {outliers_dbscan.sum()}')
    

이상치 처리 방법

이상치를 발견했다면, 어떻게 처리할지 결정해야 해. 여기 몇 가지 방법을 소개할게. 🛠️

1) 이상치 제거


# Z-점수 기반 이상치 제거
df_no_outliers_z = df[~(abs_z_scores > 3)]

# IQR 기반 이상치 제거
df_no_outliers_iqr = df[~((df['Fare'] < lower_bound) | (df['Fare'] > upper_bound))]
    

2) 이상치 대체


# 이상치를 경계값으로 대체 (Capping/Winsorization)
df_capped = df.copy()
df_capped.loc[df_capped['Fare'] > upper_bound, 'Fare'] = upper_bound
df_capped.loc[df_capped['Fare'] < lower_bound, 'Fare'] = lower_bound
    

3) 이상치 변환


# 로그 변환으로 이상치 영향 감소
df_log = df.copy()
df_log['Fare_log'] = np.log1p(df_log['Fare'])  # log(1+x) 변환

# 제곱근 변환
df_sqrt = df.copy()
df_sqrt['Fare_sqrt'] = np.sqrt(df_sqrt['Fare'])
    

주의사항: 이상치가 실제 오류인지, 아니면 중요한 정보를 담고 있는지 신중하게 판단해야 해. 무조건 제거하는 것보다 데이터의 특성과 도메인 지식을 고려해서 처리하는 게 중요해. 🧐

이상치 처리는 데이터 과학에서 예술과도 같은 영역이야. 재능넷에서 활동하는 데이터 분석가들도 이런 미묘한 판단을 통해 데이터의 품질을 높이고 있지. 이상치를 어떻게 처리하느냐에 따라 모델의 성능이 크게 달라질 수 있으니 신중하게 접근하자! 🎯

5. 데이터 정규화와 표준화 📊

서로 다른 스케일을 가진 특성들이 있을 때, 이를 비슷한 범위로 조정해주는 과정이 필요해. 이런 과정을 특성 스케일링(Feature Scaling)이라고 하는데, 주로 정규화(Normalization)와 표준화(Standardization)가 사용돼. 🔄

왜 스케일링이 필요할까?

스케일링이 필요한 이유는 여러 가지가 있어:

  1. 거리 기반 알고리즘(KNN, K-means 등)은 스케일에 민감해.
  2. 경사 하강법을 사용하는 알고리즘은 수렴 속도가 개선돼.
  3. 정규화 항(L1, L2)이 모든 특성에 균등하게 적용돼.
  4. 특성 간 중요도를 공정하게 비교할 수 있어.
데이터 스케일링 비교 원본 데이터 X (0-1000) Y (0-100) 정규화 (Min-Max) X (0-1) Y (0-1) 표준화 (Z-score) X (μ=0, σ=1) Y (μ=0, σ=1) 스케일링 후 알고리즘 성능 향상 및 수렴 속도 개선 거리 기반 알고리즘(KNN, K-means)과 경사 하강법에 특히 중요

Min-Max 정규화 (Normalization)

모든 값을 0과 1 사이로 변환하는 방법이야. 특히 신경망의 입력값으로 많이 사용돼. 🧠


from sklearn.preprocessing import MinMaxScaler

# 정규화할 특성 선택
features_to_scale = ['Age', 'Fare']
df_norm = df.copy()

# Min-Max 정규화 적용
scaler = MinMaxScaler()
df_norm[features_to_scale] = scaler.fit_transform(df[features_to_scale].fillna(0))

print(df_norm[features_to_scale].describe())
    

수식으로는 다음과 같이 표현돼: X_norm = (X - X_min) / (X_max - X_min)

Z-점수 표준화 (Standardization)

평균이 0, 표준편차가 1이 되도록 변환하는 방법이야. 이상치에 덜 민감하고 선형 모델에 적합해. 📈


from sklearn.preprocessing import StandardScaler

# 표준화할 특성 선택
df_std = df.copy()

# Z-점수 표준화 적용
scaler = StandardScaler()
df_std[features_to_scale] = scaler.fit_transform(df[features_to_scale].fillna(0))

print(df_std[features_to_scale].describe())
    

수식으로는 다음과 같이 표현돼: X_std = (X - μ) / σ

로버스트 스케일링 (Robust Scaling)

이상치에 강건한 스케일링 방법으로, 중앙값과 IQR을 사용해. 이상치가 많은 데이터에 유용해. 🛡️


from sklearn.preprocessing import RobustScaler

# 로버스트 스케일링 적용
df_robust = df.copy()
scaler = RobustScaler()
df_robust[features_to_scale] = scaler.fit_transform(df[features_to_scale].fillna(0))

print(df_robust[features_to_scale].describe())
    

수식으로는 다음과 같이 표현돼: X_robust = (X - median) / IQR

MaxAbs 스케일링

각 특성의 최대 절대값으로 나누는 방법으로, 희소 데이터(sparse data)에 유용해. 0을 보존하는 특징이 있어. 🔢


from sklearn.preprocessing import MaxAbsScaler

# MaxAbs 스케일링 적용
df_maxabs = df.copy()
scaler = MaxAbsScaler()
df_maxabs[features_to_scale] = scaler.fit_transform(df[features_to_scale].fillna(0))

print(df_maxabs[features_to_scale].describe())
    

어떤 스케일링 방법을 선택해야 할까?

  1. MinMaxScaler: 데이터 분포가 정규분포가 아닐 때, 신경망 입력값으로 사용할 때
  2. StandardScaler: 선형 모델(회귀, SVM 등)에 사용할 때, 데이터가 정규분포에 가까울 때
  3. RobustScaler: 이상치가 많은 데이터에 사용할 때
  4. MaxAbsScaler: 희소 데이터를 다룰 때, 0 값을 보존하고 싶을 때

스케일링은 모델 성능에 큰 영향을 미칠 수 있어. 재능넷에서 데이터 분석 서비스를 찾는다면, 이런 세부적인 전처리 기법에 능숙한 전문가를 만날 수 있을 거야. 여러 방법을 실험해보고 모델 성능을 비교해보는 것이 좋은 접근법이야! 🚀

6. 범주형 데이터 인코딩 🏷️

머신러닝 알고리즘은 대부분 숫자 데이터만 처리할 수 있어. 그래서 범주형 데이터(문자열, 레이블 등)를 숫자로 변환하는 과정이 필요한데, 이를 인코딩(Encoding)이라고 해. 🔄

범주형 데이터 탐색하기


# 데이터셋의 범주형 변수 확인
categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
print(f'범주형 변수: {categorical_cols}')

# 각 범주형 변수의 고유값 확인
for col in categorical_cols:
    unique_values = df[col].unique()
    print(f'{col}: {len(unique_values)} 개의 고유값')
    print(unique_values[:10])  # 처음 10개만 출력
    

1. 레이블 인코딩 (Label Encoding)

각 범주에 고유한 정수를 할당하는 방법이야. 순서가 있는 범주형 데이터에 적합해. 🔢


from sklearn.preprocessing import LabelEncoder

# 레이블 인코딩 적용
df_label = df.copy()
le = LabelEncoder()
df_label['Sex_encoded'] = le.fit_transform(df['Sex'])

print(df_label[['Sex', 'Sex_encoded']].head())
print(f'매핑: {dict(zip(le.classes_, le.transform(le.classes_)))}')
    

주의! 레이블 인코딩은 범주 간에 순서 관계가 없는데도 숫자의 크기 관계가 생기므로, 일부 알고리즘에서는 잘못된 관계를 학습할 수 있어. 의사결정트리 계열 알고리즘에서는 괜찮지만, 선형 모델에서는 문제가 될 수 있어. ⚠️

2. 원-핫 인코딩 (One-Hot Encoding)

각 범주를 이진 벡터로 표현하는 방법이야. 범주 간 순서가 없을 때 가장 널리 사용돼. 🔥


# pandas의 get_dummies 사용
df_onehot = df.copy()
df_onehot = pd.get_dummies(df_onehot, columns=['Sex', 'Embarked'], drop_first=False)

print(df_onehot.head())

# scikit-learn의 OneHotEncoder 사용
from sklearn.preprocessing import OneHotEncoder

# 원-핫 인코딩 적용
encoder = OneHotEncoder(sparse=False, drop=None)
encoded_features = encoder.fit_transform(df[['Sex', 'Embarked']])

# 결과를 DataFrame으로 변환
encoded_df = pd.DataFrame(
    encoded_features,
    columns=encoder.get_feature_names_out(['Sex', 'Embarked'])
)

print(encoded_df.head())
    

drop_first=True 옵션을 사용하면 다중공선성(multicollinearity) 문제를 방지할 수 있어. 이를 더미 인코딩(Dummy Encoding)이라고도 불러. 🧩

3. 빈도 인코딩 (Frequency Encoding)

각 범주의 빈도(또는 비율)로 인코딩하는 방법이야. 높은 차원의 범주형 변수에 유용해. 📊


# 빈도 인코딩 적용
df_freq = df.copy()
for col in ['Embarked', 'Cabin']:
    # 결측치 처리
    if df_freq[col].isnull().any():
        df_freq[col].fillna('Missing', inplace=True)
    
    # 빈도 계산
    frequency = df_freq[col].value_counts(normalize=True)
    df_freq[f'{col}_freq'] = df_freq[col].map(frequency)

print(df_freq[['Embarked', 'Embarked_freq']].head(10))
    

4. 타겟 인코딩 (Target Encoding)

타겟 변수의 평균값으로 범주를 인코딩하는 방법이야. 높은 차원의 범주형 변수에 효과적이지만, 과적합에 주의해야 해. 🎯


# 타겟 인코딩 적용
df_target = df.copy()

# 간단한 타겟 인코딩 구현
for col in ['Embarked', 'Pclass']:
    # 각 범주별 타겟 평균 계산
    target_means = df_target.groupby(col)['Survived'].mean()
    df_target[f'{col}_target'] = df_target[col].map(target_means)

print(df_target[['Embarked', 'Survived', 'Embarked_target']].head(10))

# 교차 검증을 사용한 타겟 인코딩 (과적합 방지)
from sklearn.model_selection import KFold

def target_encode_cv(df, col, target, n_folds=5):
    df_result = df.copy()
    kf = KFold(n_splits=n_folds, shuffle=True, random_state=42)
    df_result[f'{col}_target_cv'] = np.nan
    
    for train_idx, test_idx in kf.split(df):
        # 훈련 세트에서 인코딩 맵 생성
        target_means = df.iloc[train_idx].groupby(col)[target].mean()
        # 테스트 세트에 적용
        df_result.iloc[test_idx, df_result.columns.get_loc(f'{col}_target_cv')] = \
            df.iloc[test_idx][col].map(target_means)
    
    return df_result

df_target_cv = target_encode_cv(df, 'Embarked', 'Survived')
print(df_target_cv[['Embarked', 'Survived', 'Embarked_target_cv']].head(10))
    

5. 해시 인코딩 (Hash Encoding)

해시 함수를 사용해 고차원 범주형 변수를 저차원으로 축소하는 방법이야. 메모리 효율적이고 온라인 학습에 적합해. 🔐


from sklearn.feature_extraction import FeatureHasher

# 해시 인코딩 적용
df_hash = df.copy()
hasher = FeatureHasher(n_features=8, input_type='string')

# 'Cabin' 열에 해시 인코딩 적용
cabin_values = df_hash['Cabin'].fillna('Missing').values.reshape(-1, 1)
hashed_features = hasher.transform(cabin_values).toarray()

# 결과를 DataFrame에 추가
hashed_df = pd.DataFrame(
    hashed_features,
    columns=[f'Cabin_hash_{i}' for i in range(8)]
)

df_hash = pd.concat([df_hash, hashed_df], axis=1)
print(df_hash.head())
    

6. 임베딩 (Embeddings)

딥러닝을 사용해 범주를 저차원 벡터로 표현하는 방법이야. 범주 간의 의미적 관계를 포착할 수 있어. 🧠


# 간단한 임베딩 예시 (Keras 사용)
import tensorflow as tf
from tensorflow.keras.layers import Embedding, Input, Dense, Flatten
from tensorflow.keras.models import Model

# 예시 데이터 준비
df_emb = df.copy()
df_emb['Pclass'] = df_emb['Pclass'].astype('str')  # 문자열로 변환
pclass_values = df_emb['Pclass'].fillna('0').astype('str')

# 범주 매핑
pclass_mapping = {val: idx for idx, val in enumerate(pclass_values.unique())}
pclass_encoded = pclass_values.map(pclass_mapping).values

# 임베딩 모델 생성
n_categories = len(pclass_mapping)
embedding_dim = 2  # 임베딩 차원

input_layer = Input(shape=(1,))
embedding_layer = Embedding(input_dim=n_categories, output_dim=embedding_dim, input_length=1)(input_layer)
flatten_layer = Flatten()(embedding_layer)
output_layer = Dense(1, activation='sigmoid')(flatten_layer)

model = Model(inputs=input_layer, outputs=output_layer)
model.compile(optimizer='adam', loss='binary_crossentropy')

# 모델 학습
model.fit(
    pclass_encoded.reshape(-1, 1),
    df_emb['Survived'].values,
    epochs=10,
    batch_size=32,
    verbose=0
)

# 학습된 임베딩 추출
embeddings = model.layers[1].get_weights()[0]
print("학습된 임베딩:")
for category, idx in pclass_mapping.items():
    print(f"범주 {category}: {embeddings[idx]}")
    

인코딩 방법 선택 가이드

  1. 원-핫 인코딩: 범주 수가 적을 때(10-20개 미만), 범주 간 순서가 없을 때
  2. 레이블 인코딩: 범주에 순서가 있을 때, 트리 기반 모델 사용 시
  3. 빈도/타겟 인코딩: 범주 수가 많을 때(100개 이상), 메모리 효율성이 중요할 때
  4. 해시 인코딩: 범주 수가 매우 많을 때, 온라인 학습 시
  5. 임베딩: 범주 간 관계가 복잡할 때, 딥러닝 모델 사용 시

범주형 데이터 인코딩은 모델 성능에 큰 영향을 미치는 중요한 전처리 단계야. 재능넷에서 데이터 분석 프로젝트를 의뢰할 때, 이런 세부적인 인코딩 기법에 대한 지식을 갖춘 전문가를 찾는 것이 좋을 거야. 데이터의 특성과 모델에 맞는 인코딩 방법을 선택하는 것이 성공의 열쇠야! 🔑

7. 특성 엔지니어링 기법 🛠️

특성 엔지니어링(Feature Engineering)은 원본 데이터에서 모델 성능을 향상시키는 새로운 특성을 만들어내는 과정이야. 데이터 과학에서 가장 창의적이고 도메인 지식이 중요한 부분이라고 할 수 있지. 🧪

특성 엔지니어링의 중요성

Andrew Ng은 "머신러닝에서 특성 엔지니어링은 모델 선택보다 더 중요하다"라고 말했어. 좋은 특성은 간단한 모델로도 뛰어난 성능을 낼 수 있게 해주지. 🚀

1. 수학적 변환

기존 특성에 수학적 연산을 적용해 새로운 특성을 만드는 방법이야. 📐


# 기본적인 수학적 변환
df_math = df.copy()

# 로그 변환 (치우친 분포 정규화)
df_math['Fare_log'] = np.log1p(df_math['Fare'])

# 제곱근 변환
df_math['Fare_sqrt'] = np.sqrt(df_math['Fare'])

# 제곱 변환
df_math['Age_squared'] = df_math['Age'] ** 2

# 다항식 특성 (Polynomial Features)
from sklearn.preprocessing import PolynomialFeatures

# 'Age'와 'Fare' 특성에 다항식 변환 적용
poly = PolynomialFeatures(degree=2, include_bias=False)
poly_features = poly.fit_transform(df[['Age', 'Fare']].fillna(0))

# 결과를 DataFrame으로 변환
poly_df = pd.DataFrame(
    poly_features,
    columns=poly.get_feature_names_out(['Age', 'Fare'])
)

print(poly_df.head())
    

2. 집계 특성 (Aggregation Features)

그룹별 통계량을 새로운 특성으로 사용하는 방법이야. 데이터의 계층 구조를 활용할 수 있어. 📊


# 그룹별 집계 특성 생성
df_agg = df.copy()

# 객실 등급별 평균 요금
pclass_fare_mean = df_agg.groupby('Pclass')['Fare'].mean()
df_agg['Pclass_fare_mean'] = df_agg['Pclass'].map(pclass_fare_mean)

# 객실 등급별 생존율
pclass_survival_rate = df_agg.groupby('Pclass')['Survived'].mean()
df_agg['Pclass_survival_rate'] = df_agg['Pclass'].map(pclass_survival_rate)

# 성별 및 객실 등급별 생존율
sex_pclass_survival = df_agg.groupby(['Sex', 'Pclass'])['Survived'].mean()
df_agg['Sex_Pclass_survival'] = df_agg.apply(
    lambda x: sex_pclass_survival.get((x['Sex'], x['Pclass']), np.nan), axis=1
)

print(df_agg[['Pclass', 'Sex', 'Pclass_fare_mean', 'Pclass_survival_rate', 'Sex_Pclass_survival']].head())
    

3. 상호작용 특성 (Interaction Features)

두 개 이상의 특성을 조합해 새로운 특성을 만드는 방법이야. 특성 간의 관계를 모델링할 수 있어. 🔄


# 상호작용 특성 생성
df_interact = df.copy()

# 곱셈 상호작용
df_interact['Age_Fare'] = df_interact['Age'] * df_interact['Fare']

# 합 상호작용
df_interact['SibSp_Parch'] = df_interact['SibSp'] + df_interact['Parch']
df_interact['Family_Size'] = df_interact['SibSp_Parch'] + 1  # 본인 포함

# 비율 상호작용
df_interact['Fare_Per_Person'] = df_interact['Fare'] / (df_interact['Family_Size'])

# 범주형 변수 조합
df_interact['Sex_Pclass'] = df_interact['Sex'] + '_' + df_interact['Pclass'].astype(str)

print(df_interact[['Age', 'Fare', 'Age_Fare', 'SibSp', 'Parch', 'Family_Size', 'Fare_Per_Person']].head())
    

4. 시간 기반 특성 (Time-Based Features)

시간 데이터에서 유용한 정보를 추출하는 방법이야. 시계열 데이터 분석에 필수적이지. 🕒


# 시간 기반 특성 생성 (예시를 위한 가상의 날짜 데이터)
import datetime

# 가상의 날짜 데이터 생성
np.random.seed(42)
start_date = datetime.datetime(1912, 4, 10)
dates = [start_date + datetime.timedelta(days=np.random.randint(0, 30)) for _ in range(len(df))]

df_time = df.copy()
df_time['Date'] = dates

# 날짜에서 다양한 특성 추출
df_time['Year'] = df_time['Date'].dt.year
df_time['Month'] = df_time['Date'].dt.month
df_time['Day'] = df_time['Date'].dt.day
df_time['Weekday'] = df_time['Date'].dt.weekday
df_time['Is_Weekend'] = df_time['Weekday'].isin([5, 6]).astype(int)
df_time['Week_of_Year'] = df_time['Date'].dt.isocalendar().week

# 시간 간격 계산
df_time['Days_Since_Start'] = (df_time['Date'] - start_date).dt.days

print(df_time[['Date', 'Year', 'Month', 'Day', 'Weekday', 'Is_Weekend', 'Days_Since_Start']].head())
    

5. 텍스트 기반 특성 (Text-Based Features)

텍스트 데이터에서 유용한 정보를 추출하는 방법이야. NLP 작업에 중요해. 📝


# 텍스트 기반 특성 생성 (Name 열 사용)
df_text = df.copy()

# 이름 길이
df_text['Name_Length'] = df_text['Name'].str.len()

# 단어 수
df_text['Name_Word_Count'] = df_text['Name'].str.split().str.len()

# 특정 패턴 추출 (타이틀 추출)
df_text['Title'] = df_text['Name'].str.extract(r' ([A-Za-z]+)\.', expand=False)

# 타이틀 그룹화
title_mapping = {
    'Mr': 'Mr',
    'Miss': 'Miss',
    'Mrs': 'Mrs',
    'Master': 'Master',
    'Dr': 'Officer',
    'Rev': 'Officer',
    'Col': 'Officer',
    'Major': 'Officer',
    'Mlle': 'Miss',
    'Mme': 'Mrs',
    'Don': 'Royalty',
    'Sir': 'Royalty',
    'Lady': 'Royalty',
    'Countess': 'Royalty',
    'Jonkheer': 'Royalty',
    'Dona': 'Royalty',
    'Capt': 'Officer'
}

df_text['Title_Grouped'] = df_text['Title'].map(title_mapping).fillna('Other')

print(df_text[['Name', 'Name_Length', 'Name_Word_Count', 'Title', 'Title_Grouped']].head())
    

6. 위치 기반 특성 (Location-Based Features)

지리적 데이터에서 유용한 정보를 추출하는 방법이야. 위치 기반 서비스에 중요해. 🌍


# 위치 기반 특성 생성 (가상의 위도/경도 데이터)
np.random.seed(42)
df_geo = df.copy()

# 가상의 위도/경도 데이터 생성
df_geo['Latitude'] = np.random.uniform(50, 55, len(df))
df_geo['Longitude'] = np.random.uniform(-10, -5, len(df))

# 하버사인 거리 계산 함수
from math import radians, sin, cos, sqrt, asin

def haversine_distance(lat1, lon1, lat2, lon2):
    """두 지점 간의 거리를 km 단위로 계산"""
    R = 6371  # 지구 반경 (km)
    
    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
    
    dlat = lat2 - lat1
    dlon = lon2 - lon1
    
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    
    return R * c

# 기준점으로부터의 거리 계산
reference_lat, reference_lon = 51.5, -8.0  # 가상의 기준점
df_geo['Distance_From_Ref'] = df_geo.apply(
    lambda row: haversine_distance(row['Latitude'], row['Longitude'], reference_lat, reference_lon),
    axis=1
)

# 클러스터링으로 위치 그룹화
from sklearn.cluster import KMeans

coords = df_geo[['Latitude', 'Longitude']].values
kmeans = KMeans(n_clusters=3, random_state=42).fit(coords)
df_geo['Location_Cluster'] = kmeans.labels_

print(df_geo[['Latitude', 'Longitude', 'Distance_From_Ref', 'Location_Cluster']].head())
    

7. 도메인 지식 기반 특성 (Domain Knowledge Features)

특정 분야의 전문 지식을 활용해 만드는 특성이야. 가장 강력한 특성이 될 수 있어. 🧠


# 도메인 지식 기반 특성 생성 (타이타닉 데이터셋 예시)
df_domain = df.copy()

# 가족 크기 (도메인 지식: 가족 단위로 생존율이 달라질 수 있음)
df_domain['Family_Size'] = df_domain['SibSp'] + df_domain['Parch'] + 1

# 가족 크기 범주화
df_domain['Family_Size_Category'] = pd.cut(
    df_domain['Family_Size'],
    bins=[0, 1, 4, float('inf')],
    labels=['Alone', 'Small', 'Large']
)

# 객실 번호에서 정보 추출 (도메인 지식: 객실 위치가 생존과 관련 있을 수 있음)
df_domain['Cabin_Letter'] = df_domain['Cabin'].str[0]
df_domain['Cabin_Deck'] = df_domain['Cabin_Letter'].map({
    'A': 'ABC',
    'B': 'ABC',
    'C': 'ABC',
    'D': 'DE',
    'E': 'DE',
    'F': 'FG',
    'G': 'FG',
    'T': 'Other'
}).fillna('Unknown')

# 요금 대비 객실 등급 (도메인 지식: 같은 등급에서도 요금 차이가 있을 수 있음)
df_domain['Fare_Per_Class'] = df_domain['Fare'] / df_domain['Pclass']

print(df_domain[['SibSp', 'Parch', 'Family_Size', 'Family_Size_Category', 'Cabin', 'Cabin_Deck', 'Fare_Per_Class']].head())
    

특성 엔지니어링 팁

  1. 도메인 지식 활용: 해당 분야의 전문 지식을 최대한 활용해 특성을 만들어.
  2. EDA를 통한 인사이트: 데이터 탐색을 통해 얻은 인사이트를 특성으로 변환해.
  3. 특성 중요도 확인: 만든 특성의 중요도를 평가하고 불필요한 특성은 제거해.
  4. 반복적 실험: 다양한 특성을 시도하고 모델 성능을 비교해.
  5. 자동화 도구 활용: 특성 선택 알고리즘이나 자동 특성 엔지니어링 도구를 활용해.

특성 엔지니어링은 데이터 과학의 예술과도 같은 영역이야. 재능넷에서 데이터 분석 프로젝트를 진행할 때, 이런 창의적인 특성 엔지니어링 능력을 갖춘 전문가와 협업하면 훨씬 더 좋은 결과를 얻을 수 있을 거야. 좋은 특성은 간단한 모델로도 뛰어난 성능을 낼 수 있게 해주니까! 💪

8. 차원 축소 기법 📉

차원 축소(Dimensionality Reduction)는 데이터의 특성(변수) 수를 줄이면서도 중요한 정보는 최대한 보존하는 기법이야. 차원의 저주(Curse of Dimensionality)를 해결하고 모델의 성능과 효율성을 높이는 데 도움이 돼. 🚀

차원 축소가 필요한 이유

  1. 모델 복잡성 감소 및 과적합 방지
  2. 계산 효율성 향상
  3. 데이터 시각화 용이
  4. 노이즈 제거
  5. 다중공선성 문제 해결

1. 주성분 분석 (PCA: Principal Component Analysis)

가장 널리 사용되는 선형 차원 축소 기법으로, 데이터의 분산을 최대한 보존하는 방향으로 차원을 축소해. 🔍


from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

# 수치형 특성 선택
numeric_features = ['Age', 'SibSp', 'Parch', 'Fare']
X = df[numeric_features].fillna(0)

# 데이터 스케일링 (PCA 전에 필수)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# PCA 적용
pca = PCA(n_components=2)  # 2차원으로 축소
X_pca = pca.fit_transform(X_scaled)

# 결과 확인
pca_df = pd.DataFrame(
    X_pca,
    columns=['PC1', 'PC2']
)
pca_df['Survived'] = df['Survived'].values

print(pca_df.head())

# 설명된 분산 비율 확인
print(f'설명된 분산 비율: {pca.explained_variance_ratio_}')
print(f'누적 설명된 분산 비율: {np.sum(pca.explained_variance_ratio_)}')

# 주성분과 원본 특성 간의 관계 확인
components_df = pd.DataFrame(
    pca.components_,
    columns=numeric_features,
    index=['PC1', 'PC2']
)
print(components_df)

# PCA 결과 시각화
plt.figure(figsize=(10, 8))
sns.scatterplot(x='PC1', y='PC2', hue='Survived', data=pca_df)
plt.title('PCA: 2D Projection')
plt.show()
    

2. 커널 PCA (Kernel PCA)

비선형 차원 축소 기법으로, 커널 트릭을 사용해 데이터를 고차원 공간으로 매핑한 후 PCA를 적용해. 🌀


from sklearn.decomposition import KernelPCA

# 커널 PCA 적용
kpca = KernelPCA(
    n_components=2,
    kernel='rbf',  # 가우시안 RBF 커널
    gamma=15       # 커널 계수
)
X_kpca = kpca.fit_transform(X_scaled)

# 결과 확인
kpca_df = pd.DataFrame(
    X_kpca,
    columns=['KPCA1', 'KPCA2']
)
kpca_df['Survived'] = df['Survived'].values

print(kpca_df.head())

# 커널 PCA 결과 시각화
plt.figure(figsize=(10, 8))
sns.scatterplot(x='KPCA1', y='KPCA2', hue='Survived', data=kpca_df)
plt.title('Kernel PCA: 2D Projection with RBF Kernel')
plt.show()
    

3. t-SNE (t-Distributed Stochastic Neighbor Embedding)

비선형 차원 축소 기법으로, 고차원 데이터의 유사성을 저차원에서도 보존하는 방식이야. 시각화에 특히 유용해. 🎨


from sklearn.manifold import TSNE

# t-SNE 적용
tsne = TSNE(
    n_components=2,
    perplexity=30,    # 이웃 수 관련 파라미터
    learning_rate=200, # 학습률
    random_state=42
)
X_tsne = tsne.fit_transform(X_scaled)

# 결과 확인
tsne_df = pd.DataFrame(
    X_tsne,
    columns=['TSNE1', 'TSNE2']
)
tsne_df['Survived'] = df['Survived'].values

print(tsne_df.head())

# t-SNE 결과 시각화
plt.figure(figsize=(10, 8))
sns.scatterplot(x='TSNE1', y='TSNE2', hue='Survived', data=tsne_df)
plt.title('t-SNE: 2D Projection')
plt.show()
    

4. UMAP (Uniform Manifold Approximation and Projection)

최신 비선형 차원 축소 기법으로, t-SNE보다 계산 효율이 좋고 전역 구조도 잘 보존해. 🌐


# UMAP 설치: pip install umap-learn
import umap

# UMAP 적용
reducer = umap.UMAP(
    n_components=2,
    n_neighbors=15,   # 이웃 수
    min_dist=0.1,     # 최소 거리
    random_state=42
)
X_umap = reducer.fit_transform(X_scaled)

# 결과 확인
umap_df = pd.DataFrame(
    X_umap,
    columns=['UMAP1', 'UMAP2']
)
umap_df['Survived'] = df['Survived'].values

print(umap_df.head())

# UMAP 결과 시각화
plt.figure(figsize=(10, 8))
sns.scatterplot(x='UMAP1', y='UMAP2', hue='Survived', data=umap_df)
plt.title('UMAP: 2D Projection')
plt.show()
    

5. 특성 선택 (Feature Selection)

중요한 특성만 선택하여 차원을 축소하는 방법이야. 해석력이 높고 구현이 간단해. 📋

5.1 필터 방법 (Filter Methods)


from sklearn.feature_selection import SelectKBest, f_classif

# 분산 기반 특성 선택
from sklearn.feature_selection import VarianceThreshold

# 낮은 분산을 가진 특성 제거
selector = VarianceThreshold(threshold=0.1)
X_var_selected = selector.fit_transform(X_scaled)
print(f'분산 기반 선택 후 특성 수: {X_var_selected.shape[1]}')

# 통계적 검정 기반 특성 선택
X = df[numeric_features].fillna(0)
y = df['Survived']

# ANOVA F-값 기반 특성 선택
selector = SelectKBest(f_classif, k=2)
X_kbest = selector.fit_transform(X, y)

# 선택된 특성 확인
selected_features = [numeric_features[i] for i in range(len(numeric_features)) 
                    if selector.get_support()[i]]
print(f'선택된 특성: {selected_features}')

# 특성 점수 확인
feature_scores = pd.DataFrame({
    'Feature': numeric_features,
    'Score': selector.scores_
})
print(feature_scores.sort_values(by='Score', ascending=False))
    

5.2 래퍼 방법 (Wrapper Methods)


from sklearn.feature_selection import RFE
from sklearn.ensemble import RandomForestClassifier

# 재귀적 특성 제거 (RFE)
model = RandomForestClassifier(random_state=42)
rfe = RFE(estimator=model, n_features_to_select=2)
X_rfe = rfe.fit_transform(X, y)

# 선택된 특성 확인
selected_features_rfe = [numeric_features[i] for i in range(len(numeric_features)) 
                        if rfe.support_[i]]
print(f'RFE로 선택된 특성: {selected_features_rfe}')

# 특성 순위 확인
feature_ranks = pd.DataFrame({
    'Feature': numeric_features,
    'Rank': rfe.ranking_
})
print(feature_ranks.sort_values(by='Rank'))
    

5.3 임베디드 방법 (Embedded Methods)


from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import Lasso

# L1 정규화 기반 특성 선택
lasso = Lasso(alpha=0.1)
selector = SelectFromModel(lasso)
X_lasso_selected = selector.fit_transform(X_scaled, y)

# 선택된 특성 확인
selected_features_lasso = [numeric_features[i] for i in range(len(numeric_features)) 
                          if selector.get_support()[i]]
print(f'Lasso로 선택된 특성: {selected_features_lasso}')

# 트리 기반 특성 중요도
from sklearn.ensemble import RandomForestClassifier

forest = RandomForestClassifier(random_state=42)
forest.fit(X, y)

# 특성 중요도 확인
feature_importances = pd.DataFrame({
    'Feature': numeric_features,
    'Importance': forest.feature_importances_
})
print(feature_importances.sort_values(by='Importance', ascending=False))

# 중요도 기반 특성 선택
selector = SelectFromModel(forest, threshold='median')
X_rf_selected = selector.fit_transform(X, y)

selected_features_rf = [numeric_features[i] for i in range(len(numeric_features)) 
                       if selector.get_support()[i]]
print(f'Random Forest로 선택된 특성: {selected_features_rf}')
    

차원 축소 기법 선택 가이드

  1. PCA: 선형 관계가 중요할 때, 계산 효율성이 필요할 때, 노이즈 제거가 목적일 때
  2. 커널 PCA: 비선형 관계가 있을 때, 데이터가 복잡한 구조를 가질 때
  3. t-SNE/UMAP: 시각화가 주 목적일 때, 국소적 구조가 중요할 때
  4. 특성 선택: 해석력이 중요할 때, 특정 특성의 영향을 이해하고 싶을 때

차원 축소는 고차원 데이터를 다룰 때 필수적인 전처리 단계야. 재능넷에서 데이터 시각화나 분석 서비스를 찾는다면, 이런 차원 축소 기법에 능숙한 전문가와 협업하는 것이 좋을 거야. 데이터의 특성과 목적에 맞는 차원 축소 기법을 선택하면 더 효율적이고 정확한 분석이 가능해질 거야! 📊

9. 데이터 불균형 처리 ⚖️

데이터 불균형(Class Imbalance)은 분류 문제에서 한 클래스의 샘플 수가 다른 클래스보다 현저히 많거나 적은 상황을 말해. 이런 불균형은 모델이 다수 클래스에 편향되게 만들어 소수 클래스 예측 성능이 떨어지는 문제를 일으켜. 🔄

데이터 불균형 확인하기


# 타겟 변수의 클래스 분포 확인
class_counts = df['Survived'].value_counts()
print(class_counts)

# 클래스 비율 확인
class_ratio = class_counts / len(df)
print(class_ratio)

# 시각화
plt.figure(figsize=(8, 6))
sns.countplot(x='Survived', data=df)
plt.title('Class Distribution')
plt.show()
    

1. 리샘플링 기법 (Resampling Techniques)

데이터셋의 클래스 분포를 조정하는 방법이야. 🔄

1.1 오버샘플링 (Oversampling)

소수 클래스의 샘플을 증가시키는 방법이야. 👆


from sklearn.model_selection import train_test_split
from imblearn.over_sampling import RandomOverSampler, SMOTE, ADASYN

# 데이터 준비
X = df[numeric_features].fillna(0)
y = df['Survived']

# 학습/테스트 세트 분할
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 원본 학습 데이터의 클래스 분포
print(f'원본 학습 데이터 클래스 분포: {pd.Series(y_train).value_counts()}')

# 1) 랜덤 오버샘플링
ros = RandomOverSampler(random_state=42)
X_ros, y_ros = ros.fit_resample(X_train, y_train)
print(f'랜덤 오버샘플링 후 클래스 분포: {pd.Series(y_ros).value_counts()}')

# 2) SMOTE (Synthetic Minority Over-sampling Technique)
smote = SMOTE(random_state=42)
X_smote, y_smote = smote.fit_resample(X_train, y_train)
print(f'SMOTE 후 클래스 분포: {pd.Series(y_smote).value_counts()}')

# 3) ADASYN (Adaptive Synthetic Sampling)
adasyn = ADASYN(random_state=42)
X_adasyn, y_adasyn = adasyn.fit_resample(X_train, y_train)
print(f'ADASYN 후 클래스 분포: {pd.Series(y_adasyn).value_counts()}')
    

1.2 언더샘플링 (Undersampling)

다수 클래스의 샘플을 감소시키는 방법이야. 👇


from imblearn.under_sampling import RandomUnderSampler, NearMiss, TomekLinks

# 1) 랜덤 언더샘플링
rus = RandomUnderSampler(random_state=42)
X_rus, y_rus = rus.fit_resample(X_train, y_train)
print(f'랜덤 언더샘플링 후 클래스 분포: {pd.Series(y_rus).value_counts()}')

# 2) NearMiss
nm = NearMiss(version=3)  # 버전 1, 2, 3 중 선택 가능
X_nm, y_nm = nm.fit_resample(X_train, y_train)
print(f'NearMiss 후 클래스 분포: {pd.Series(y_nm).value_counts()}')

# 3) Tomek Links
tl = TomekLinks()
X_tl, y_tl = tl.fit_resample(X_train, y_train)
print(f'Tomek Links 후 클래스 분포: {pd.Series(y_tl).value_counts()}')
    

1.3 혼합 샘플링 (Combination Sampling)

오버샘플링과 언더샘플링을 함께 사용하는 방법이야. 🔄


from imblearn.combine import SMOTETomek, SMOTEENN

# 1) SMOTE + Tomek Links
smt = SMOTETomek(random_state=42)
X_smt, y_smt = smt.fit_resample(X_train, y_train)
print(f'SMOTE + Tomek Links 후 클래스 분포: {pd.Series(y_smt).value_counts()}')

# 2) SMOTE + ENN (Edited Nearest Neighbors)
smote_enn = SMOTEENN(random_state=42)
X_smote_enn, y_smote_enn = smote_enn.fit_resample(X_train, y_train)
print(f'SMOTE + ENN 후 클래스 분포: {pd.Series(y_smote_enn).value_counts()}')
    

2. 알고리즘 수준 방법 (Algorithm-level Methods)

모델 자체를 조정하여 불균형 데이터에 대응하는 방법이야. 🧠

2.1 비용 민감 학습 (Cost-sensitive Learning)


from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

# 클래스 가중치 설정
class_weights = {0: 1, 1: 2}  # 소수 클래스에 더 높은 가중치 부여

# 가중치를 적용한 모델 학습
weighted_model = RandomForestClassifier(
    class_weight=class_weights,
    random_state=42
)
weighted_model.fit(X_train, y_train)

# 예측 및 평가
y_pred = weighted_model.predict(X_test)
print(classification_report(y_test, y_pred))

# 자동으로 클래스 가중치 계산
balanced_model = RandomForestClassifier(
    class_weight='balanced',
    random_state=42
)
balanced_model.fit(X_train, y_train)

# 예측 및 평가
y_pred_balanced = balanced_model.predict(X_test)
print(classification_report(y_test, y_pred_balanced))
    

2.2 앙상블 기법 (Ensemble Techniques)


from imblearn.ensemble import BalancedRandomForestClassifier, EasyEnsembleClassifier

# 1) Balanced Random Forest
brf = BalancedRandomForestClassifier(random_state=42)
brf.fit(X_train, y_train)
y_pred_brf = brf.predict(X_test)
print(classification_report(y_test, y_pred_brf))

# 2) Easy Ensemble (AdaBoost + Bagging with undersampling)
eec = EasyEnsembleClassifier(random_state=42)
eec.fit(X_train, y_train)
y_pred_eec = eec.predict(X_test)
print(classification_report(y_test, y_pred_eec))
    

3. 평가 지표 선택 (Evaluation Metrics)

불균형 데이터셋에서는 정확도(Accuracy)보다 다른 평가 지표가 더 적합할 수 있어. 📊


from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.metrics import f1_score, roc_auc_score, average_precision_score
from sklearn.metrics import confusion_matrix, precision_recall_curve

# 모델 학습 (SMOTE로 균형 잡힌 데이터 사용)
model = RandomForestClassifier(random_state=42)
model.fit(X_smote, y_smote)

# 예측
y_pred = model.predict(X_test)
y_prob = model.predict_proba(X_test)[:, 1]  # 양성 클래스 확률

# 다양한 평가 지표 계산
print(f'정확도 (Accuracy): {accuracy_score(y_test, y_pred):.4f}')
print(f'정밀도 (Precision): {precision_score(y_test, y_pred):.4f}')
print(f'재현율 (Recall): {recall_score(y_test, y_pred):.4f}')
print(f'F1 점수: {f1_score(y_test, y_pred):.4f}')
print(f'ROC AUC: {roc_auc_score(y_test, y_prob):.4f}')
print(f'PR AUC: {average_precision_score(y_test, y_prob):.4f}')

# 혼동 행렬 (Confusion Matrix)
cm = confusion_matrix(y_test, y_pred)
print(f'혼동 행렬:\n{cm}')

# 정밀도-재현율 곡선
precision, recall, thresholds = precision_recall_curve(y_test, y_prob)

plt.figure(figsize=(10, 6))
plt.plot(recall, precision, marker='.')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curve')
plt.grid(True)
plt.show()
    

4. 임계값 조정 (Threshold Adjustment)

분류 임계값을 조정하여 소수 클래스 예측 성능을 향상시키는 방법이야. 🎚️


# 최적 임계값 찾기
from sklearn.metrics import f1_score

# 다양한 임계값에 대한 F1 점수 계산
thresholds = np.arange(0.1, 1.0, 0.05)
f1_scores = []

for threshold in thresholds:
    y_pred_threshold = (y_prob >= threshold).astype(int)
    f1 = f1_score(y_test, y_pred_threshold)
    f1_scores.append(f1)

# 최적 임계값 찾기
best_threshold_idx = np.argmax(f1_scores)
best_threshold = thresholds[best_threshold_idx]
best_f1 = f1_scores[best_threshold_idx]

print(f'최적 임계값: {best_threshold:.2f}, F1 점수: {best_f1:.4f}')

# 최적 임계값 적용
y_pred_optimal = (y_prob >= best_threshold).astype(int)
print(classification_report(y_test, y_pred_optimal))

# 임계값에 따른 F1 점수 시각화
plt.figure(figsize=(10, 6))
plt.plot(thresholds, f1_scores, marker='o')
plt.axvline(x=best_threshold, color='r', linestyle='--')
plt.xlabel('Threshold')
plt.ylabel('F1 Score')
plt.title('F1 Score vs. Threshold')
plt.grid(True)
plt.show()
    

불균형 데이터 처리 전략 선택 가이드

  1. 데이터가 적을 때: 오버샘플링(SMOTE) 또는 비용 민감 학습
  2. 데이터가 많을 때: 언더샘플링 또는 혼합 샘플링
  3. 노이즈가 많을 때: 언더샘플링보다 오버샘플링이 유리
  4. 계산 효율성이 중요할 때: 알고리즘 수준 방법 또는 임계값 조정
  5. 극단적 불균형(1:100 이상): 혼합 샘플링 + 앙상블 기법

데이터 불균형 처리는 실제 문제에서 매우 중요한 전처리 단계야. 재능넷에서 머신러닝 모델 개발을 의뢰할 때, 이런 불균형 데이터 처리에 능숙한 전문가를 찾는 것이 좋을 거야. 적절한 불균형 처리 기법을 적용하면 소수 클래스에 대한 예측 성능을 크게 향상시킬 수 있어! 🚀

10. 효율적인 데이터 전처리 파이프라인 구축 🔄

지금까지 다양한 데이터 전처리 기법들을 살펴봤어. 이제 이 모든 단계를 효율적으로 연결하는 전처리 파이프라인을 구축하는 방법을 알아보자! 파이프라인을 사용하면 코드 중복을 줄이고, 실수를 방지하며, 재현 가능한 워크플로우를 만들 수 있어. 🛠️

1. Scikit-learn 파이프라인

Scikit-learn의 Pipeline 클래스를 사용하면 여러 전처리 단계와 모델을 하나의 객체로 연결할 수 있어. 🔗


from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score

# 데이터 준비
df_pipe = df.copy()
X = df_pipe.drop('Survived', axis=1)
y = df_pipe['Survived']

# 수치형/범주형 특성 구분
numeric_features = ['Age', 'SibSp', 'Parch', 'Fare']
categorical_features = ['Pclass', 'Sex', 'Embarked']

# 학습/테스트 세트 분할
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 수치형 특성 전처리 파이프라인
numeric_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),  # 결측치 처리
    ('scaler', StandardScaler())                    # 표준화
])

# 범주형 특성 전처리 파이프라인
categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')),  # 결측치 처리
    ('onehot', OneHotEncoder(handle_unknown='ignore'))     # 원-핫 인코딩
])

# 전처리 단계 통합
preprocessor = ColumnTransformer(
    transformers=[
        ('num', numeric_transformer, numeric_features),
        ('cat', categorical_transformer, categorical_features)
    ]
)

# 전체 파이프라인 (전처리 + 모델)
full_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier(random_state=42))
])

# 파이프라인 학습
full_pipeline.fit(X_train, y_train)

# 성능 평가
accuracy = full_pipeline.score(X_test, y_test)
print(f'테스트 세트 정확도: {accuracy:.4f}')

# 교차 검증
cv_scores = cross_val_score(full_pipeline, X, y, cv=5)
print(f'교차 검증 정확도: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}')
    

2. 커스텀 변환기 만들기

Scikit-learn의 BaseEstimator와 TransformerMixin을 상속받아 커스텀 변환기를 만들 수 있어. 이를 통해 복잡한 전처리 로직을 캡슐화할 수 있지. 🧩


from sklearn.base import BaseEstimator, TransformerMixin

# 특성 엔지니어링을 위한 커스텀 변환기
class FamilyFeaturesTransformer(BaseEstimator, TransformerMixin):
    def __init__(self):
        pass
    
    def fit(self, X, y=None):
        return self
    
    def transform(self, X):
        X_copy = X.copy()
        
        # 가족 크기 특성 생성
        X_copy['FamilySize'] = X_copy['SibSp'] + X_copy['Parch'] + 1
        
        # 혼자 여행하는지 여부
        X_copy['IsAlone'] = (X_copy['FamilySize'] == 1).astype(int)
        
        # 대가족 여부
        X_copy['IsLargeFamily'] = (X_copy['FamilySize'] >= 5).astype(int)
        
        return X_copy

# 이름에서 타이틀 추출하는 커스텀 변환기
class TitleExtractor(BaseEstimator, TransformerMixin):
    def __init__(self):
        self.title_mapping = {}
    
    def fit(self, X, y=None):
        # 이름에서 타이틀 추출
        titles = X['Name'].str.extract(r' ([A-Za-z]+)\.', expand=False)
        
        # 빈도가 낮은 타이틀 그룹화
        rare_titles = titles.value_counts()[titles.value_counts() < 10].index
        for title in rare_titles:
            if title in ['Mlle', 'Ms', 'Miss']:
                titles = titles.replace(title, 'Miss')
            elif title in ['Mme', 'Mrs']:
                titles = titles.replace(title, 'Mrs')
            else:
                titles = titles.replace(title, 'Rare')
        
        # 매핑 저장
        self.title_mapping = {title: i for i, title in enumerate(titles.unique())}
        return self
    
    def transform(self, X):
        X_copy = X.copy()
        
        # 타이틀 추출 및 매핑 적용
        titles = X_copy['Name'].str.extract(r' ([A-Za-z]+)\.', expand=False)
        
        # 학습 시 보지 못한 타이틀 처리
        titles = titles.map(lambda x: x if x in self.title_mapping else 'Rare')
        
        # 숫자로 인코딩
        X_copy['Title'] = titles.map(self.title_mapping).fillna(-1).astype(int)
        
        return X_copy

# 커스텀 변환기를 포함한 파이프라인 구성
custom_pipeline = Pipeline(steps=[
    ('family_features', FamilyFeaturesTransformer()),
    ('title_extractor', TitleExtractor()),
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier(random_state=42))
])

# 파이프라인 학습 및 평가
custom_pipeline.fit(X_train, y_train)
custom_accuracy = custom_pipeline.score(X_test, y_test)
print(f'커스텀 파이프라인 정확도: {custom_accuracy:.4f}')
    

3. 파이프라인 하이퍼파라미터 튜닝

파이프라인의 각 단계에 대한 하이퍼파라미터를 함께 튜닝할 수 있어. 이를 통해 전처리와 모델링을 동시에 최적화할 수 있지. 🎛️


from sklearn.model_selection import GridSearchCV

# 파이프라인 파라미터 그리드 정의
param_grid = {
    'preprocessor__num__imputer__strategy': ['mean', 'median'],
    'classifier__n_estimators': [100, 200],
    'classifier__max_depth': [None, 10, 20],
    'classifier__min_samples_split': [2, 5]
}

# 그리드 서치 수행
grid_search = GridSearchCV(
    full_pipeline,
    param_grid,
    cv=5,
    scoring='accuracy',
    n_jobs=-1
)

grid_search.fit(X_train, y_train)

# 최적 파라미터 및 성능 출력
print(f'최적 파라미터: {grid_search.best_params_}')
print(f'최적 교차 검증 정확도: {grid_search.best_score_:.4f}')
print(f'테스트 세트 정확도: {grid_search.score(X_test, y_test):.4f}')
    

4. 파이프라인 저장 및 로드

학습된 파이프라인을 저장하고 나중에 다시 로드하여 사용할 수 있어. 이를 통해 모델을 배포하거나 공유할 수 있지. 💾


import joblib

# 파이프라인 저장
joblib.dump(grid_search.best_estimator_, 'titanic_pipeline.pkl')

# 파이프라인 로드
loaded_pipeline = joblib.load('titanic_pipeline.pkl')

# 로드된 파이프라인으로 예측
loaded_accuracy = loaded_pipeline.score(X_test, y_test)
print(f'로드된 파이프라인 정확도: {loaded_accuracy:.4f}')
    

5. 효율적인 파이프라인 구축 팁

  1. 모듈화: 각 전처리 단계를 독립적인 변환기로 분리하여 재사용성을 높여.
  2. 데이터 누수 방지: 전처리 단계를 파이프라인 내부에 포함시켜 테스트 데이터 누수를 방지해.
  3. 메모리 효율성: 대용량 데이터셋의 경우 memory 파라미터를 사용하여 중간 결과를 디스크에 캐싱해.
  4. 병렬 처리: n_jobs 파라미터를 활용하여 병렬 처리로 속도를 향상시켜.
  5. 에러 처리: 예외 상황을 고려한 견고한 파이프라인을 설계해.

6. 고급 파이프라인 기법


from sklearn.pipeline import FeatureUnion

# 여러 특성 추출 방법을 병렬로 적용
feature_union = FeatureUnion(transformer_list=[
    ('standard', numeric_transformer),
    ('pca', Pipeline([
        ('imputer', SimpleImputer(strategy='median')),
        ('scaler', StandardScaler()),
        ('pca', PCA(n_components=2))
    ]))
])

# 메모리 캐싱을 사용한 파이프라인
from tempfile import mkdtemp
from shutil import rmtree
from sklearn.pipeline import Pipeline

# 임시 캐시 디렉토리
cachedir = mkdtemp()

# 캐싱을 사용한 파이프라인
cached_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier())
], memory=cachedir)

# 파이프라인 사용 후 캐시 정리
# rmtree(cachedir)
    

효율적인 데이터 전처리 파이프라인을 구축하면 작업 흐름이 간소화되고, 코드 재사용성이 높아지며, 실수를 줄일 수 있어. 재능넷에서 데이터 분석 프로젝트를 진행할 때, 이런 파이프라인 구축 능력을 갖춘 전문가와 협업하면 더 체계적이고 효율적인 결과물을 얻을 수 있을 거야. 파이프라인은 데이터 과학 워크플로우의 핵심 요소니까 꼭 마스터하자! 🚀

11. 실전 프로젝트: 전처리 종합 실습 🏆

지금까지 배운 모든 전처리 기법을 종합적으로 적용해보는 실전 프로젝트를 진행해볼게. 이 프로젝트에서는 주택 가격 예측 데이터셋을 사용할 거야. 실제 데이터 과학 프로젝트와 유사한 워크플로우를 따라가며 전처리의 모든 단계를 실습해보자! 🏠

1. 데이터 로드 및 탐색


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split

# 데이터 로드 (예: 보스턴 주택 가격 데이터셋)
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing()

# DataFrame 생성
housing_df = pd.DataFrame(
    housing.data,
    columns=housing.feature_names
)
housing_df['PRICE'] = housing.target

# 데이터 탐색
print(f'데이터 크기: {housing_df.shape}')
print(housing_df.info())
print(housing_df.describe())

# 결측치 확인
print(f'결측치 개수:\n{housing_df.isnull().sum()}')

# 타겟 변수 분포 확인
plt.figure(figsize=(10, 6))
sns.histplot(housing_df['PRICE'], kde=True)
plt.title('House Price Distribution')
plt.show()

# 상관관계 확인
plt.figure(figsize=(12, 10))
correlation_matrix = housing_df.corr()
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', linewidths=0.5)
plt.title('Correlation Matrix')
plt.show()

# 특성과 타겟 간의 관계 확인
fig, axes = plt.subplots(3, 3, figsize=(18, 12))
axes = axes.flatten()

for i, feature in enumerate(housing_df.columns[:-1]):
    sns.scatterplot(x=feature, y='PRICE', data=housing_df, ax=axes[i], alpha=0.6)
    axes[i].set_title(f'{feature} vs PRICE')

plt.tight_layout()
plt.show()
    

2. 데이터 전처리 파이프라인 구축


from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder, PowerTransformer
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score

# 데이터 분할
X = housing_df.drop('PRICE', axis=1)
y = housing_df['PRICE']

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 수치형 특성 전처리 파이프라인
numeric_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler()),
    ('power', PowerTransformer(method='yeo-johnson'))  # 정규성 향상
])

# 전처리 파이프라인 통합
preprocessor = ColumnTransformer(
    transformers=[
        ('num', numeric_transformer, X.columns)
    ]
)

# 특성 선택 및 모델링 파이프라인
full_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('feature_selection', SelectKBest(f_regression, k=6)),  # 상위 6개 특성 선택
    ('regressor', RandomForestRegressor(random_state=42))
])

# 파이프라인 학습
full_pipeline.fit(X_train, y_train)

# 예측 및 평가
y_pred = full_pipeline.predict(X_test)

mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)

print(f'RMSE: {rmse:.4f}')
print(f'R²: {r2:.4f}')
    

3. 특성 엔지니어링 추가


from sklearn.base import BaseEstimator, TransformerMixin

# 특성 엔지니어링을 위한 커스텀 변환기
class FeatureEngineer(BaseEstimator, TransformerMixin):
    def __init__(self):
        pass
    
    def fit(self, X, y=None):
        return self
    
    def transform(self, X):
        X_copy = X.copy()
        
        # 인구 밀도 (Population / HouseAge)
        X_copy['POP_DENSITY'] = X_copy['Population'] / X_copy['AveRooms']
        
        # 방 대비 침실 비율
        X_copy['BEDROOM_RATIO'] = X_copy['AveBedrms'] / X_copy['AveRooms']
        
        # 소득 대비 주택 가격 비율 (affordability)
        X_copy['INCOME_PER_ROOM'] = X_copy['MedInc'] / X_copy['AveRooms']
        
        # 위치 기반 특성 (위도/경도 조합)
        X_copy['LOCATION'] = X_copy['Latitude'] * X_copy['Longitude']
        
        # 해안 근접성 (위도와 경도의 제곱합)
        X_copy['COASTAL_PROXIMITY'] = X_copy['Latitude']**2 + X_copy['Longitude']**2
        
        return X_copy

# 개선된 파이프라인
improved_pipeline = Pipeline(steps=[
    ('feature_engineer', FeatureEngineer()),
    ('preprocessor', preprocessor),
    ('feature_selection', SelectKBest(f_regression, k=10)),  # 상위 10개 특성 선택
    ('regressor', RandomForestRegressor(
        n_estimators=200,
        max_depth=20,
        min_samples_split=5,
        random_state=42
    ))
])

# 개선된 파이프라인 학습
improved_pipeline.fit(X_train, y_train)

# 예측 및 평가
y_pred_improved = improved_pipeline.predict(X_test)

mse_improved = mean_squared_error(y_test, y_pred_improved)
rmse_improved = np.sqrt(mse_improved)
r2_improved = r2_score(y_test, y_pred_improved)

print(f'개선된 모델 RMSE: {rmse_improved:.4f}')
print(f'개선된 모델 R²: {r2_improved:.4f}')
print(f'성능 향상: RMSE {(rmse - rmse_improved) / rmse * 100:.2f}%, R² {(r2_improved - r2) / r2 * 100:.2f}%')
    

4. 하이퍼파라미터 튜닝


from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, uniform

# 하이퍼파라미터 탐색 공간
param_distributions = {
    'feature_selection__k': randint(5, 15),
    'regressor__n_estimators': randint(100, 500),
    'regressor__max_depth': randint(10, 30),
    'regressor__min_samples_split': randint(2, 10),
    'regressor__min_samples_leaf': randint(1, 5)
}

# 랜덤 서치 수행
random_search = RandomizedSearchCV(
    improved_pipeline,
    param_distributions=param_distributions,
    n_iter=20,
    cv=5,
    scoring='neg_root_mean_squared_error',
    n_jobs=-1,
    random_state=42
)

random_search.fit(X_train, y_train)

# 최적 파라미터 및 성능 출력
print(f'최적 파라미터: {random_search.best_params_}')
print(f'최적 RMSE: {-random_search.best_score_:.4f}')

# 최적 모델로 예측
best_model = random_search.best_estimator_
y_pred_best = best_model.predict(X_test)

rmse_best = np.sqrt(mean_squared_error(y_test, y_pred_best))
r2_best = r2_score(y_test, y_pred_best)

print(f'최적 모델 테스트 RMSE: {rmse_best:.4f}')
print(f'최적 모델 테스트 R²: {r2_best:.4f}')
    

5. 결과 시각화 및 해석


# 예측 vs 실제 값 비교
plt.figure(figsize=(10, 6))
plt.scatter(y_test, y_pred_best, alpha=0.6)
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
plt.xlabel('Actual Prices')
plt.ylabel('Predicted Prices')
plt.title('Actual vs Predicted House Prices')
plt.show()

# 잔차 분석
residuals = y_test - y_pred_best

plt.figure(figsize=(10, 6))
sns.histplot(residuals, kde=True)
plt.axvline(0, color='r', linestyle='--')
plt.title('Residuals Distribution')
plt.xlabel('Residual')
plt.show()

plt.figure(figsize=(10, 6))
plt.scatter(y_pred_best, residuals, alpha=0.6)
plt.axhline(0, color='r', linestyle='--')
plt.title('Residuals vs Predicted Values')
plt.xlabel('Predicted Values')
plt.ylabel('Residuals')
plt.show()

# 특성 중요도 확인
if hasattr(best_model[-1], 'feature_importances_'):
    # 특성 선택 후 남은 특성 이름 가져오기
    feature_selector = best_model.named_steps['feature_selection']
    selected_indices = feature_selector.get_support(indices=True)
    
    # 특성 엔지니어링 단계에서 생성된 특성 이름 가져오기
    feature_engineer = best_model.named_steps['feature_engineer']
    engineered_features = feature_engineer.transform(X_train.iloc[:1]).columns
    
    selected_features = [engineered_features[i] for i in selected_indices]
    
    # 특성 중요도 시각화
    importances = best_model[-1].feature_importances_
    indices = np.argsort(importances)[::-1]
    
    plt.figure(figsize=(12, 8))
    plt.title('Feature Importances')
    plt.barh(range(len(indices)), importances[indices], align='center')
    plt.yticks(range(len(indices)), [selected_features[i] for i in indices])
    plt.xlabel('Relative Importance')
    plt.tight_layout()
    plt.show()
    

6. 모델 저장 및 배포


import joblib

# 최적 모델 저장
joblib.dump(best_model, 'housing_price_model.pkl')

# 모델 로드 및 테스트
loaded_model = joblib.load('housing_price_model.pkl')
test_predictions = loaded_model.predict(X_test)

# 새로운 데이터에 대한 예측 함수
def predict_house_price(features_dict):
    """
    새로운 주택 데이터에 대한 가격 예측
    
    Parameters:
    features_dict (dict): 주택 특성을 담은 딕셔너리
    
    Returns:
    float: 예측된 주택 가격
    """
    # 딕셔너리를 DataFrame으로 변환
    features_df = pd.DataFrame([features_dict])
    
    # 누락된 특성 처리
    for col in X.columns:
        if col not in features_df.columns:
            features_df[col] = 0
    
    # 예측
    predicted_price = loaded_model.predict(features_df)[0]
    return predicted_price

# 예측 함수 테스트
sample_house = {
    'MedInc': 5.0,
    'HouseAge': 30.0,
    'AveRooms': 6.0,
    'AveBedrms': 1.0,
    'Population': 1000,
    'AveOccup': 3.0,
    'Latitude': 37.85,
    'Longitude': -122.25
}

predicted_price = predict_house_price(sample_house)
print(f'예측된 주택 가격: ${predicted_price:.2f}')
    

7. 프로젝트 결론 및 개선점

이 실전 프로젝트를 통해 데이터 전처리의 전체 워크플로우를 경험해봤어. 주요 단계를 요약하면 다음과 같아:

  1. 데이터 탐색 및 이해: 데이터의 특성, 분포, 관계 파악
  2. 전처리 파이프라인 구축: 결측치 처리, 스케일링, 변환 등
  3. 특성 엔지니어링: 도메인 지식을 활용한 새로운 특성 생성
  4. 특성 선택: 중요한 특성만 선별하여 모델 복잡성 감소
  5. 모델 학습 및 튜닝: 최적의 하이퍼파라미터 탐색
  6. 결과 평가 및 해석: 모델 성능 평가 및 특성 중요도 분석
  7. 모델 저장 및 배포: 학습된 모델을 저장하고 새로운 데이터에 적용

이 프로젝트에서 더 개선할 수 있는 부분은 다음과 같아:

  • 더 다양한 특성 엔지니어링 시도
  • 다른 모델(XGBoost, LightGBM 등) 비교 실험
  • 이상치 처리 방법 개선
  • 교차 검증 전략 최적화
  • 모델 해석력 향상을 위한 SHAP 값 분석

데이터 전처리는 끊임없는 실험과 개선의 과정이야. 재능넷에서 데이터 분석 프로젝트를 진행할 때도 이런 체계적인 접근 방식이 큰 도움이 될 거야. 다양한 전처리 기법을 시도하고, 결과를 비교하며, 최적의 솔루션을 찾아가는 과정이 데이터 과학의 핵심이니까! 🚀

마무리: 데이터 전처리의 예술과 과학 🎭

지금까지 데이터 전처리의 다양한 기법과 실전 팁들을 알아봤어. 데이터 전처리는 단순한 기술적 과정이 아니라 예술과 과학이 결합된 영역이라고 할 수 있어. 데이터의 특성을 이해하고, 적절한 기법을 선택하며, 창의적인 특성을 만들어내는 과정에는 기술적 지식뿐만 아니라 직관과 경험도 중요하지. 🧠

데이터 전처리의 핵심 포인트를 다시 한번 정리해볼게:

  1. 데이터 이해가 최우선: 전처리 전에 데이터의 특성과 구조를 철저히 파악해야 해.
  2. 목적 지향적 접근: 분석 목적에 맞는 전처리 기법을 선택해야 해.
  3. 도메인 지식 활용: 해당 분야의 전문 지식을 특성 엔지니어링에 적극 활용해야 해.
  4. 반복적 실험: 다양한 전처리 방법을 시도하고 결과를 비교해야 해.
  5. 파이프라인 구축: 재현 가능하고 효율적인 전처리 워크플로우를 만들어야 해.
  6. 데이터 누수 방지: 테스트 데이터의 정보가 학습 과정에 유입되지 않도록 주의해야 해.
  7. 균형 잡힌 접근: 과도한 전처리는 오히려 성능을 저하시킬 수 있어.

데이터 전처리는 데이터 과학 프로젝트의 80%를 차지한다는 말이 있을 정도로 중요한 과정이야. 재능넷에서 데이터 분석이나 머신러닝 관련 서비스를 찾는다면, 이런 전처리 기법에 능숙한 전문가를 만나는 것이 프로젝트 성공의 열쇠가 될 거야. 🔑

이 글에서 다룬 내용들을 실제 프로젝트에 적용해보면서 자신만의 전처리 노하우를 쌓아가길 바라. 데이터 전처리는 실전 경험을 통해 계속 발전시켜 나가는 영역이니까. 끊임없이 학습하고, 실험하고, 개선해 나가는 과정에서 진정한 데이터 과학자로 성장할 수 있을 거야! 💪

마지막으로, 데이터 전처리는 목적이 아니라 수단이라는 점을 기억하자. 궁극적인 목표는 데이터에서 가치 있는 인사이트를 도출하고, 더 나은 의사결정을 지원하는 것이야. 전처리 과정에서 이 목표를 항상 염두에 두고 접근한다면, 더 효과적이고 의미 있는 결과를 얻을 수 있을 거야. 🎯

데이터 전처리의 세계에 오신 것을 환영해! 이제 당신은 데이터를 정제하고, 변환하고, 강화하는 다양한 도구와 기법을 알게 되었어. 이 지식을 바탕으로 더 나은 데이터 과학자로 성장하길 바라! 🚀

댓글 작성

이 글에 대한 여러분의 생각을 들려주세요

댓글 0
댓글을 불러오는 중입니다.

아직 댓글이 없습니다.