1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
| def create_behavioral_sequence_features(self, user_activities_df: pd.DataFrame):
"""
从用户活动数据创建行为序列特征
Args:
user_activities_df: 包含用户活动数据的数据框
应包含:user_id, activity_type, activity_date, activity_details
"""
activities = user_activities_df.copy()
activities['activity_date'] = pd.to_datetime(activities['activity_date'])
activities = activities.sort_values(['user_id', 'activity_date'])
# 计算活动频率
user_activity_freq = activities.groupby(['user_id', 'activity_type']).size().reset_index(name='freq')
user_activity_pivot = user_activity_freq.pivot(
index='user_id',
columns='activity_type',
values='freq'
).fillna(0).add_prefix('act_')
# 活跃度指标
time_diffs = activities.groupby('user_id')['activity_date'].diff().dt.days.fillna(0)
activities.loc[:, 'days_since_last_activity'] = time_diffs
# 计算用户持续活跃天数统计
user_engagement_metrics = activities.groupby('user_id').agg({
'days_since_last_activity': ['mean', 'min', 'max', 'std'],
'activity_date': ['nunique', 'count'], # 独一日期和总活动数
}).fillna(0)
# 扁平化列名
user_engagement_metrics.columns = [
'engagement_' + '_'.join(col).strip()
for col in user_engagement_metrics.columns.values
]
# 合并所有行为特征
result = pd.concat([
user_engagement_metrics,
user_activity_pivot
], axis=1).fillna(0)
return result.reset_index()
def create_risk_segmentation_features(self, df: pd.DataFrame):
"""
创建风险细分特征
Args:
df: 包含客户信息的数据框
"""
risk_features = df.copy()
# 基于信用评分的风险分级
if 'credit_score' in df.columns:
risk_features['credit_grade'] = pd.cut(
df['credit_score'],
bins=[0, 550, 650, 750, 850, np.inf],
labels=['Very Poor', 'Poor', 'Fair', 'Good', 'Excellent']
).cat.codes
# 收入等级划分
if 'income' in df.columns:
risk_features['income_bracket'] = pd.qcut(
df['income'],
q=5,
labels=['Bottom 20%', '20-40%', 'Mid 20%', '40-80%', 'Top 20%']
).cat.codes
# 综合风险评分
if 'credit_score' in df.columns and 'income' in df.columns:
risk_features['composite_risk_score'] = (
0.4 * (df['credit_score'] / df['credit_score'].max()) +
0.3 * (df.get('income', 0) / df.get('income', 0).max()) +
0.3 * (df.get('age', 0) / df.get('age', 0).max()).fillna(0)
)
return risk_features
# 7. 高级特征工程流水线
class AdvancedFeatureEngineeringPipeline:
"""
高级特征工程流水线整合上述所有方法
"""
def __init__(self):
self.feature_processors = {
'tsfresh': AutomatedTSFreshFramework(),
'featuretools': AutomatedFeatureToolsFramework(),
'autofeat': AutomatedAutoFeatFramework(),
'time_series': TimeSeriesFeatureEngineering(),
'cross_features': CrossFeatureEngineering(),
'selector': FeatureSelectorHybrid(),
'fintech_risk': FintechRiskFeatures()
}
def run_complete_pipeline(self,
raw_data: Dict[str, pd.DataFrame],
target_col: str = None,
task_type: str = 'classification',
enable_ts_features: bool = True,
enable_cross_features: bool = True,
enable_selection: bool = True):
"""
运行完整特征工程流水线
Args:
raw_data: 原始数据字典
target_col: 目标列名
task_type: 任务类型 ('classification', 'regression')
enable_ts_features: 是否启用时间序列特征
enable_cross_features: 是否启用交叉特征
enable_selection: 是否启用特征选择
"""
processed_data = {}
# 1. 自动化特征工程
print("步骤 1: 运行自动化特征工程...")
if 'main' in raw_data:
try:
feat_tools_framework = AutomatedFeatureToolsFramework()
feature_matrix, feature_defs = (
feat_tools_framework
.setup_entityset(raw_data)
.generate_features('main')
)
if target_col and target_col in raw_data['main'].columns:
y = raw_data['main'][target_col]
X = feature_matrix.drop(columns=[target_col])
else:
print("警告: 未找到目标列,跳过监督特征选择")
X = feature_matrix
y = None
except Exception as e:
print(f"特征工具出错: {e}")
# 备选方案 - 简单的特征合并
X = pd.concat(raw_data.values(), axis=1).fillna(0)
y = raw_data.get('main', pd.DataFrame()).get(target_col)
else:
# 如果没有'main'实体,使用第一个数据框
first_key = list(raw_data.keys())[0]
X = raw_data[first_key].copy()
if target_col in X.columns:
y = X.pop(target_col) # 从X中移除目标列并保存
else:
y = None
# 2. 时间序列特征(如果适用)
if enable_ts_features and 'timeseries' in raw_data:
print("步骤 2: 生产时间序列特征...")
ts_feat_eng = TimeSeriesFeatureEngineering()
ts_features = ts_feat_eng.create_lag_features(
raw_data['timeseries'],
value_column=raw_data['timeseries'].select_dtypes(
include=[np.number]).columns[0]
)
# 合并时间序列特征与主特征矩阵
X = pd.concat([X, ts_features.drop(columns=raw_data['timeseries'].columns)], axis=1)
# 3. 交叉特征
if enable_cross_features and len(X.select_dtypes(include=[np.number]).columns) > 1:
print("步骤 3: 创建交叉特征...")
cross_engineer = CrossFeatureEngineering()
numeric_cols = X.select_dtypes(include=[np.number]).columns[:10] # 只使用前10个特征,避免过多交互
X_cross = cross_engineer.create_manual_interactions(X, numeric_cols.tolist())
X = X_cross
# 4. 风控特征(如果适用)
if 'risk_data' in raw_data:
print("步骤 4: 创建风险领域专用特征...")
risk_engineer = FintechRiskFeatures()
if 'bureau' in raw_data:
bureau_risk_features = risk_engineer.create_aggregated_bureau_features(raw_data['bureau'])
X = X.merge(bureau_risk_features, left_on='user_id', right_on='person_id', how='left')
# 5. 特征选择(如果提供目标变量)
if enable_selection and y is not None:
print("步骤 5: 执行特征选择...")
# 将数据分割为训练集和测试集用于选择
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 拟合简单模型用于选择
if task_type == 'classification':
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=50, random_state=42)
else:
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators=50, random_state=42)
model.fit(X_train, y_train)
# 使用混合选择方法
hybrid_selector = FeatureSelectorHybrid(primary_method='permutation')
selected_indices = hybrid_selector.fit_selection(X_train, y_train, model=model)
# 裁剪特征集合
X = X.iloc[:, selected_indices] if len(selected_indices) > 0 else X
print(f"最终特征矩阵形状: {X.shape}")
return X, y
# 8. 决策流程图说明
def print_decision_flow():
"""
打印特征工程决策流程
"""
flow_chart = """
高级特征工程决策流程图
========================
开始分析数据结构
|
v
┌─────────────────┐
│ 评估数据特征 │
│ - 数据量级 │
│ - 数据结构 │
│ - 时间序列性 │
│ - 业务领域 │
└─────────┬───────┘
|
v
┌─────────────────┐
│ 自动化特征提取 │
│ ? │
│ 适合复杂关系数据│
└─────┬─────────┬─┘
│ 是 │ 否
v v
┌─────────┐ ┌─────────────┐
│ TSFresh │ │ 手工设计 │
│FeatTools│ │ 或领域特征 │
│AutoFeat │ └─────────────┘
└─────────┘
|
v
┌─────────────────┐
│ 时间序列特征 │
│ ? │
└─────┬───────────┘
│ 是
v
┌─────────────────┐
│ 滞后特征 │
│ 滚动统计 │
│ 循环编码 │
│ 变化特征 │
└─────────────────┘
|
v
┌─────────────────┐
│ 交叉特征工程 │
│ ? │
└─────┬───────────┘
│ 是
v
┌─────────────────┐
│ 低到高阶交叉 │
│ 比率特征 │
│ 逻辑交互 │
└─────────────────┘
|
v
┌─────────────────┐
│ 域特定特征 │
│ ? │
│ (金融/医疗/等) │
└─────┬───────────┘
│ 是
v
┌─────────────────┐
│ 预定义模板 │
│ 风险评分 │
│ 行为指标 │
└─────────────────┘
|
v
┌─────────────────┐
│ 特征选择 │
│ ? │
└─────┬───────────┘
│ 是
v
┌─────────────────┐
│ - 置换重要性 │
│ - SHAP分析 │
│ - 遗传算法 │
│ - 统计测试 │
└─────────────────┘
|
v
┌─────────────────┐
│ 特征质量验证 │
│ - 重复性检测 │
│ - 多重共线检测 │
│ - 有效性评估 │
└─────────────────┘
|
v
┌─────────────────┐
│ 清理最终特征集 │
└─────────────────┘
|
v
┌─────────────────┐
│ 构建模型管道 │
└─────────────────┘
"""
print(flow_chart)
# 9. 使用示例
def example_usage():
"""
演示如何使用完整的特征工程框架
"""
print("=== 高级特征工程框架演示 ===\n")
# 示例数据创建
np.random.seed(42)
n_samples = 1000
# 创建示例主表数据
demo_main_data = pd.DataFrame({
'user_id': range(n_samples),
'age': np.random.randint(18, 80, n_samples),
'income': np.random.lognormal(10, 1, n_samples),
'credit_score': np.random.normal(650, 100, n_samples),
'requested_amount': np.random.lognormal(10, 0.8, n_samples),
'target': np.random.binomial(1, 0.1, n_samples)
})
# 创建示例历史数据
n_records_per_user = 5
demo_history_data = pd.DataFrame({
'user_id': np.repeat(range(n_samples), n_records_per_user),
'transaction_amount': np.random.normal(1000, 200, n_samples * n_records_per_user),
'days_ago': np.random.randint(1, 365, n_samples * n_records_per_user)
})
# 准备数据字典
sample_data = {
'main': demo_main_data,
'history': demo_history_data
}
print(f"输入数据结构:")
for name, df in sample_data.items():
print(f"{name}: 形状={df.shape}, 列名={df.columns.tolist()}")
print(f"\ntarget列值分布:\n{demo_main_data['target'].value_counts()}")
# 实例化流水线
pipeline = AdvancedFeatureEngineeringPipeline()
# 运行完整流水线
processed_X, processed_y = pipeline.run_complete_pipeline(
raw_data=sample_data,
target_col='target',
task_type='classification',
enable_ts_features=True,
enable_cross_features=True,
enable_selection=True
)
print(f"\n处理后的数据:")
print(f"特征矩阵形状: {processed_X.shape}")
print(f"目标向量形状: {processed_y.shape if processed_y is not None else 'None'}")
print("\n特征工程完成! 演示结束.")
# 在适当位置添加主执行块
if __name__ == "__main__":
print("运行高级特征工程框架演示...")
print_decision_flow()
print("\n" + "="*60)
example_usage()
|