1
---
2
name: Feature Engineering
3
description: Create and transform features using encoding, scaling, polynomial features, and domain-specific transformations for improved model performance and interpretability
4
---
5
6
# Feature Engineering
7
8
## Overview
9
10
Feature engineering creates and transforms features to improve model performance, interpretability, and generalization through domain knowledge and mathematical transformations.
11
12
## When to Use
13
14
- When you need to improve model performance beyond using raw features
15
- When dealing with categorical variables that need encoding for ML algorithms
16
- When features have different scales and require normalization
17
- When creating domain-specific features based on business knowledge
18
- When handling skewed distributions or non-linear relationships
19
- When preparing data for different types of ML algorithms with specific requirements
20
21
## Engineering Techniques
22
23
- **Encoding**: Converting categorical to numerical
24
- **Scaling**: Normalizing feature ranges
25
- **Polynomial Features**: Higher-order terms
26
- **Interactions**: Combining features
27
- **Domain-specific**: Business-relevant transformations
28
- **Temporal**: Time-based features
29
30
## Key Principles
31
32
- Create features based on domain knowledge
33
- Remove redundant features
34
- Scale features appropriately
35
- Handle categorical variables
36
- Create meaningful interactions
37
38
## Implementation with Python
39
40
```python
41
import pandas as pd
42
import numpy as np
43
import matplotlib.pyplot as plt
44
from sklearn.preprocessing import (
45
StandardScaler, MinMaxScaler, RobustScaler, PolynomialFeatures,
46
OneHotEncoder, OrdinalEncoder, LabelEncoder
47
)
48
from sklearn.pipeline import Pipeline
49
from sklearn.compose import ColumnTransformer
50
import seaborn as sns
51
52
# Create sample dataset
53
np.random.seed(42)
54
df = pd.DataFrame({
55
'age': np.random.uniform(18, 80, 1000),
56
'income': np.random.uniform(20000, 150000, 1000),
57
'experience_years': np.random.uniform(0, 50, 1000),
58
'category': np.random.choice(['A', 'B', 'C'], 1000),
59
'city': np.random.choice(['NYC', 'LA', 'Chicago'], 1000),
60
'purchased': np.random.choice([0, 1], 1000),
61
})
62
63
print("Original Data:")
64
print(df.head())
65
print(df.info())
66
67
# 1. Categorical Encoding
68
# One-Hot Encoding
69
print("\n1. One-Hot Encoding:")
70
df_ohe = pd.get_dummies(df, columns=['category', 'city'], drop_first=True)
71
print(df_ohe.head())
72
73
# Ordinal Encoding
74
print("\n2. Ordinal Encoding:")
75
ordinal_encoder = OrdinalEncoder()
76
df['category_ordinal'] = ordinal_encoder.fit_transform(df[['category']])
77
print(df[['category', 'category_ordinal']].head())
78
79
# Label Encoding
80
print("\n3. Label Encoding:")
81
le = LabelEncoder()
82
df['city_encoded'] = le.fit_transform(df['city'])
83
print(df[['city', 'city_encoded']].head())
84
85
# 2. Feature Scaling
86
print("\n4. Feature Scaling:")
87
X = df[['age', 'income', 'experience_years']].copy()
88
89
# StandardScaler (mean=0, std=1)
90
scaler = StandardScaler()
91
X_standard = scaler.fit_transform(X)
92
93
# MinMaxScaler [0, 1]
94
minmax_scaler = MinMaxScaler()
95
X_minmax = minmax_scaler.fit_transform(X)
96
97
# RobustScaler (resistant to outliers)
98
robust_scaler = RobustScaler()
99
X_robust = robust_scaler.fit_transform(X)
100
101
# Visualization
102
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
103
104
axes[0, 0].hist(X['age'], bins=30, edgecolor='black')
105
axes[0, 0].set_title('Original Age')
106
107
axes[0, 1].hist(X_standard[:, 0], bins=30, edgecolor='black')
108
axes[0, 1].set_title('StandardScaler Age')
109
110
axes[1, 0].hist(X_minmax[:, 0], bins=30, edgecolor='black')
111
axes[1, 0].set_title('MinMaxScaler Age')
112
113
axes[1, 1].hist(X_robust[:, 0], bins=30, edgecolor='black')
114
axes[1, 1].set_title('RobustScaler Age')
115
116
plt.tight_layout()
117
plt.show()
118
119
# 3. Polynomial Features
120
print("\n5. Polynomial Features:")
121
X_simple = df[['age']].copy()
122
poly = PolynomialFeatures(degree=2, include_bias=False)
123
X_poly = poly.fit_transform(X_simple)
124
X_poly_df = pd.DataFrame(X_poly, columns=['age', 'age^2'])
125
print(X_poly_df.head())
126
127
# Visualization
128
plt.figure(figsize=(12, 5))
129
plt.scatter(df['age'], df['income'], alpha=0.5)
130
plt.xlabel('Age')
131
plt.ylabel('Income')
132
plt.title('Age vs Income')
133
plt.grid(True, alpha=0.3)
134
plt.show()
135
136
# 4. Feature Interactions
137
print("\n6. Feature Interactions:")
138
df['age_income_interaction'] = df['age'] * df['income'] / 10000
139
df['age_experience_ratio'] = df['age'] / (df['experience_years'] + 1)
140
print(df[['age', 'income', 'age_income_interaction', 'age_experience_ratio']].head())
141
142
# 5. Domain-specific Transformations
143
print("\n7. Domain-specific Features:")
144
df['age_group'] = pd.cut(df['age'], bins=[0, 30, 45, 60, 100],
145
labels=['Young', 'Middle', 'Senior', 'Retired'])
146
df['income_level'] = pd.qcut(df['income'], q=3, labels=['Low', 'Medium', 'High'])
147
df['log_income'] = np.log1p(df['income'])
148
df['sqrt_experience'] = np.sqrt(df['experience_years'])
149
150
print(df[['age', 'age_group', 'income', 'income_level', 'log_income']].head())
151
152
# 6. Temporal Features (if date data available)
153
print("\n8. Temporal Features:")
154
dates = pd.date_range('2023-01-01', periods=len(df))
155
df['date'] = dates
156
df['year'] = df['date'].dt.year
157
df['month'] = df['date'].dt.month
158
df['day_of_week'] = df['date'].dt.dayofweek
159
df['quarter'] = df['date'].dt.quarter
160
df['is_weekend'] = df['date'].dt.dayofweek >= 5
161
162
print(df[['date', 'year', 'month', 'day_of_week', 'is_weekend']].head())
163
164
# 7. Feature Standardization Pipeline
165
print("\n9. Feature Engineering Pipeline:")
166
167
# Separate numerical and categorical features
168
numerical_features = ['age', 'income', 'experience_years']
169
categorical_features = ['category', 'city']
170
171
# Create preprocessing pipeline
172
preprocessor = ColumnTransformer(
173
transformers=[
174
('num', StandardScaler(), numerical_features),
175
('cat', OneHotEncoder(drop='first'), categorical_features),
176
]
177
)
178
179
X_processed = preprocessor.fit_transform(df[numerical_features + categorical_features])
180
print(f"Processed shape: {X_processed.shape}")
181
182
# 8. Feature Statistics
183
print("\n10. Feature Statistics:")
184
X_for_stats = df[numerical_features].copy()
185
X_for_stats['category_A'] = (df['category'] == 'A').astype(int)
186
X_for_stats['city_NYC'] = (df['city'] == 'NYC').astype(int)
187
188
feature_stats = pd.DataFrame({
189
'Feature': X_for_stats.columns,
190
'Mean': X_for_stats.mean(),
191
'Std': X_for_stats.std(),
192
'Min': X_for_stats.min(),
193
'Max': X_for_stats.max(),
194
'Skewness': X_for_stats.skew(),
195
'Kurtosis': X_for_stats.kurtosis(),
196
})
197
198
print(feature_stats)
199
200
# 9. Feature Correlations
201
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
202
203
X_numeric = df[numerical_features].copy()
204
X_numeric['purchased'] = df['purchased']
205
corr_matrix = X_numeric.corr()
206
207
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0, ax=axes[0])
208
axes[0].set_title('Feature Correlation Matrix')
209
210
# Distribution of engineered features
211
axes[1].hist(df['age_income_interaction'], bins=30, edgecolor='black', alpha=0.7)
212
axes[1].set_title('Age-Income Interaction Distribution')
213
axes[1].set_xlabel('Value')
214
axes[1].set_ylabel('Frequency')
215
216
plt.tight_layout()
217
plt.show()
218
219
# 10. Feature Binning / Discretization
220
print("\n11. Feature Binning:")
221
df['age_bin_equal'] = pd.cut(df['age'], bins=5)
222
df['age_bin_quantile'] = pd.qcut(df['age'], q=5)
223
df['income_bins'] = pd.cut(df['income'], bins=[0, 50000, 100000, 150000])
224
225
print("Equal Width Binning:")
226
print(df['age_bin_equal'].value_counts().sort_index())
227
228
print("\nEqual Frequency Binning:")
229
print(df['age_bin_quantile'].value_counts().sort_index())
230
231
# 11. Missing Value Creation and Handling
232
print("\n12. Missing Value Imputation:")
233
df_with_missing = df.copy()
234
missing_indices = np.random.choice(len(df), 50, replace=False)
235
df_with_missing.loc[missing_indices, 'age'] = np.nan
236
237
# Mean imputation
238
age_mean = df_with_missing['age'].mean()
239
df_with_missing['age_imputed_mean'] = df_with_missing['age'].fillna(age_mean)
240
241
# Median imputation
242
age_median = df_with_missing['age'].median()
243
df_with_missing['age_imputed_median'] = df_with_missing['age'].fillna(age_median)
244
245
# Forward fill
246
df_with_missing['age_imputed_ffill'] = df_with_missing['age'].fillna(method='ffill')
247
248
print(df_with_missing[['age', 'age_imputed_mean', 'age_imputed_median']].head(10))
249
250
print("\nFeature Engineering Complete!")
251
print(f"Original features: {len(df.columns) - 5}")
252
print(f"Final features available: {len(df.columns)}")
253
```
254
255
## Best Practices
256
257
- Understand your domain before engineering features
258
- Create features that are interpretable
259
- Avoid data leakage (using future information)
260
- Test feature importance after engineering
261
- Document all transformations
262
- Use appropriate scaling for different algorithms
263
264
## Common Transformations
265
266
- **Log Transform**: For skewed distributions
267
- **Polynomial Features**: For non-linear relationships
268
- **Interaction Terms**: For combined effects
269
- **Binning**: For categorical approximation
270
- **Normalization**: For comparison across scales
271
272
## Deliverables
273
274
- Engineered feature dataset
275
- Feature transformation documentation
276
- Correlation analysis of new features
277
- Distribution comparisons (before/after)
278
- Feature importance rankings
279
- Preprocessing pipeline code
280
- Data dictionary with feature descriptions
281