Data Preprocessing
Data Preprocessing
The process of cleaning raw data into a form suitable for analysis. Includes handling missing values, normalization, and encoding.
Data Preprocessing
The process of cleaning raw data into a form suitable for analysis. Includes handling missing values, normalization, and encoding.
Data preprocessing is the process of cleaning and transforming raw data into a form suitable for machine learning models or analysis. It is so central that 60-80% of the total time in a real data science project is spent on it. As the maxim "Garbage In, Garbage Out" says, the quality of preprocessing has a direct impact on model performance.
The main preprocessing tasks include handling missing values, detecting and removing outliers, data normalization/standardization, encoding categorical variables, and feature selection and transformation. Missing values are handled with various strategies such as deletion, mean/median imputation, KNN imputation, and multiple imputation (MICE), while outliers are detected with IQR, Z-score, Isolation Forest, and others. For scaling, you must choose an appropriate method depending on the algorithm.
Scaling methods for numerical data include Min-Max normalization (0-1 range), StandardScaler (Z-score standardization), and RobustScaler (median-based and robust to outliers). Categorical data is converted to numbers with One-Hot Encoding (nominal), Label Encoding (ordinal), Target Encoding (high-cardinality categories), and so on. Text and date data also need appropriate transformations.
Using scikit-learn's Pipeline and ColumnTransformer, you can structure the preprocessing process in a reproducible, modular form. Large datasets are processed in a distributed way with Spark or Dask, and registering preprocessing logic in a Feature Store keeps training and inference consistent. Preprocessing is not a mere chore but a core skill that reflects domain knowledge.
# 종합적인 데이터 전처리 파이프라인 예시
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import (
StandardScaler, MinMaxScaler, OneHotEncoder,
OrdinalEncoder, PowerTransformer
)
from sklearn.impute import SimpleImputer, KNNImputer
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
# 1. 데이터 로드 및 탐색
df = pd.read_csv('customer_data.csv')
print(f"Shape: {df.shape}")
print(f"결측값:\n{df.isnull().sum()}")
print(f"데이터 타입:\n{df.dtypes}")
# 2. 컬럼 타입별 분류
numeric_features = ['age', 'income', 'credit_score', 'account_balance']
categorical_features = ['gender', 'region', 'membership_type']
ordinal_features = ['education'] # 순서 있는 범주
# 3. 이상치 탐지 및 처리 (IQR 방식)
def remove_outliers_iqr(df, column, threshold=1.5):
"""IQR 기반 이상치 제거"""
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower = Q1 - threshold * IQR
upper = Q3 + threshold * IQR
return df[(df[column] >= lower) & (df[column] <= upper)]
# 수치형 컬럼에 이상치 처리 적용
for col in numeric_features:
df = remove_outliers_iqr(df, col)
# 4. 전처리 파이프라인 구성
# 수치형: KNN 대체 -> Z-score 정규화 -> 정규분포화
numeric_transformer = Pipeline(steps=[
('imputer', KNNImputer(n_neighbors=5)),
('scaler', StandardScaler()),
('power', PowerTransformer(method='yeo-johnson'))
])
# 범주형: 최빈값 대체 -> One-Hot 인코딩
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
])
# 순서형: 최빈값 대체 -> Ordinal 인코딩
ordinal_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('encoder', OrdinalEncoder(categories=[
['고졸', '전문대졸', '대졸', '석사', '박사']
]))
])
# 5. ColumnTransformer로 통합
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features),
('ord', ordinal_transformer, ordinal_features)
],
remainder='drop'
)
# 6. 전체 ML 파이프라인 (전처리 + 특성 선택 + 모델)
full_pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('feature_selection', SelectKBest(mutual_info_classif, k=15)),
('classifier', RandomForestClassifier(n_estimators=100, random_state=42))
])
# 7. 학습 및 평가
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# 전체 파이프라인 학습
full_pipeline.fit(X_train, y_train)
predictions = full_pipeline.predict(X_test)
# 8. 전처리된 데이터 확인
X_preprocessed = preprocessor.fit_transform(X_train)
feature_names = preprocessor.get_feature_names_out()
print(f"전처리 후 특성 수: {len(feature_names)}")
print(f"특성 이름: {feature_names[:10]}...")
# 9. 파이프라인 저장 (재사용)
import joblib
joblib.dump(full_pipeline, 'preprocessing_pipeline.pkl')
# 추론 시 동일한 파이프라인 사용
loaded_pipeline = joblib.load('preprocessing_pipeline.pkl')
new_predictions = loaded_pipeline.predict(new_data)
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free