๐Ÿ“ŠData Engineering

Feature Engineering

Feature Engineering

Creating ML-useful features from raw data. Greatly affects model performance.

๐Ÿ“– Detailed Explanation

Feature Engineering is the process of transforming raw data into features that are well suited for machine learning models to learn from. As the maxim "data matters more than the algorithm" says, good features greatly improve model performance.

Key techniques include numerical transformations (log transformation, scaling, normalization), categorical encoding (One-Hot, Label, Target Encoding), time-series features (day of week, time of day, lag features, rolling statistics), text features (TF-IDF, word count, sentiment score), and interaction features (products, ratios, differences).

Domain knowledge is key. For example, in e-commerce, features such as "days since last purchase," "average purchase interval," and "purchase-to-cart ratio" are effective. In finance, features such as "debt-to-income ratio" and "number of late payments in the last 3 months" are important.

Feature Selection is also important. Irrelevant features become noise and degrade model performance. Meaningful features are selected through correlation analysis, Feature Importance, Recursive Feature Elimination, and the like.

๐Ÿ’ป Code Example

# Pandas ๊ธฐ๋ฐ˜ ํ”ผ์ฒ˜ ์—”์ง€๋‹ˆ์–ด๋ง ์˜ˆ์ œ

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, LabelEncoder

# ์ƒ˜ํ”Œ ๋ฐ์ดํ„ฐ
df = pd.DataFrame({
    'user_id': [1, 1, 1, 2, 2, 3],
    'purchase_date': pd.to_datetime(['2024-01-01', '2024-01-15', '2024-02-01',
                                     '2024-01-10', '2024-01-20', '2024-02-15']),
    'amount': [100, 250, 180, 500, 120, 80],
    'category': ['electronics', 'clothing', 'electronics', 'food', 'food', 'clothing'],
    'is_weekend': [False, False, True, True, False, True]
})

print("์›๋ณธ ๋ฐ์ดํ„ฐ:")
print(df)

# 1. ์‹œ๊ณ„์—ด ํ”ผ์ฒ˜
df['day_of_week'] = df['purchase_date'].dt.dayofweek
df['month'] = df['purchase_date'].dt.month
df['is_month_start'] = df['purchase_date'].dt.is_month_start.astype(int)

# 2. ์ˆ˜์น˜ํ˜• ๋ณ€ํ™˜
df['amount_log'] = np.log1p(df['amount'])  # ๋กœ๊ทธ ๋ณ€ํ™˜ (์™œ๋„ ๊ฐ์†Œ)
scaler = StandardScaler()
df['amount_scaled'] = scaler.fit_transform(df[['amount']])

# 3. ๋ฒ”์ฃผํ˜• ์ธ์ฝ”๋”ฉ
# One-Hot Encoding
category_dummies = pd.get_dummies(df['category'], prefix='cat')
df = pd.concat([df, category_dummies], axis=1)

# Label Encoding
le = LabelEncoder()
df['category_encoded'] = le.fit_transform(df['category'])

# 4. ์‚ฌ์šฉ์ž๋ณ„ ์ง‘๊ณ„ ํ”ผ์ฒ˜ (RFM ๋ถ„์„ ์Šคํƒ€์ผ)
user_features = df.groupby('user_id').agg({
    'purchase_date': ['min', 'max', 'count'],
    'amount': ['sum', 'mean', 'std']
}).reset_index()
user_features.columns = ['user_id', 'first_purchase', 'last_purchase',
                         'purchase_count', 'total_amount', 'avg_amount', 'std_amount']

# Recency (๋งˆ์ง€๋ง‰ ๊ตฌ๋งค ํ›„ ๊ฒฝ๊ณผ ์ผ์ˆ˜)
reference_date = pd.Timestamp('2024-03-01')
user_features['recency_days'] = (reference_date - user_features['last_purchase']).dt.days

# Tenure (์ฒซ ๊ตฌ๋งค๋ถ€ํ„ฐ ๊ฒฝ๊ณผ ์ผ์ˆ˜)
user_features['tenure_days'] = (reference_date - user_features['first_purchase']).dt.days

# ๊ตฌ๋งค ๋นˆ๋„ (์ผ ํ‰๊ท )
user_features['purchase_frequency'] = user_features['purchase_count'] / user_features['tenure_days']

# ๊ฒฐ์ธก๊ฐ’ ์ฒ˜๋ฆฌ
user_features['std_amount'] = user_features['std_amount'].fillna(0)

print("\n์‚ฌ์šฉ์ž๋ณ„ ํ”ผ์ฒ˜:")
print(user_features)

# 5. Lag ํ”ผ์ฒ˜ (์ด์ „ ๊ฐ’ ์ฐธ์กฐ)
df_sorted = df.sort_values(['user_id', 'purchase_date'])
df_sorted['prev_amount'] = df_sorted.groupby('user_id')['amount'].shift(1)
df_sorted['amount_diff'] = df_sorted['amount'] - df_sorted['prev_amount']

# 6. Rolling ํ”ผ์ฒ˜ (์ด๋™ ํ†ต๊ณ„)
df_sorted['rolling_avg_3'] = df_sorted.groupby('user_id')['amount'].transform(
    lambda x: x.rolling(window=3, min_periods=1).mean()
)

print("\nLag/Rolling ํ”ผ์ฒ˜ ์ถ”๊ฐ€:")
print(df_sorted[['user_id', 'purchase_date', 'amount', 'prev_amount',
                  'amount_diff', 'rolling_avg_3']])

๐Ÿ—ฃ๏ธ How It's Said in Practice

ML Engineer: "Model performance isn't improving, so I'll do more feature engineering. I'm planning to add RFM features and purchase interval variability."

Analyst: "I think it would be good to ask a domain expert which features are important."

Senior: "Sounds good, and let's also analyze feature importance and remove unnecessary features at the same time."

Interviewer: "What do you consider the most important aspect of feature engineering?"

Candidate: "Preventing Data Leakage. If future information gets into the features, performance looks good during training but the model fails in the actual service. You need to be especially careful with time-series data, and you must clearly define the point at which training and validation are split."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "You encoded with the entire dataset in this Target Encoding, so information leaks into the validation set."

Author: "Ah, so I should encode using only the training data and then transform. I'll fix it so it's handled inside the cross-validation fold."

โš ๏ธ Cautions

๐Ÿ“š Learn More