Justin7219 commited on
Commit
392d9fc
·
verified ·
1 Parent(s): 82a7a5f

Add engineered feature files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. outputs/features/autofeat/breast_w_features.csv +3 -0
  2. outputs/features/autofeat/credit_g_features.csv +3 -0
  3. outputs/features/autofeat/diabetes_features.csv +3 -0
  4. outputs/features/autofeat/heart_features.csv +3 -0
  5. outputs/features/caafe/adult_features.csv +3 -0
  6. outputs/features/caafe/bank_marketing_features.csv +3 -0
  7. outputs/features/caafe/blood_transfusion_features.csv +3 -0
  8. outputs/features/caafe/breast_w_features.csv +3 -0
  9. outputs/features/caafe/credit_g_features.csv +3 -0
  10. outputs/features/caafe/diabetes_features.csv +3 -0
  11. outputs/features/caafe/heart_features.csv +3 -0
  12. outputs/features/caafe/simecny_40feat_features.csv +3 -0
  13. outputs/features/caafe/simecny_features.csv +3 -0
  14. outputs/features/featllm/adult_features.csv +3 -0
  15. outputs/features/featllm/bank_marketing_features.csv +3 -0
  16. outputs/features/featllm/blood_transfusion_features.csv +3 -0
  17. outputs/features/featllm/breast_w_features.csv +3 -0
  18. outputs/features/featllm/credit_g_features.csv +3 -0
  19. outputs/features/featllm/diabetes_features.csv +3 -0
  20. outputs/features/featllm/heart_features.csv +3 -0
  21. outputs/features/featllm/simecny_40feat_features.csv.gz +3 -0
  22. outputs/features/featllm/simecny_features.csv.gz +3 -0
  23. outputs/features/knowfeat/adult_features.csv +3 -0
  24. outputs/features/knowfeat/adult_schema_only_features.csv +3 -0
  25. outputs/features/knowfeat/bank_marketing_features.csv +3 -0
  26. outputs/features/knowfeat/blood_transfusion_features.csv +3 -0
  27. outputs/features/knowfeat/breast_w_features.csv +3 -0
  28. outputs/features/knowfeat/credit_g_features.csv +3 -0
  29. outputs/features/knowfeat/diabetes_features.csv +3 -0
  30. outputs/features/knowfeat/heart_features.csv +3 -0
  31. outputs/features/knowfeat/heart_schema_only_features.csv +3 -0
  32. outputs/features/knowfeat/simecny_features.csv +3 -0
  33. outputs/features/knowfeat/simecny_schema_only_features.csv +3 -0
  34. outputs/features/knowfeat_ablation/bank_marketing_expert_generic_features.json +107 -0
  35. outputs/features/knowfeat_ablation/bank_marketing_expert_knowfeat_features.csv +3 -0
  36. outputs/features/knowfeat_ablation/bank_marketing_indicators_generic_features.json +158 -0
  37. outputs/features/knowfeat_ablation/bank_marketing_indicators_knowfeat_features.csv +3 -0
  38. outputs/features/knowfeat_ablation/bank_marketing_rules_generic_features.json +86 -0
  39. outputs/features/knowfeat_ablation/bank_marketing_rules_knowfeat_features.csv +3 -0
  40. outputs/features/knowfeat_ablation/blood_transfusion_expert_generic_features.json +43 -0
  41. outputs/features/knowfeat_ablation/blood_transfusion_expert_knowfeat_features.csv +3 -0
  42. outputs/features/knowfeat_ablation/blood_transfusion_indicators_generic_features.json +37 -0
  43. outputs/features/knowfeat_ablation/blood_transfusion_indicators_knowfeat_features.csv +3 -0
  44. outputs/features/knowfeat_ablation/blood_transfusion_rules_generic_features.json +47 -0
  45. outputs/features/knowfeat_ablation/blood_transfusion_rules_knowfeat_features.csv +3 -0
  46. outputs/features/knowfeat_ablation/breast_w_expert_generic_features.json +73 -0
  47. outputs/features/knowfeat_ablation/breast_w_expert_knowfeat_features.csv +3 -0
  48. outputs/features/knowfeat_ablation/breast_w_indicators_generic_features.json +30 -0
  49. outputs/features/knowfeat_ablation/breast_w_indicators_knowfeat_features.csv +3 -0
  50. outputs/features/knowfeat_ablation/breast_w_rules_generic_features.json +93 -0
outputs/features/autofeat/breast_w_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b72d1e053c70c6188eb6295be7d699a51e11ebf37ee0bfdfe3b3e8bd7025316
3
+ size 52076
outputs/features/autofeat/credit_g_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acd680901fd641bc46682f154d85bb6154747dfe2faaf0b009b4b462161e72a2
3
+ size 22528
outputs/features/autofeat/diabetes_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5369fd95a50975f0f0bfabfef970ec21c20478bb8e5dcde0c6b29ecaabf1bbb6
3
+ size 43828
outputs/features/autofeat/heart_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52f4bfbb0fdad92914f4527d2eee2b82bf677ae885268d6051f0977eaafa6c95
3
+ size 65409
outputs/features/caafe/adult_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5fd2813bd27555eeba3b16295b9b892d71b75a0307cc855fc4440f56bd2f3cda
3
+ size 723660
outputs/features/caafe/bank_marketing_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d435e9b6afc4f28c2aae5df1cd3b78ee6d4ac42d6ccd6c0ae61dfc13db66aa99
3
+ size 1006399
outputs/features/caafe/blood_transfusion_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e67d972bddaf824140b7bee3f1199dfd4c1c56c4626f0a5391d5356351e42ef9
3
+ size 8703
outputs/features/caafe/breast_w_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:530b5f7ac30e7f3a3613c8e96d5b3919d2bd14149f86dd7d0ab28290961066c3
3
+ size 1665
outputs/features/caafe/credit_g_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77bf51935db7694db9a3db8285a14edf9580ddccab100c7bb0d6c979b5135fc9
3
+ size 23321
outputs/features/caafe/diabetes_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ac6a5022f4d7d0346021081738bdd93a97231669d44c015b53f61d37a2a5133
3
+ size 2926
outputs/features/caafe/heart_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf6b9a683ca4aa677838b2f26baee7eb8504e397831dfceb19ff6363402b567e
3
+ size 20390
outputs/features/caafe/simecny_40feat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7e7fc67790a92ce46c052f5659af02d468b6701b7130d2b5cbeb378e3fe5c49
3
+ size 3801342
outputs/features/caafe/simecny_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d63c83ba0deb2757dcdae72db36e6397a596a71e7f06b8505102b405172ffdef
3
+ size 3959104
outputs/features/featllm/adult_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb52925a21f0cf0784c1f54f055d1dc991b7c4baefff2585f92af5b456b96c4b
3
+ size 29995824
outputs/features/featllm/bank_marketing_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fcee603cc8175d19195434e39a3cc4b68dcd842663c5d2214f2a36a618c8dcbf
3
+ size 15643578
outputs/features/featllm/blood_transfusion_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aff624daa4e994d8cfc61e34b1b34b7b8329056509e40d620afb451ccb2e0376
3
+ size 248763
outputs/features/featllm/breast_w_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc33cfb5973a156dda6ebcdbc19f02f496f9cac2d68b415db4618ade9750bf9d
3
+ size 137046
outputs/features/featllm/credit_g_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7a710c2eb625de1cf00a1fc5717d6206e5f6235fae77fd2c386ff407fc3f053
3
+ size 1367425
outputs/features/featllm/diabetes_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18eb80182cb2618a0938b740095fcbb3ed7f111ab75f1d20e4ebed8b407ddeac
3
+ size 309581
outputs/features/featllm/heart_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a9b0ace482a08ca36e1c3bfa09400e60c308841e40daaa14ea44737dfa43b12
3
+ size 176733
outputs/features/featllm/simecny_40feat_features.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4aa75768f2d1bfac5908a49e3a13efd49e883bbc5461529794d22085be75a9f8
3
+ size 125335935
outputs/features/featllm/simecny_features.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46101ee42a37797c1db8ba4ee27f0e53de88b43dba3e911a1442c155182c01d5
3
+ size 108381936
outputs/features/knowfeat/adult_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca57e1c4db42509bef61a7e523fdf172fd3133d7e3eb943f5c411bdf3c85e9f5
3
+ size 5542525
outputs/features/knowfeat/adult_schema_only_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5fc4b459a1e4e9fd95861d7dc7d65778712823c67db860a5bb4bba9b9bab39b
3
+ size 8612645
outputs/features/knowfeat/bank_marketing_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c408655a99edffa124c7788a4b13552f8353b25e2bd7e1d484dc9eb87763c0b
3
+ size 2075012
outputs/features/knowfeat/blood_transfusion_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3516cb233f224d801144c62411c8878c9b9c606dcd74f4fbeb44e848582ae58
3
+ size 60068
outputs/features/knowfeat/breast_w_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93a3bd21b449754421fad7e1868b1e6d6e5b5fa9f3a457d79953b1f2f5f9fd8e
3
+ size 35087
outputs/features/knowfeat/credit_g_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ff9b3488f11e00c757b4b14612c3ec7dfcd735fbf2470a4a4929e5e1e555a60
3
+ size 57345
outputs/features/knowfeat/diabetes_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52cf6a1807fab1c91177468c3cae26fe8733e0f407ca9f8a2324d9dfd53b51e6
3
+ size 141985
outputs/features/knowfeat/heart_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b21eba008d29882c0c2fb3116ddca0a74bc0b8e7d36cc75915267b244085f27
3
+ size 83309
outputs/features/knowfeat/heart_schema_only_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:209ca42c4d3c9bc257c621f74ee9c80afcd5597bf79fd2715b81191ff3382d0d
3
+ size 49949
outputs/features/knowfeat/simecny_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77c55ad6f4460c46b8ad20adf9b304bf95069437fc7bd3ded931dfe36526ed59
3
+ size 5924227
outputs/features/knowfeat/simecny_schema_only_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f70f573482fed871892755c6d25d88cf86f27a6573e9efb1a60c3c3d34779b4
3
+ size 3139922
outputs/features/knowfeat_ablation/bank_marketing_expert_generic_features.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "customer_financial_health_score",
4
+ "dimensions": [
5
+ "客户画像"
6
+ ],
7
+ "code": "def customer_financial_health_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于 RULE_005: 无住房贷款+无个人贷款+正余额+无违约 = 高优先级\n # 每个条件贡献1分,总分0-4分\n \n # 1. 无住房贷款 (IND_05)\n score_housing = (df['housing'] == 'no').astype(int)\n \n # 2. 无个人贷款 (IND_06)\n score_loan = (df['loan'] == 'no').astype(int)\n \n # 3. 无违约 (IND_10)\n score_default = (df['default'] == 'no').astype(int)\n \n # 4. 正余额 (IND_11) - 余额>0\n score_balance = (df['balance'] > 0).astype(int)\n \n # 总分\n result['fin_health_score'] = score_housing + score_loan + score_default + score_balance\n \n return result[['row_id', 'fin_health_score']]\n"
8
+ },
9
+ {
10
+ "name": "age_job_lifecycle_stage",
11
+ "dimensions": [
12
+ "客户画像"
13
+ ],
14
+ "code": "def age_job_lifecycle_stage(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于 IND_07(职业类型) 和年龄的交互效应\n # 不同年龄段的相同职业有不同含义\n # 例如:年轻学生(18-25) vs 年长学生(25-35) 转化率不同\n # 退休人员中,65+的转化率远高于55-65\n \n # 创建年龄分段\n age = df['age']\n job = df['job']\n \n # 定义生命周期阶段评分\n # 基于探索数据发现的高转化率组合\n \n # 1. 年轻学生 (<25) - 高转化率 ~36%\n cond1 = (age < 25) & (job == 'student')\n \n # 2. 年长退休人员 (65+) - 极高转化率 ~44%\n cond2 = (age >= 65) & (job == 'retired')\n \n # 3. 年轻管理层 (<25) - 高转化率 ~27.5%\n cond3 = (age < 25) & (job == 'management')\n \n # 4. 年轻自由职业 (<25) - 高转化率 ~32%\n cond4 = (age < 25) & (job == 'self-employed')\n \n # 5. 65+ 其他职业 - 较高转化率\n cond5 = (age >= 65) & (job.isin(['technician', 'housemaid', 'management', 'admin.', 'entrepreneur']))\n \n # 6. 55-65 退休人员 - 中等转化率\n cond6 = (age >= 55) & (age < 65) & (job == 'retired')\n \n # 7. 学生 (25-35) - 中等转化率 ~22%\n cond7 = (age >= 25) & (age < 35) & (job == 'student')\n \n # 8. 55-65 管理层/管理 - 中等转化率\n cond8 = (age >= 55) & (age < 65) & (job.isin(['management', 'admin.']))\n \n # 9. 年轻失业 (<25)\n cond9 = (age < 25) & (job == 'unemployed')\n \n # 10. 蓝领 (任何年龄) - 低转化率基准\n cond10 = (job == 'blue-collar')\n \n # 赋值评分 (基于探索数据中的转化率)\n result['age_job_stage'] = 0\n result.loc[cond1, 'age_job_stage'] = 4 # 年轻学生\n result.loc[cond2, 'age_job_stage'] = 5 # 年长退休人员 (最高)\n result.loc[cond3, 'age_job_stage'] = 3 # 年轻管理层\n result.loc[cond4, 'age_job_stage'] = 3 # 年轻自由职业\n result.loc[cond5, 'age_job_stage'] = 4 # 65+其他职业\n result.loc[cond6, 'age_job_stage'] = 2 # 55-65退休\n result.loc[cond7, 'age_job_stage'] = 2 # 25-35学生\n result.loc[cond8, 'age_job_stage'] = 1 # 55-65管理层\n result.loc[cond9, 'age_job_stage'] = 1 # 年轻失业\n result.loc[cond10, 'age_job_stage'] = -1 # 蓝领 (低转化)\n \n return result[['row_id', 'age_job_stage']]\n"
15
+ },
16
+ {
17
+ "name": "education_job_housing_social_grade",
18
+ "dimensions": [
19
+ "客户画像"
20
+ ],
21
+ "code": "def education_job_housing_social_grade(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于 IND_09(教育水平)、IND_07(职业类型)、IND_05(住房贷款)的交互效应\n edu = df['education'].values\n job = df['job'].values\n housing = df['housing'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 高转化率组合 (>25%)\n # student + no housing 无论教育水平\n student_no_mask = (job == 'student') & (housing == 'no')\n scores[student_no_mask] = 3.0\n \n # student + yes housing\n student_yes_mask = (job == 'student') & (housing == 'yes')\n scores[student_yes_mask] = 2.0\n \n # retired + tertiary + no housing\n retired_tertiary_no = (job == 'retired') & (edu == 'tertiary') & (housing == 'no')\n scores[retired_tertiary_no] = 2.5\n \n # retired + primary/secondary + no housing\n retired_other_no = (job == 'retired') & (np.isin(edu, ['primary', 'secondary'])) & (housing == 'no')\n scores[retired_other_no] = 2.0\n \n # unemployed + tertiary + no housing\n unemployed_tertiary_no = (job == 'unemployed') & (edu == 'tertiary') & (housing == 'no')\n scores[unemployed_tertiary_no] = 2.0\n \n # 中等转化率组合 (15-25%)\n # management + tertiary + no housing\n mgmt_tertiary_no = (job == 'management') & (edu == 'tertiary') & (housing == 'no')\n scores[mgmt_tertiary_no] = 1.5\n \n # admin./technician + tertiary + no housing\n white_collar_tertiary_no = (np.isin(job, ['admin.', 'technician'])) & (edu == 'tertiary') & (housing == 'no')\n scores[white_collar_tertiary_no] = 1.0\n \n # 任何职业 + tertiary + no housing (通用)\n any_tertiary_no = (edu == 'tertiary') & (housing == 'no') & (scores == 0)\n scores[any_tertiary_no] = 1.0\n \n # 任何职业 + unknown + no housing\n any_unknown_no = (edu == 'unknown') & (housing == 'no') & (scores == 0)\n scores[any_unknown_no] = 0.5\n \n # 低转化率组合 (<10%)\n # blue-collar + yes housing\n blue_collar_yes = (job == 'blue-collar') & (housing == 'yes')\n scores[blue_collar_yes] = -1.0\n \n # primary + yes housing (除student/retired外)\n primary_yes = (edu == 'primary') & (housing == 'yes') & (~np.isin(job, ['student', 'retired']))\n scores[primary_yes] = -0.5\n \n # 默认值:secondary + yes housing\n secondary_yes_default = (edu == 'secondary') & (housing == 'yes') & (scores == 0)\n scores[secondary_yes_default] = 0.0\n \n result['edu_job_housing_grade'] = scores\n \n return result[['row_id', 'edu_job_housing_grade']]\n"
22
+ },
23
+ {
24
+ "name": "contact_history_quality_score",
25
+ "dimensions": [
26
+ "联系记录"
27
+ ],
28
+ "code": "def contact_history_quality_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于领域知识中的多个规则和指标:\n # IND_01: poutcome=success 大幅增加认购概率 (>60%)\n # RULE_002: 优先历史成功客户\n # RULE_001: 3次联系规则,超过后转化率下降\n # IND_12: 联系次数边际效应,超过3-4次后效果递减\n \n poutcome = df['poutcome'].values\n campaign = df['campaign'].values\n previous = df['previous'].values\n pdays = df['pdays'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 步骤1: 基于 poutcome 的基础评分\n # poutcome=success: 最高分 (IND_01, RULE_002)\n # poutcome=other: 中等分\n # poutcome=failure: 低分\n # poutcome=unknown: 最低分(无历史信息)\n \n # 步骤2: 结合 campaign 调整(RULE_001, IND_12)\n # campaign<=3: 保持或加分\n # campaign>3: 减分(边际效应递减)\n \n # 步骤3: 结合 previous 调整(之前被联系过是正信号)\n # previous>0: 加分\n \n # 步骤4: 结合 pdays 调整(EXP_05)\n # pdays>0(之前被联系过): 加分\n \n # 组合评分\n for i in range(n):\n score = 0.0\n \n # poutcome 基础分\n if poutcome[i] == 'success':\n score += 3.0\n elif poutcome[i] == 'other':\n score += 1.5\n elif poutcome[i] == 'failure':\n score += 0.5\n # unknown: 0.0\n \n # campaign 调整 (RULE_001: 3次联系规则)\n if campaign[i] <= 3:\n score += 1.0 # 最佳联系次数\n elif campaign[i] <= 5:\n score += 0.0 # 中性\n else:\n score -= 1.0 # 过度联系,减分\n \n # previous 调整 (IND_12: 之前被联系过是正信号)\n if previous[i] > 0:\n score += 1.0\n \n # pdays 调整 (EXP_05: 之前被联系过是正信号)\n if pdays[i] > 0:\n score += 0.5\n \n scores[i] = score\n \n result['contact_history_quality'] = scores\n \n return result[['row_id', 'contact_history_quality']]"
29
+ },
30
+ {
31
+ "name": "seasonal_contact_effectiveness",
32
+ "dimensions": [
33
+ "联系记录"
34
+ ],
35
+ "code": "def seasonal_contact_effectiveness(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于领域知识:\n # IND_04(季节性时机): 3月(~50.5%)、9月、10月、12月最高\n # RULE_003(季节性活动时机): 集中在3月、9月、10月、12月开展活动\n # RULE_004(手机优先): 手机联系转化率约为电话的3倍\n # IND_03(联系方式-手机): cellular ~15%, telephone ~5%\n # EXP_08: 葡萄牙定期存款认购的季节性由税季(3月)、财年末(9-10月)、年终奖(12月)驱动\n \n month = df['month'].values\n contact = df['contact'].values\n previous = df['previous'].values\n campaign = df['campaign'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 最佳月份列表 (IND_04, RULE_003)\n best_months = {'mar', 'sep', 'oct', 'dec'}\n \n for i in range(n):\n score = 0.0\n \n # 月份评分 (IND_04, RULE_003, EXP_08)\n if month[i] in best_months:\n score += 2.0 # 最佳月份\n elif month[i] in {'apr', 'jun', 'nov'}:\n score += 0.5 # 中等月份\n elif month[i] in {'jan', 'feb', 'jul', 'aug'}:\n score += 0.0 # 一般月份\n else: # may - 最差月份\n score -= 0.5 # 5月过度饱和,转化率最低\n \n # 联系方式评分 (IND_03, RULE_004)\n if contact[i] == 'cellular':\n score += 1.5 # 手机联系,关系深度高\n elif contact[i] == 'telephone':\n score += 0.5 # 电话联系\n else: # unknown\n score -= 0.5 # 未知联系方式,关系深度低\n \n # 交互增强:最佳月份+手机联系有协同效应 (EXP_06)\n if month[i] in best_months and contact[i] == 'cellular':\n score += 1.0 # 协同效应加分\n \n # previous>0 进一步增强 (之前被联系过是正信号)\n if previous[i] > 0 and month[i] in best_months:\n score += 0.5\n \n # campaign<=3 在最佳月份中效果更好\n if month[i] in best_months and campaign[i] <= 3:\n score += 0.5\n \n scores[i] = score\n \n result['seasonal_contact_eff'] = scores\n \n return result[['row_id', 'seasonal_contact_eff']]"
36
+ },
37
+ {
38
+ "name": "contact_fatigue_index",
39
+ "dimensions": [
40
+ "联系记录"
41
+ ],
42
+ "code": "def contact_fatigue_index(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于领域知识:\n # RULE_001(3次联系规则): campaign<=3最优,超过后转化率急剧下降\n # IND_12(联系次数边际效应): 超过3-4次后效果递减,>5次转化率降至~8.7%\n # EXP_05(pdays编码处理): pdays=-1表示从未被联系过\n # RULE_010(反饱和量控): 月联系量超过5000后预期递减回报\n \n campaign = df['campaign'].values\n pdays = df['pdays'].values\n previous = df['previous'].values\n poutcome = df['poutcome'].values\n \n n = len(df)\n fatigue = np.zeros(n, dtype=float)\n \n for i in range(n):\n # 基础疲劳度:campaign越高越疲劳\n # 使用非线性变换:campaign=1时疲劳度低,快速上升后趋于平缓\n c = campaign[i]\n \n # 步骤1: 基于campaign的疲劳基础分(RULE_001, IND_12)\n if c <= 1:\n base_fatigue = 0.0 # 首次联系,无疲劳\n elif c <= 3:\n base_fatigue = 0.3 # 2-3次,轻度疲劳\n elif c <= 5:\n base_fatigue = 0.6 # 4-5次,中度疲劳\n elif c <= 8:\n base_fatigue = 0.8 # 6-8次,高度疲劳\n else:\n base_fatigue = 1.0 # 9次以上,极度疲劳\n \n # 步骤2: 根据pdays调整(EXP_05)\n # 从未联系过(pdays=-1)的客户对多次联系更敏感\n # 之前联系过(pdays>0)的客户对多次联系容忍度稍高\n if pdays[i] == -1:\n # 从未联系过,疲劳效应更强\n pass # 保持基础疲劳度\n else:\n # 之前联系过,疲劳度稍微减轻(有历史关系)\n base_fatigue = max(0, base_fatigue - 0.1)\n \n # 步骤3: 根据previous调整(IND_12)\n # previous>0表示之前被联系过,有历史关系,疲劳度减轻\n if previous[i] > 0:\n base_fatigue = max(0, base_fatigue - 0.15)\n \n # 步骤4: 根据poutcome调整(IND_01)\n # poutcome=success: 即使多次联系也不疲劳\n # poutcome=failure: 多次联系疲劳度加重\n if poutcome[i] == 'success':\n base_fatigue = max(0, base_fatigue - 0.3)\n elif poutcome[i] == 'failure':\n base_fatigue = min(1.0, base_fatigue + 0.2)\n \n fatigue[i] = base_fatigue\n \n result['contact_fatigue'] = fatigue\n \n return result[['row_id', 'contact_fatigue']]"
43
+ },
44
+ {
45
+ "name": "education_adjusted_balance_rank",
46
+ "dimensions": [
47
+ "经济环境"
48
+ ],
49
+ "code": "def education_adjusted_balance_rank(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于领域知识:\n # IND_09: 教育水平 - 高等教育与金融素养、更高收入相关\n # IND_11: 账户余额 - 余额越高认购率越高\n # 核心思想:相同教育水平内,余额相对排名更能反映经济状况\n # 因为不同教育水平的余额基准不同(tertiary中位数577 vs primary中位数403)\n \n # 计算每个教育水平内的余额百分位排名\n edu_balance_pct = np.zeros(len(df), dtype=float)\n \n for edu in df['education'].unique():\n mask = df['education'] == edu\n sub_balance = df.loc[mask, 'balance'].values\n # 使用排名百分比\n ranks = np.argsort(np.argsort(sub_balance))\n pct = ranks / (len(sub_balance) - 1) if len(sub_balance) > 1 else 0.5\n edu_balance_pct[mask.values] = pct\n \n # 将百分位映射到[-1, 1]范围,中心化\n # 百分位0-0.2 -> -1.0到-0.6 (低)\n # 百分位0.2-0.4 -> -0.6到-0.2\n # 百分位0.4-0.6 -> -0.2到0.2 (中等)\n # 百分位0.6-0.8 -> 0.2到0.6\n # 百分位0.8-1.0 -> 0.6到1.0 (高)\n \n result['edu_balance_rank'] = (edu_balance_pct - 0.5) * 2.0\n \n return result[['row_id', 'edu_balance_rank']]\n"
50
+ },
51
+ {
52
+ "name": "month_job_financial_interaction",
53
+ "dimensions": [
54
+ "时机因素"
55
+ ],
56
+ "code": "def month_job_financial_interaction(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n month = df['month'].values\n job = df['job'].values\n housing = df['housing'].values\n loan = df['loan'].values\n balance = df['balance'].values\n default = df['default'].values\n education = df['education'].values\n marital = df['marital'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 最佳月份 (IND_04, RULE_003, EXP_08)\n best_months = {'mar', 'sep', 'oct', 'dec'}\n # 最差月份\n worst_months = {'may', 'jul'}\n \n for i in range(n):\n score = 0.0\n m = month[i]\n j = job[i]\n h = housing[i]\n l = loan[i]\n b = balance[i]\n d = default[i]\n e = education[i]\n ma = marital[i]\n \n # 基础:月份分\n if m in best_months:\n base = 1.0\n elif m in worst_months:\n base = -1.0\n else:\n base = 0.0\n \n # 交互1: 最佳月份 + 退休人员 (IND_07, EXP_06)\n # 退休人员在最佳月份转化率极高 (mar: 56%, dec: 51%, sep: 46%)\n if m in best_months and j == 'retired':\n score += 2.0\n \n # 交互2: 最佳月份 + 学生 (IND_07)\n # 学生在最佳月份转化率高\n if m in best_months and j == 'student':\n score += 2.0\n \n # 交互3: 最佳月份 + 无房贷 + 无个人贷 (IND_05, IND_06)\n # 最佳月份中无财务负担的客户转化率极高\n if m in best_months and h == 'no' and l == 'no':\n score += 1.5\n \n # 交互4: 最佳月份 + 高等教育 (IND_09)\n if m in best_months and e == 'tertiary':\n score += 1.0\n \n # 交互5: 最佳月份 + 单身 (IND_08)\n if m in best_months and ma == 'single':\n score += 0.5\n \n # 交互6: 最差月份 + 蓝领 (IND_07)\n # 蓝领在最差月份转化率极低\n if m in worst_months and j == 'blue-collar':\n score -= 1.5\n \n # 交互7: 最差月份 + 有房贷 (IND_05)\n if m in worst_months and h == 'yes':\n score -= 1.0\n \n # 交互8: 最差月份 + 有个人贷 (IND_06)\n if m in worst_months and l == 'yes':\n score -= 0.5\n \n # 交互9: 最佳月份 + 正余额 (IND_11)\n if m in best_months and b > 0:\n score += 0.5\n \n # 交互10: 违约排除 (RULE_006)\n if d == 'yes':\n score -= 3.0\n \n # 交互11: 最佳月份 + 无违约 + 无房贷 + 无个人贷 + 正余额 (RULE_005)\n if m in best_months and d == 'no' and h == 'no' and l == 'no' and b > 0:\n score += 1.0\n \n scores[i] = score + base\n \n result['month_job_fin_score'] = scores\n \n return result[['row_id', 'month_job_fin_score']]\n"
57
+ },
58
+ {
59
+ "name": "age_lifecycle_maturity_score",
60
+ "dimensions": [
61
+ "客户画像"
62
+ ],
63
+ "code": "def age_lifecycle_maturity_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n age = df['age'].values\n marital = df['marital'].values\n education = df['education'].values\n job = df['job'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 基于领域知识:\n # 数据探索发现 age 与 y 呈 U 型关系:年轻人(<25)和老年人(60+)转化率高,中年人(35-55)低\n # |age-40| 与 y 的相关性(0.1247)远高于 age 本身(0.0252)\n # IND_07: 职业类型 - student和retired转化率最高\n # IND_08: 婚姻状况 - single > divorced > married\n # IND_09: 教育水平 - tertiary > secondary > primary\n # EXP_06: 年龄-职业交互 - 年轻学生和老年退休者响应方式不同\n \n for i in range(n):\n score = 0.0\n a = age[i]\n m = marital[i]\n e = education[i]\n j = job[i]\n \n # 步骤1: 年龄生命周期基础分 - U型曲线\n # 离40岁越远,基础分越高\n deviation = abs(a - 40)\n \n # 非线性映射:<25或>55为高分段,25-55为低分段\n if a < 25:\n lifecycle_base = 3.0 # 年轻群体,高转化\n elif a < 30:\n lifecycle_base = 1.5 # 25-30,中等偏高\n elif a < 35:\n lifecycle_base = 0.5 # 30-35,中等\n elif a < 55:\n lifecycle_base = 0.0 # 35-55,低谷期\n elif a < 60:\n lifecycle_base = 1.5 # 55-60,回升期\n else:\n lifecycle_base = 3.0 # 60+,高转化\n \n # 步骤2: 年龄-婚姻交互 (IND_08)\n # 年轻单身(<30): 独���决策,高转化\n if a < 30 and m == 'single':\n marital_bonus = 1.5\n # 中年已婚(30-55): 家庭决策,需协商\n elif 30 <= a < 55 and m == 'married':\n marital_bonus = -0.5\n # 老年单身(55+): 独立决策\n elif a >= 55 and m == 'single':\n marital_bonus = 1.0\n # 老年离婚(55+): 可能独立\n elif a >= 55 and m == 'divorced':\n marital_bonus = 0.5\n else:\n marital_bonus = 0.0\n \n # 步骤3: 年龄-教育交互 (IND_09)\n # 年轻+高等教育: 金融素养高\n if a < 30 and e == 'tertiary':\n edu_bonus = 1.0\n # 中年+高等教育: 收入高\n elif 30 <= a < 55 and e == 'tertiary':\n edu_bonus = 0.5\n # 老年+高等教育: 金融素养+退休规划\n elif a >= 55 and e == 'tertiary':\n edu_bonus = 1.0\n # 低教育惩罚\n elif e == 'primary':\n edu_bonus = -0.5\n else:\n edu_bonus = 0.0\n \n # 步骤4: 年龄-职业交互 (IND_07, EXP_06)\n # 年轻学生\n if a < 25 and j == 'student':\n job_bonus = 1.0\n # 老年退休\n elif a >= 55 and j == 'retired':\n job_bonus = 1.5\n # 中年蓝领 - 低谷\n elif 30 <= a < 55 and j == 'blue-collar':\n job_bonus = -1.0\n else:\n job_bonus = 0.0\n \n # 综合评分\n score = lifecycle_base + marital_bonus + edu_bonus + job_bonus\n \n scores[i] = score\n \n result['age_lifecycle_score'] = scores\n \n return result[['row_id', 'age_lifecycle_score']]\n"
64
+ },
65
+ {
66
+ "name": "balance_lifecycle_ratio",
67
+ "dimensions": [
68
+ "经济环境"
69
+ ],
70
+ "code": "def balance_lifecycle_ratio(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于领域知识:\n # IND_11: 账户余额 - 余额越高认购率越高\n # IND_07: 职业类型 - retired和student转化率最高\n # 探索数据显示:不同年龄段的余额和转化率差异巨大\n # 20-30岁: 余额均值991, 转化率17.4%\n # 30-50岁: 余额均值~1280, 转化率~9.5%\n # 50-60岁: 余额均值1687, 转化率9.3%\n # 60+岁: 余额均值~2500, 转化率~35%\n # 核心思想:相同余额在不同年龄段的含义不同\n # 年轻人余额低是正常的(积累阶段),老年人余额高是正常的(退休储蓄)\n # 因此用余额/年龄期望余额的比率更能反映经济状况\n \n age = df['age'].values\n balance = df['balance'].values\n job = df['job'].values\n \n n = len(df)\n ratios = np.zeros(n, dtype=float)\n \n # 定义不同年龄段的期望余额(基于数据探索)\n # 使用分段线性函数近似年龄-余额关系\n for i in range(n):\n a = age[i]\n b = balance[i]\n \n # 计算该年龄的期望余额(基于数据拟合)\n if a < 25:\n expected = 900.0\n elif a < 35:\n expected = 1100.0 + (a - 25) * 10.0 # 1100-1200\n elif a < 45:\n expected = 1200.0 + (a - 35) * 15.0 # 1200-1350\n elif a < 55:\n expected = 1350.0 + (a - 45) * 30.0 # 1350-1650\n elif a < 65:\n expected = 1650.0 + (a - 55) * 60.0 # 1650-2250\n else:\n expected = 2250.0 + (a - 65) * 70.0 # 2250+\n \n # 计算比率:实际余额 / 期望余额\n # 比率>1表示比同龄人经济状况好,<1表示差\n if expected > 0:\n # 使用log变换使分布更对称\n ratio = b / expected\n # 对极端值进行截断\n ratio = np.clip(ratio, -5.0, 20.0)\n ratios[i] = ratio\n else:\n ratios[i] = 0.0\n \n # 针对特殊职业调整 (IND_07)\n # student: 虽然余额不高但转化率高,说明他们的余额相对年龄更有意义\n # retired: 余额高但转化率也高,他们的余额是退休储蓄\n for i in range(n):\n if job[i] == 'student':\n # 学生通常余额低但转化意愿强,适当提升比率\n if ratios[i] > 0:\n ratios[i] *= 1.2\n elif job[i] == 'retired':\n # 退休人员余额是长期储蓄,适当提升比率\n if ratios[i] > 0:\n ratios[i] *= 1.15\n \n result['balance_lifecycle_ratio'] = ratios\n \n return result[['row_id', 'balance_lifecycle_ratio']]"
71
+ },
72
+ {
73
+ "name": "age_education_housing_profile",
74
+ "dimensions": [
75
+ "经济环境"
76
+ ],
77
+ "code": "def age_education_housing_profile(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于领域知识:\n # IND_09: 教育水平 - 高等教育正相关(tertiary 15.0%, secondary 10.6%, primary 8.6%)\n # IND_05: 无住房贷款 - housing=no 认购概率更高(16.7% vs 7.7%)\n # EXP_06: 关键特征交互 - age-job交互\n # 探索数据显示 age * education * housing 交互效应极强:\n # <30 + tertiary + no: 31.7% (年轻高学历无房贷)\n # 50+ + primary + yes: 5.0% (年长低学历有房贷)\n # 核心思想:年龄反映生命周期阶段,教育反映收入潜力,\n # 住房贷款反映财务负担,三者组合刻画完整经济画像\n \n age = df['age'].values\n education = df['education'].values\n housing = df['housing'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n for i in range(n):\n a = age[i]\n e = education[i]\n h = housing[i]\n \n # 步骤1: 年龄阶段\n if a < 30:\n age_stage = 'young'\n elif a < 50:\n age_stage = 'mid'\n else:\n age_stage = 'senior'\n \n # 步骤2: 基于 age+education+housing 的评分\n # 使用探索数据的转化率模式\n if age_stage == 'young':\n if h == 'no':\n if e == 'tertiary':\n score = 3.0 # 31.7% - 年轻高学历无房贷\n elif e == 'secondary':\n score = 2.5 # 26.7% - 年轻中等学历无房贷\n elif e == 'unknown':\n score = 3.0 # 33.1% - 年轻未知学历无房贷\n else: # primary\n score = 2.0 # 22.9% - 年轻低学历无房贷\n else: # housing == 'yes'\n if e == 'tertiary':\n score = 1.0 # 12.7%\n elif e == 'secondary':\n score = 0.5 # 8.9%\n else:\n score = 0.0 # 6.2%\n elif age_stage == 'mid':\n if h == 'no':\n if e == 'tertiary':\n score = 1.5 # 18.3%\n elif e == 'secondary':\n score = 1.0 # 11.8%\n elif e == 'unknown':\n score = 1.0 # 15.6%\n else: # primary\n score = 0.0 # 6.2%\n else: # housing == 'yes'\n score = -0.5 # 所有中年有房贷都低 (~7%)\n else: # senior\n if h == 'no':\n if e == 'tertiary':\n score = 1.5 # 19.4%\n elif e == 'secondary':\n score = 1.5 # 17.6%\n elif e == 'unknown':\n score = 1.5 # 17.5%\n else: # primary\n score = 1.0 # 16.3%\n else: # housing == 'yes'\n if e == 'tertiary':\n score = 0.5 # 8.6%\n elif e == 'secondary':\n score = 0.0 # 7.1%\n elif e == 'unknown':\n score = 0.5 # 9.9%\n else: # primary\n score = -0.5 # 5.0%\n \n scores[i] = score\n \n result['age_edu_housing'] = scores\n \n return result[['row_id', 'age_edu_housing']]"
78
+ },
79
+ {
80
+ "name": "campaign_seasonal_efficiency",
81
+ "dimensions": [
82
+ "经济环境"
83
+ ],
84
+ "code": "def campaign_seasonal_efficiency(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n month = df['month'].values\n campaign = df['campaign'].values\n previous = df['previous'].values\n poutcome = df['poutcome'].values\n day = df['day'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 最佳月份和最差月份 (IND_04, RULE_003, EXP_08)\n best_months = {'mar', 'sep', 'oct', 'dec'}\n worst_months = {'may', 'jul'}\n \n for i in range(n):\n score = 0.0\n m = month[i]\n c = campaign[i]\n p = previous[i]\n po = poutcome[i]\n d = day[i]\n \n # 步骤1: 月份基础分 (IND_04, RULE_003, EXP_08)\n # 3月(税季)、9-10月(财年末)、12月(年终奖)最佳\n if m in best_months:\n score += 2.0\n elif m in {'apr', 'jun', 'nov'}:\n score += 0.5 # 中等月份\n elif m in {'jan', 'feb', 'aug'}:\n score += 0.0 # 一般月份\n else: # may, jul - 最差\n score -= 1.0 # 5月过度饱和,7月度假季\n \n # 步骤2: 联系次数效率 (RULE_001, IND_12)\n # campaign<=3 最优,超过后递减\n if c <= 2:\n score += 1.5 # 极少联系,高效\n elif c <= 3:\n score += 0.5 # 最优范围内\n elif c <= 5:\n score -= 0.5 # 超过最优\n else:\n score -= 1.5 # 过度联系\n \n # 步骤3: 交互 - 最佳月份+少联系 (协同效应)\n if m in best_months and c <= 2:\n score += 2.0 # 最佳时机+最少打扰=最高效\n elif m in best_months and c <= 3:\n score += 1.0\n \n # 步骤4: 交互 - 最差月份+多联系 (负协同)\n if m in worst_months and c > 3:\n score -= 1.0\n \n # 步骤5: 历史成功加成 (IND_01)\n if po == 'success':\n score += 2.0\n \n # 步骤6: 历史联系过但未成功 - 中等信号 (IND_12)\n if p > 0 and po != 'success':\n score += 0.5\n \n # 步骤7: 月初联系效率 (day <= 10 通常更有效)\n if d <= 10 and m in best_months:\n score += 0.5\n \n scores[i] = score\n \n result['campaign_seasonal_eff'] = scores\n \n return result[['row_id', 'campaign_seasonal_eff']]"
85
+ },
86
+ {
87
+ "name": "job_education_economic_status",
88
+ "dimensions": [
89
+ "经济环境"
90
+ ],
91
+ "code": "def job_education_economic_status(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n job = df['job'].values\n education = df['education'].values\n marital = df['marital'].values\n default = df['default'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 步骤1: 基于领域知识计算 job 的经济地位分 (IND_07)\n # student(28.7%)和retired(22.8%)最高,blue-collar(7.3%)最低\n job_scores_map = {\n 'student': 3.0,\n 'retired': 2.5,\n 'unemployed': 1.5,\n 'management': 1.5,\n 'admin.': 1.0,\n 'self-employed': 1.0,\n 'unknown': 1.0,\n 'technician': 1.0,\n 'services': 0.5,\n 'housemaid': 0.5,\n 'entrepreneur': 0.5,\n 'blue-collar': 0.0\n }\n \n # 步骤2: 基于领域知识计算 education 的经济地位分 (IND_09)\n # tertiary(15.0%) > secondary(10.6%) > primary(8.6%)\n edu_scores_map = {\n 'tertiary': 2.0,\n 'secondary': 1.0,\n 'unknown': 1.0,\n 'primary': 0.0\n }\n \n # 步骤3: 基于领域知识计算 marital 的经济独立分 (IND_08)\n # single > divorced > married\n marital_scores_map = {\n 'single': 1.0,\n 'divorced': 0.5,\n 'married': 0.0\n }\n \n for i in range(n):\n score = 0.0\n j = job[i]\n e = education[i]\n m = marital[i]\n d = default[i]\n \n # 职业经济地位 (IND_07)\n score += job_scores_map.get(j, 0.0)\n \n # 教育经济地位 (IND_09)\n score += edu_scores_map.get(e, 0.0)\n \n # 婚姻经济独立 (IND_08)\n score += marital_scores_map.get(m, 0.0)\n \n # 违约惩罚 (IND_10, RULE_006)\n if d == 'yes':\n score -= 3.0\n \n # 交互增强: 高转化职业+高等教育 (协同效应)\n if j in ['student', 'retired', 'management'] and e == 'tertiary':\n score += 1.0\n \n # 交互增强: 学生+单身 (独立决策)\n if j == 'student' and m == 'single':\n score += 1.0\n \n # 交互增强: 退休+高等教育 (高金融素养退休人员)\n if j == 'retired' and e == 'tertiary':\n score += 1.0\n \n # 交互惩罚: 蓝领+低教育 (经济困难)\n if j == 'blue-collar' and e == 'primary':\n score -= 1.0\n \n scores[i] = score\n \n result['job_edu_econ_status'] = scores\n \n return result[['row_id', 'job_edu_econ_status']]"
92
+ },
93
+ {
94
+ "name": "month_previous_breakthrough",
95
+ "dimensions": [
96
+ "时机因素"
97
+ ],
98
+ "code": "def month_previous_breakthrough(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n month = df['month'].values\n previous = df['previous'].values\n poutcome = df['poutcome'].values\n campaign = df['campaign'].values\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n # 月份分类 (IND_04, RULE_003, EXP_08)\n best_months = {'mar', 'sep', 'oct', 'dec'}\n worst_months = {'may', 'jul'}\n mid_months = {'apr', 'jun', 'nov'}\n normal_months = {'jan', 'feb', 'aug'}\n \n for i in range(n):\n score = 0.0\n m = month[i]\n p = previous[i]\n po = poutcome[i]\n c = campaign[i]\n \n # 基础月份分\n if m in best_months:\n base = 2.0\n elif m in mid_months:\n base = 0.5\n elif m in normal_months:\n base = 0.0\n else: # worst\n base = -1.0\n \n # 突破效应:最差月份中,有历史联系的客户是突破口\n if m in worst_months and p > 0:\n # 淡季突破效应:有历史联系的客户转化率远高于平均水平\n score += 3.0 # 突破加分\n if po == 'success':\n score += 2.0 # 历史成功更是黄金\n elif po == 'failure':\n score += 0.5 # 历史失败但仍有联系\n # campaign<=3 效果更好\n if c <= 3:\n score += 0.5\n elif m in worst_months:\n # 最差月份,无历史联系 - 低分\n score -= 0.5\n \n # 最佳月��中,历史联系强化\n if m in best_months:\n if p > 0:\n score += 1.5 # 旺季+历史联系\n if po == 'success':\n score += 1.5 # 历史成功客户在旺季几乎必买\n else:\n score += 0.5 # 旺季即使无历史联系也不错\n \n # 中等月份\n if m in mid_months or m in normal_months:\n if p > 0:\n score += 1.0\n if po == 'success':\n score += 1.0\n \n # 加上月份基础分\n score += base\n \n scores[i] = score\n \n result['month_prev_breakthrough'] = scores\n \n return result[['row_id', 'month_prev_breakthrough']]"
99
+ },
100
+ {
101
+ "name": "month_distance_to_peak",
102
+ "dimensions": [
103
+ "时机因素"
104
+ ],
105
+ "code": "def month_distance_to_peak(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n month = df['month'].values\n \n # 月份映射 (IND_04, RULE_003, EXP_08)\n month_map = {'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6, \n 'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12}\n \n # 最佳月份 (IND_04: mar, sep, oct, dec 转化率最高)\n peak_months = np.array([3, 9, 10, 12])\n \n n = len(df)\n scores = np.zeros(n, dtype=float)\n \n for i in range(n):\n m = month_map.get(month[i], 0)\n \n # 计算到最近最佳月份的循环距离\n distances = []\n for p in peak_months:\n d = abs(m - p)\n d = min(d, 12 - d) # 循环距离(跨年)\n distances.append(d)\n \n min_dist = min(distances)\n \n # 将距离映射为评分 (基于数据探索的转化率)\n if min_dist == 0:\n score = 3.0 # 最佳月份: ~46.8%\n elif min_dist == 1:\n score = 1.0 # 距离1: ~12.7%\n elif min_dist == 2:\n score = 0.0 # 距离2: ~7.7%\n else: # min_dist == 3\n score = -0.5 # 距离3: ~10.2% (jun)\n \n scores[i] = score\n \n result['month_dist_to_peak'] = scores\n \n return result[['row_id', 'month_dist_to_peak']]"
106
+ }
107
+ ]
outputs/features/knowfeat_ablation/bank_marketing_expert_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:841e9d4cd44271cc1e71ce14536fc944f63cb5afb07a0e2fc117f21a9ae145d1
3
+ size 4266249
outputs/features/knowfeat_ablation/bank_marketing_indicators_generic_features.json ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "premium_profile_score",
4
+ "dimensions": [
5
+ "客户画像"
6
+ ],
7
+ "code": "def feature_premium_profile_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 基础画像因子 - 每个因子贡献1分\n # 因子1: 职业 - student(0.287) 或 retired(0.228) 高转化职业\n score_job = df['job'].isin(['student', 'retired']).astype(int)\n \n # 因子2: 婚姻 - single(0.149) 高于其他\n score_marital = (df['marital'] == 'single').astype(int)\n \n # 因子3: 教育 - tertiary(0.150) 最高\n score_education = (df['education'] == 'tertiary').astype(int)\n \n # 因子4: 无住房贷款 - housing=no (0.167 vs 0.077)\n score_no_housing = (df['housing'] == 'no').astype(int)\n \n # 因子5: 无个人贷款 - loan=no (0.127 vs 0.067)\n score_no_loan = (df['loan'] == 'no').astype(int)\n \n # 因子6: 无违约 - default=no (0.118 vs 0.064)\n score_no_default = (df['default'] == 'no').astype(int)\n \n # 因子7: 正余额 - balance > 0\n score_pos_balance = (df['balance'] > 0).astype(int)\n \n # 因子8: 年龄 - 60+ (0.423) 或 18-25 (0.240) 高转化年龄段\n score_age = ((df['age'] >= 60) | (df['age'] <= 25)).astype(int)\n \n # 步骤2: 加权求和 - 根据转化率差异赋予不同权重\n # 权重基于各因子正负类差异倍数\n weights = {\n 'job': 2.0, # student/retired vs blue-collar 差异约4x\n 'marital': 1.0, # single vs married 差异约1.5x\n 'education': 1.5, # tertiary vs primary 差异约1.7x\n 'no_housing': 2.0, # no vs yes 差异约2.2x\n 'no_loan': 1.5, # no vs yes 差异约1.9x\n 'no_default': 1.0, # no vs yes 差异约1.8x\n 'pos_balance': 1.0,# 正余额 vs 负余额\n 'age': 2.0 # 60+/<25 vs 其他 差异约3-4x\n }\n \n result['premium_profile_score'] = (\n score_job * weights['job'] +\n score_marital * weights['marital'] +\n score_education * weights['education'] +\n score_no_housing * weights['no_housing'] +\n score_no_loan * weights['no_loan'] +\n score_no_default * weights['no_default'] +\n score_pos_balance * weights['pos_balance'] +\n score_age * weights['age']\n )\n \n return result\n"
8
+ },
9
+ {
10
+ "name": "age_job_marital_risk_score",
11
+ "dimensions": [
12
+ "客户画像"
13
+ ],
14
+ "code": "def feature_age_job_marital_risk_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 年龄分段 - 基于数据探索的转化率模式\n # 60+ (0.423), 18-25 (0.240), 25-30 (0.145), 30-40 (0.102), 40-50 (0.091), 50-60 (0.101)\n def age_score(age):\n if age >= 60:\n return 3 # 最高转化\n elif age <= 25:\n return 2 # 高转化\n elif age <= 30:\n return 1 # 中等偏高\n elif age <= 40:\n return 0 # 中等\n elif age <= 60:\n return 0 # 中等偏低\n else:\n return 0\n \n result['age_score'] = df['age'].apply(age_score)\n \n # 步骤2: 职业评分 - 基于IND_07\n # student(0.287), retired(0.228), unemployed(0.155), management(0.138)\n # admin.(0.122), self-employed(0.118), technician(0.111), services(0.089)\n # housemaid(0.088), entrepreneur(0.083), blue-collar(0.073)\n job_score_map = {\n 'student': 3,\n 'retired': 3,\n 'unemployed': 2,\n 'management': 1,\n 'admin.': 1,\n 'self-employed': 1,\n 'technician': 1,\n 'unknown': 1,\n 'services': 0,\n 'housemaid': 0,\n 'entrepreneur': 0,\n 'blue-collar': 0\n }\n result['job_score'] = df['job'].map(job_score_map).fillna(0)\n \n # 步骤3: 婚姻评分 - 基于IND_08\n # single(0.149) > divorced(0.119) > married(0.101)\n marital_score_map = {\n 'single': 2,\n 'divorced': 1,\n 'married': 0\n }\n result['marital_score'] = df['marital'].map(marital_score_map).fillna(0)\n \n # 步骤4: 教育评分 - 基于IND_09\n # tertiary(0.150) > unknown(0.136) > secondary(0.106) > primary(0.086)\n edu_score_map = {\n 'tertiary': 2,\n 'unknown': 1,\n 'secondary': 1,\n 'primary': 0\n }\n result['edu_score'] = df['education'].map(edu_score_map).fillna(0)\n \n # 步骤5: 年龄-职业交互增强 - 基于EXP_06\n # 年轻学生(age<=25 & student): 极高转化\n # 老年退休(age>=55 & retired): 极高转化\n # 年轻单身(age<=30 & single): 高转化\n # 老年已婚(age>=60 & married): 高转化(老年已婚转化率0.417)\n interaction_boost = np.zeros(len(df))\n \n # 年轻学生: age<=25 & student\n interaction_boost += ((df['age'] <= 25) & (df['job'] == 'student')).astype(int) * 2\n \n # 老年退休: age>=55 & retired\n interaction_boost += ((df['age'] >= 55) & (df['job'] == 'retired')).astype(int) * 2\n \n # 年轻单身: age<=30 & single\n interaction_boost += ((df['age'] <= 30) & (df['marital'] == 'single')).astype(int) * 1\n \n # 老年已婚: age>=60 & married (老年已婚转化率0.417)\n interaction_boost += ((df['age'] >= 60) & (df['marital'] == 'married')).astype(int) * 1\n \n # 年轻高教育: age<=30 & tertiary\n interaction_boost += ((df['age'] <= 30) & (df['education'] == 'tertiary')).astype(int) * 1\n \n result['interaction_boost'] = interaction_boost\n \n # 步骤6: 综合评分 = 各维度评分之和 + 交互增强\n result['age_job_marital_risk_score'] = (\n result['age_score'] + \n result['job_score'] + \n result['marital_score'] + \n result['edu_score'] + \n result['interaction_boost']\n )\n \n # 删除中间列\n result = result[['row_id', 'age_job_marital_risk_score']]\n \n return result\n"
15
+ },
16
+ {
17
+ "name": "financial_health_index",
18
+ "dimensions": [
19
+ "客户画像"
20
+ ],
21
+ "code": "def feature_financial_health_index(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 计算财务负担得分 (负向指标)\n # 有住房贷款: -1分 (IND_05: housing=yes 转化率0.077 vs no 0.167)\n # 有个人贷款: -1分 (IND_06: loan=yes 转化率0.067 vs no 0.127)\n # 有信用违约: -2分 (IND_10: default=yes 转化率0.064 vs no 0.118)\n burden_score = (\n (df['housing'] == 'yes').astype(int) * (-1) +\n (df['loan'] == 'yes').astype(int) * (-1) +\n (df['default'] == 'yes').astype(int) * (-2)\n )\n \n # 步骤2: 计算余额得分 (正向指标)\n # IND_11: 余额越高认购率越高\n # 基于分位数分段: Q1(0.070), Q2(0.100), Q3(0.117), Q4(0.135), Q5(0.164)\n # 负余额: -1, 零余额: 0, 正余额按分位数分段\n balance_conditions = [\n (df['balance'] < 0), # 负余额\n (df['balance'] == 0), # 零余额\n (df['balance'] > 0) & (df['balance'] <= df['balance'].quantile(0.25)), # Q1正余额\n (df['balance'] > df['balance'].quantile(0.25)) & (df['balance'] <= df['balance'].quantile(0.5)), # Q2\n (df['balance'] > df['balance'].quantile(0.5)) & (df['balance'] <= df['balance'].quantile(0.75)), # Q3\n (df['balance'] > df['balance'].quantile(0.75)) # Q4 (top 25%)\n ]\n balance_scores = [-1, 0, 1, 2, 3, 4]\n balance_score = np.select(balance_conditions, balance_scores, default=0)\n \n # 步骤3: 计算财务健康指数\n # 基础分 = 5 (使结果非负)\n # 财务健康指数 = 5 + burden_score + balance_score\n # 范围: 5 + (-4) + (-1) = 0 到 5 + 0 + 4 = 9\n result['financial_health_index'] = 5 + burden_score + balance_score\n \n # 步骤4: 添加非线性增强 - 高余额+无负担的客户获得额外加分\n # RULE_005: 无住房贷款+无个人贷款+正余额+无违约 = 高优先级\n high_quality = (\n (df['housing'] == 'no') & \n (df['loan'] == 'no') & \n (df['balance'] > 0) & \n (df['default'] == 'no')\n ).astype(int)\n \n # 余额越高,额外加分越多\n balance_percentile = df['balance'].rank(pct=True)\n extra_boost = high_quality * (balance_percentile * 2).round(0)\n \n result['financial_health_index'] = result['financial_health_index'] + extra_boost\n \n return result[['row_id', 'financial_health_index']]\n"
22
+ },
23
+ {
24
+ "name": "poutcome_campaign_interaction",
25
+ "dimensions": [
26
+ "联系记录"
27
+ ],
28
+ "code": "def feature_poutcome_campaign_interaction(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 对poutcome进行数值编码\n # IND_01: poutcome=success 转化率>60%, unknown ~6%, failure更低\n # 基于实际转化率: success=0.647, other=0.167, failure=0.126, unknown=0.092\n poutcome_score_map = {\n 'success': 3,\n 'other': 1,\n 'failure': 0,\n 'unknown': 0\n }\n poutcome_score = df['poutcome'].map(poutcome_score_map).fillna(0)\n \n # 步骤2: 对campaign进行编码\n # RULE_001: campaign<=3最优,>3后转化率急剧下降\n # 数据: campaign<=3转化率0.129, >3转化率0.074\n campaign_score = np.where(df['campaign'] <= 3, 1, \n np.where(df['campaign'] <= 5, 0, -1))\n \n # 步骤3: 交互特征 = poutcome_score * (1 + campaign_score)\n # 当poutcome=success且campaign<=3时,得分最高(3*2=6)\n # 当poutcome=unknown且campaign>5时,得分为0\n result['poutcome_campaign_interaction'] = poutcome_score * (1 + campaign_score)\n \n return result\n"
29
+ },
30
+ {
31
+ "name": "contact_saturation_risk",
32
+ "dimensions": [
33
+ "联系记录"
34
+ ],
35
+ "code": "def feature_contact_saturation_risk(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # ��骤1: 计算当月联系饱和度\n # RULE_010: 月联系量超过5000后预期递减回报\n # 计算每个月的总联系量\n month_volume = df.groupby('month')['row_id'].transform('count')\n \n # 步骤2: 计算饱和风险分数\n # 高联系量月份(>5000)的客户面临过度饱和风险\n # 结合campaign次数 - 在饱和月份被多次联系的客户风险最高\n saturation_risk = np.where(month_volume > 5000, 1, 0)\n \n # 步骤3: 结合campaign次数\n # campaign>3的客户在饱和月份风险加倍\n high_campaign = (df['campaign'] > 3).astype(int)\n \n # 步骤4: 结合月份季节性\n # IND_04: 5月联系量最大(13769)但转化率最低(6.4%)\n # 在低转化月份被多次联系 = 高风险\n low_conv_months = ['may', 'jun', 'jul', 'aug']\n bad_month = df['month'].isin(low_conv_months).astype(int)\n \n # 综合风险分 = 饱和月份基础分 + 多次联系加成 + 低转化月份加成\n result['contact_saturation_risk'] = (\n saturation_risk * 1.0 +\n high_campaign * 1.5 +\n bad_month * 1.0\n )\n \n return result\n"
36
+ },
37
+ {
38
+ "name": "contact_channel_quality",
39
+ "dimensions": [
40
+ "联系记录"
41
+ ],
42
+ "code": "def feature_contact_channel_quality(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 联系方式基础评分\n # IND_03: cellular转化率~15%, telephone~5%, unknown~4%\n # EXP_02: 手机联系意味着银行有客户个人手机号(已有关系)\n contact_score_map = {\n 'cellular': 2,\n 'telephone': 1,\n 'unknown': 0\n }\n contact_score = df['contact'].map(contact_score_map).fillna(0)\n \n # 步骤2: 结合poutcome增强\n # 如果poutcome=success且contact=cellular,质量最高\n # 数据: cellular+success转化率0.650\n poutcome_success = (df['poutcome'] == 'success').astype(int)\n \n # 步骤3: 结合previous增强\n # 有之前联系记录+手机联系 = 已建立关系的客户\n prev_contacted = (df['previous'] > 0).astype(int)\n \n # 综合质量分 = 基础分 + success加成 + 历史联系加成\n result['contact_channel_quality'] = (\n contact_score +\n poutcome_success * 2.0 +\n prev_contacted * 0.5\n )\n \n return result\n"
43
+ },
44
+ {
45
+ "name": "economic_contact_efficiency",
46
+ "dimensions": [
47
+ "经济环境"
48
+ ],
49
+ "code": "def feature_economic_contact_efficiency(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 经济活跃月份判定 (基于EXP_08和IND_04)\n # 税季(3月): 转化率51.99%\n # 财年末(9-10月): 转化率46.46%, 43.77%\n # 年终奖(12月): 转化率46.73%\n # 这些月份联系效率最高\n prime_months = df['month'].isin(['mar', 'sep', 'oct', 'dec']).astype(int)\n \n # 步骤2: 联系次数效率 (基于RULE_001和IND_12)\n # campaign<=3最优,>3后转化率急剧下降\n # 在经济活跃月份,campaign=1-3的转化率46-55%\n # 在经济不活跃月份,campaign=1-3的转化率仅8-10%\n efficient_campaign = (df['campaign'] <= 3).astype(int)\n \n # 步骤3: 历史联系信号 (基于IND_01和EXP_05)\n # 之前成功认购的客户在任何月份都有高转化率\n # 从未被联系过的客户在经济活跃月份也有高转化率(38-51%)\n prev_success = (df['poutcome'] == 'success').astype(int)\n never_contacted = (df['pdays'] == -1).astype(int)\n \n # 步骤4: 构建经济联系效率特征\n # 核心逻辑: 在经济活跃月份,联系效率最高,尤其是首次联系或少量联系\n # 使用条件组合而非线性加权\n \n # 情况1: 经济活跃月份 + 高效联系(<=3次) = 最高效率\n # 情况2: 经济活跃月份 + 低效联系(>3次) = 中等效率\n # 情况3: 经济不活跃月份 + 历史成功 = 中等效率\n # 情况4: 经济不活跃月份 + 从未联系 = 低效率\n # 情况5: 经济不活跃月份 + 多次联系 = 最低效率\n \n # 使用条件赋值避免线性加权\n conditions = [\n (prime_months == 1) & (efficient_campaign == 1) & (prev_success == 1), # 好月份+高效+历史成功\n (prime_months == 1) & (efficient_campaign == 1), # 好月份+高效\n (prime_months == 1) & (efficient_campaign == 0), # 好月份+低效\n (prime_months == 0) & (prev_success == 1), # 差月份+历史成功\n (prime_months == 0) & (never_contacted == 1) & (efficient_campaign == 1),# 差月份+从未联系+高效\n (prime_months == 0) & (never_contacted == 1) & (efficient_campaign == 0),# 差月份+从未联系+低效\n (prime_months == 0) & (never_contacted == 0) & (efficient_campaign == 1),# 差月份+曾联系+高效\n ]\n scores = [5, 4, 3, 3, 2, 1, 1]\n default_score = 0 # 差月份+曾联系+低效\n \n result['economic_contact_efficiency'] = np.select(conditions, scores, default=default_score)\n \n return result\n"
50
+ },
51
+ {
52
+ "name": "seasonal_timing_score",
53
+ "dimensions": [
54
+ "时机因素"
55
+ ],
56
+ "code": "def feature_seasonal_timing_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 月份基础评分 - 基于IND_04和RULE_003\n # 高转化月份: mar(0.520), dec(0.467), sep(0.465), oct(0.438)\n # 中转化月份: apr(0.197), fe(0.166)\n # 低转化月份: aug(0.110), jun(0.102), nov(0.102), jan(0.101), jul(0.091), may(0.067)\n month_score_map = {\n 'mar': 4, # 税季 - 最高转化\n 'dec': 3, # 年终奖\n 'sep': 3, # 财年末\n 'oct': 3, # 财年末\n 'apr': 2, # 次高\n 'fe': 2, # 次高\n 'aug': 1, # 低转化\n 'jun': 1,\n 'nov': 1,\n 'jan': 1,\n 'jul': 1,\n 'may': 0 # 最低转化\n }\n month_score = df['month'].map(month_score_map).fillna(0)\n \n # 步骤2: day评分 - 基于数据探索\n # 月初(1-5)和月中(11-15)转化率较高\n # 在高转化月份中,21-25日转化率最高(0.584)\n day_score = np.select(\n [\n (df['day'] >= 1) & (df['day'] <= 5),\n (df['day'] >= 6) & (df['day'] <= 10),\n (df['day'] >= 11) & (df['day'] <= 15),\n (df['day'] >= 16) & (df['day'] <= 20),\n (df['day'] >= 21) & (df['day'] <= 25),\n (df['day'] >= 26) & (df['day'] <= 31)\n ],\n [2, 1, 2, 1, 2, 1],\n default=0\n )\n \n # 步骤3: 季节性交互增强 - EXP_08\n # 高转化月份中,21-25日转化率0.584,是黄金窗口\n # 低转化月份中,月初稍好\n is_high_month = df['month'].isin(['mar', 'sep', 'oct', 'dec']).astype(int)\n is_mid_month = df['month'].isin(['apr', 'fe']).astype(int)\n \n # 在高转化月份,21-25日获得额外加分\n golden_window = (is_high_month == 1) & (df['day'] >= 21) & (df['day'] <= 25)\n early_month_boost = (is_mid_month == 1) & (df['day'] >= 1) & (df['day'] <= 10)\n \n interaction_boost = golden_window.astype(int) * 2 + early_month_boost.astype(int) * 1\n \n # 步骤4: 综合评分\n result['seasonal_timing_score'] = month_score + day_score + interaction_boost\n \n return result\n"
57
+ },
58
+ {
59
+ "name": "pdays_recency_score",
60
+ "dimensions": [
61
+ "时机因素"
62
+ ],
63
+ "code": "def feature_pdays_recency_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 处理pdays编码 - RULE_007和EXP_05\n # pdays=-1表示从未被联系过(82%数据),应拆分为二元指标\n was_previously_contacted = (df['pdays'] != -1).astype(int)\n \n # 步骤2: 对pdays>0的客户计算近期度评分\n pdays_pos = df['pdays'].values\n \n # 初始化recency_score\n recency_score = np.zeros(len(df))\n \n # 最佳窗口: 31-90天 (转化率0.421)\n mask_31_90 = (pdays_pos > 30) & (pdays_pos <= 90)\n mask_91_180 = (pdays_pos > 90) & (pdays_pos <= 180)\n mask_181_365 = (pdays_pos > 180) & (pdays_pos <= 365)\n mask_366_plus = (pdays_pos > 365)\n mask_0_30 = (pdays_pos > 0) & (pdays_pos <= 30)\n \n recency_score[mask_31_90] = 4\n recency_score[mask_91_180] = 3\n recency_score[mask_366_plus] = 3\n recency_score[mask_181_365] = 2\n recency_score[mask_0_30] = 1\n # pdays=-1 保持为0\n \n # 步骤3: 结合previous次数增强\n previous_score = np.zeros(len(df))\n previous_score[df['previous'] == 0] = 0\n previous_score[(df['previous'] > 0) & (df['previous'] <= 2)] = 1\n previous_score[(df['previous'] > 2) & (df['previous'] <= 5)] = 2\n previous_score[df['previous'] > 5] = 3\n \n # 步骤4: 结合poutcome增强 - IND_01\n poutcome_boost = (df['poutcome'] == 'success').astype(int) * 3\n \n # 步骤5: 综合评分\n result['pdays_recency_score'] = (\n was_previously_contacted + \n recency_score + \n previous_score + \n poutcome_boost\n )\n \n return result\n"
64
+ },
65
+ {
66
+ "name": "life_stage_segment",
67
+ "dimensions": [
68
+ "客户画像"
69
+ ],
70
+ "code": "def feature_life_stage_segment(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 定义生命周期阶段评分\n # 基于年龄、婚姻、职业、教育、房贷的综合判断\n \n # 阶段1: 年轻学生/刚入职 (age<=25, student/ unemployed)\n # 转化率: 0.240-0.287\n is_young_student = (df['age'] <= 25) & (df['job'].isin(['student', 'unemployed']))\n \n # 阶段2: 年轻单身无负担 (age<=30, single, housing=no, loan=no)\n # 转化率: ~0.16-0.29\n is_young_single_free = (df['age'] <= 30) & (df['marital'] == 'single') & (df['housing'] == 'no') & (df['loan'] == 'no')\n \n # 阶段3: 年轻家庭 (age<=35, married, housing=yes)\n # 转化率: ~0.07-0.14\n is_young_family = (df['age'] <= 35) & (df['marital'] == 'married') & (df['housing'] == 'yes')\n \n # 阶段4: 中年稳定 (age 30-50, married, housing=no, job in management/admin/technician)\n # 转化率: ~0.10-0.13\n is_mid_stable = (df['age'] >= 30) & (df['age'] <= 50) & (df['housing'] == 'no') & (df['job'].isin(['management', 'admin.', 'technician', 'self-employed']))\n \n # 阶段5: 中年负担 (age 30-50, housing=yes, loan=yes)\n # 转化率: 很低\n is_mid_burden = (df['age'] >= 30) & (df['age'] <= 50) & (df['housing'] == 'yes') & (df['loan'] == 'yes')\n \n # 阶段6: 中年单身/离异 (age 35-55, single/divorced)\n # 转化率: ~0.10-0.14\n is_mid_single = (df['age'] >= 35) & (df['age'] <= 55) & (df['marital'].isin(['single', 'divorced']))\n \n # 阶段7: 临近退休 (age 50-60, job in management/admin/technician)\n # 转化率: ~0.10-0.17\n is_pre_retire = (df['age'] >= 50) & (df['age'] < 60) & (df['job'].isin(['management', 'admin.', 'technician', 'self-employed']))\n \n # 阶段8: 退休人员 (age>=55, retired)\n # 转化率: 0.228-0.256\n is_retired = (df['age'] >= 55) & (df['job'] == 'retired')\n \n # 阶段9: 老年无负担 (age>=60, housing=no, loan=no)\n # 转化率: 0.412-0.473\n is_elderly_free = (df['age'] >= 60) & (df['housing'] == 'no') & (df['loan'] == 'no')\n \n # 阶段10: 老年有负担 (age>=60, housing=yes)\n # 转化率: 0.448\n is_elderly_burden = (df['age'] >= 60) & (df['housing'] == 'yes')\n \n # 为每个阶段分配评分 (基于转化率排序)\n # 阶段9(老年无负担): 10分, 阶段10(老年有负担): 9分\n # 阶段1(年轻学生): 8分, 阶段8(退休): 8分\n # 阶段2(年轻单身无负担): 7分\n # 阶段6(中年单身/离异): 5分, 阶段4(中年稳定): 5分\n # 阶段7(临近退休): 4分\n # 阶段3(年轻家庭): 3分\n # 阶段5(中年负担): 1分\n # 默认(其他): 2分\n \n conditions = [\n is_elderly_free,\n is_elderly_burden,\n is_young_student,\n is_retired,\n is_young_single_free,\n is_mid_single,\n is_mid_stable,\n is_pre_retire,\n is_young_family,\n is_mid_burden\n ]\n \n scores = [10, 9, 8, 8, 7, 5, 5, 4, 3, 1]\n \n result['life_stage_segment'] = np.select(conditions, scores, default=2)\n \n return result[['row_id', 'life_stage_segment']]\n"
71
+ },
72
+ {
73
+ "name": "contact_fatigue_score",
74
+ "dimensions": [
75
+ "联系记录"
76
+ ],
77
+ "code": "def feature_contact_fatigue_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 基于campaign计算基础疲劳度 (RULE_001, IND_12)\n # campaign=1: 首次联系,无疲劳 -> 0\n # campaign=2: 二次联系,轻度疲劳 -> 1\n # campaign=3: 三次联系,中度疲劳 -> 2 (RULE_001: 最优上限)\n # campaign=4-5: 过度联系,高度疲劳 -> 3\n # campaign=6-10: 严重疲劳 -> 4\n # campaign>10: 极度疲劳 -> 5\n campaign_conditions = [\n (df['campaign'] == 1),\n (df['campaign'] == 2),\n (df['campaign'] == 3),\n (df['campaign'] >= 4) & (df['campaign'] <= 5),\n (df['campaign'] >= 6) & (df['campaign'] <= 10),\n (df['campaign'] > 10)\n ]\n fatigue_scores = [0, 1, 2, 3, 4, 5]\n base_fatigue = np.select(campaign_conditions, fatigue_scores, default=0)\n \n # 步骤2: 基于poutcome调整疲劳度 (IND_01)\n # poutcome=success: 历史成功,即使多次联系也不疲劳 -> 疲劳度减半\n # poutcome=unknown: 从未联系过,疲劳度不变\n # poutcome=failure/other: 历史失败,疲劳度加重\n poutcome_adjust = np.select(\n [\n (df['poutcome'] == 'success'),\n (df['poutcome'] == 'unknown'),\n (df['poutcome'] == 'failure'),\n (df['poutcome'] == 'other')\n ],\n [-2, 0, 1, 0],\n default=0\n )\n \n # 步骤3: 综合疲劳度 = base_fatigue + poutcome_adjust\n # 确保非负\n fatigue = base_fatigue + poutcome_adjust\n fatigue = np.maximum(fatigue, 0)\n \n # 步骤4: 非线性变换 - 疲劳度越高,转化率下降越剧烈\n # 使用平方变换放大高疲劳度的惩罚效果\n result['contact_fatigue_score'] = fatigue ** 2\n \n return result\n"
78
+ },
79
+ {
80
+ "name": "seasonal_financial_capacity",
81
+ "dimensions": [
82
+ "时机因素",
83
+ "客户画像"
84
+ ],
85
+ "code": "def feature_seasonal_financial_capacity(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 月份季节性评分 (IND_04, EXP_08)\n prime_months = df['month'].isin(['mar', 'sep', 'oct', 'dec']).astype(int)\n mid_months = df['month'].isin(['apr', 'fe']).astype(int)\n \n # 步骤2: 财务自由度 (基于IND_05, IND_06, RULE_005)\n # free: 无房贷+无贷款 = 最高财务自由度\n # housing_only: 有房贷无贷款 = 中等\n # loan_only: 无房贷有贷款 = 中低\n # both: 有房贷+有贷款 = 最低\n financial_free = ((df['housing'] == 'no') & (df['loan'] == 'no')).astype(int)\n housing_only = ((df['housing'] == 'yes') & (df['loan'] == 'no')).astype(int)\n loan_only = ((df['housing'] == 'no') & (df['loan'] == 'yes')).astype(int)\n both_loans = ((df['housing'] == 'yes') & (df['loan'] == 'yes')).astype(int)\n \n # 步骤3: 余额水平 (IND_11)\n # 正余额增强财务能力\n pos_balance = (df['balance'] > 0).astype(int)\n high_balance = (df['balance'] > df['balance'].median()).astype(int)\n \n # 步骤4: 无违约 (IND_10)\n no_default = (df['default'] == 'no').astype(int)\n \n # 步骤5: 构建季节性-财务能力评分\n # 核心洞察: 在prime月份,财务自由的客户转化率极高(mar+free=53.4%)\n # 在low月份,即使财务自由转化率也低(jun+free=12.5%)\n # 数据验证:\n # - prime + free: mar=53.4%, dec=47.9%, sep=47.5%, oct=44.1% (平均~48%)\n # - prime + housing_only: mar=49.5%, dec=47.2%, sep=46.0%, oct=43.9% (平均~47%)\n # - low + free: may=15.0%, jun=12.5%, jul=13.5%, aug=11.2% (平均~13%)\n # - low + housing_only: jun=8.1%, jul=7.7%, aug=13.8% (平均~10%)\n \n # 条件1: prime months + free + 正余额 + 无违约 = 最高分\n cond1 = (prime_months == 1) & (financial_free == 1) & (pos_balance == 1) & (no_default == 1)\n \n # 条件2: prime months + free = 高分\n cond2 = (prime_months == 1) & (financial_free == 1)\n \n # 条件3: prime months + housing_only = 中高分\n cond3 = (prime_months == 1) & (housing_only == 1)\n \n # 条件4: mid months + free + 正余额 = 中分\n cond4 = (mid_months == 1) & (financial_free == 1) & (pos_balance == 1)\n \n # 条件5: mid months + free = 中低分\n cond5 = (mid_months == 1) & (financial_free == 1)\n \n # 条件6: low months + free + 高余额 = 低分\n cond6 = (~prime_months.astype(bool)) & (~mid_months.astype(bool)) & (financial_free == 1) & (high_balance == 1)\n \n # 条件7: low months + free = 最低分\n cond7 = (~prime_months.astype(bool)) & (~mid_months.astype(bool)) & (financial_free == 1)\n \n conditions = [cond1, cond2, cond3, cond4, cond5, cond6, cond7]\n scores = [6, 5, 4, 3, 2, 1, 0]\n \n result['seasonal_financial_capacity'] = np.select(conditions, scores, default=0)\n \n return result\n"
86
+ },
87
+ {
88
+ "name": "job_age_balance_lifecycle",
89
+ "dimensions": [
90
+ "客户画像"
91
+ ],
92
+ "code": "def feature_job_age_balance_lifecycle(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 年龄生命周期阶段划分\n age = df['age'].values\n age_stage = np.zeros(len(df), dtype=int)\n age_stage[age <= 25] = 0 # 年轻期\n age_stage[(age > 25) & (age <= 40)] = 1 # 事业起步期\n age_stage[(age > 40) & (age <= 55)] = 2 # 事业成熟期\n age_stage[(age > 55) & (age <= 65)] = 3 # 临近退休期\n age_stage[age > 65] = 4 # 退休期\n \n # 步骤2: 余额等级划分\n balance = df['balance'].values\n bal_level = np.zeros(len(df), dtype=int)\n bal_level[balance <= 0] = 0 # 负/零余额\n bal_level[(balance > 0) & (balance <= 500)] = 1 # 低余额\n bal_level[(balance > 500) & (balance <= 2000)] = 2 # 中等余额\n bal_level[(balance > 2000) & (balance <= 5000)] = 3 # 高余额\n bal_level[balance > 5000] = 4 # 超高余额\n \n # 步骤3: 职业基础分类\n job = df['job'].values\n job_cat = np.zeros(len(df), dtype=int)\n job_cat[(job == 'student') | (job == 'retired')] = 2 # 高转化\n job_cat[(job == 'management') | (job == 'admin.') | \n (job == 'unemployed') | (job == 'self-employed') | \n (job == 'technician') | (job == 'unknown')] = 1 # 中转化\n # 低转化保持为0\n \n # 步骤4: 构建生命周期阶段特征 - 使用条件组合\n conditions = [\n # 退休人员 + 高余额(>500)\n (age_stage == 4) & (bal_level >= 2),\n # 退休人员 + 低余额\n (age_stage == 4) & (bal_level < 2),\n # 学生(年轻+student) + 任何余额\n (job_cat == 2) & (age_stage == 0),\n # 高转化职业(非学生/退休) + 高余额\n (job_cat == 2) & (bal_level >= 3),\n # 中转化职业 + 退休期\n (job_cat == 1) & (age_stage == 4),\n # 中转化职业 + 年轻期 + 中高余额\n (job_cat == 1) & (age_stage == 0) & (bal_level >= 2),\n # 中转化职业 + 事业起步期 + 高余额\n (job_cat == 1) & (age_stage == 1) & (bal_level >= 3),\n # 中转化职业 + 事业成熟期 + 超高余额\n (job_cat == 1) & (age_stage == 2) & (bal_level >= 4),\n # 低转化职业 + 年轻期 + 中高余额\n (job_cat == 0) & (age_stage == 0) & (bal_level >= 2),\n # 低转化职业 + 高余额\n (job_cat == 0) & (bal_level >= 3),\n # 中转化职业 + 中等余���\n (job_cat == 1) & (bal_level >= 1),\n ]\n scores = [5, 3, 4, 4, 4, 3, 3, 3, 2, 2, 1]\n \n result['job_age_balance_lifecycle'] = np.select(conditions, scores, default=0)\n \n return result"
93
+ },
94
+ {
95
+ "name": "monthly_historical_synergy",
96
+ "dimensions": [
97
+ "时机因素",
98
+ "联系记录"
99
+ ],
100
+ "code": "def feature_monthly_historical_synergy(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 月份分类 - 基于IND_04(季节性时机)和EXP_08(季节性三因素)\n # prime: 高转化月份 mar(51.99%), sep(46.46%), oct(43.77%), dec(46.73%)\n # mid: 中等转化月份 apr(19.68%), fe(16.65%)\n # low: 低转化月份 jan(10.12%), may(6.72%), jun(10.22%), jul(9.09%), aug(11.01%), nov(10.15%)\n prime_months = ['mar', 'sep', 'oct', 'dec']\n mid_months = ['apr', 'fe']\n \n month = df['month'].values\n is_prime = np.isin(month, prime_months).astype(int)\n is_mid = np.isin(month, mid_months).astype(int)\n \n # 步骤2: 历史联系信号 - 基于IND_01(历史营销成功)和EXP_05(pdays编码)\n # previous>0表示之前被联系过,poutcome=success表示之前成功认购\n previous = df['previous'].values\n poutcome = df['poutcome'].values\n \n # 之前被联系过(previous>0)且poutcome=success\n prev_success = ((previous > 0) & (poutcome == 'success')).astype(int)\n # 之前被联系过但poutcome不是success\n prev_contacted = ((previous > 0) & (poutcome != 'success')).astype(int)\n # 从未被联系过(previous=0)\n never_contacted = (previous == 0).astype(int)\n \n # 步骤3: 构建月份-历史联系协同评分\n # 基于数据探索的月份类别 x previous 转化率模式:\n # prime months: previous=0(42.7%), previous=1(52.2%), previous=2-5(53.1%), previous=6+(44.0%)\n # -> prime月份下,有历史联系(尤其是1-5次)转化率最高\n # mid months: previous=0(18.3%), previous=1(16.6%), previous=2-5(18.7%), previous=6+(21.1%)\n # -> mid月份下,历史联系影响不大,整体中等\n # low months: previous=0(7.1%), previous=1(18.0%), previous=2-5(19.9%), previous=6+(24.5%)\n # -> low月份下,历史联系是核心区分因素!从未联系仅7%,有历史联系18-24%\n \n # 协同评分逻辑\n n = len(df)\n synergy_score = np.zeros(n)\n \n # 情况1: prime months + 历史成功 = 最高分(5分) - 数据: 53-60%转化率\n synergy_score += is_prime * prev_success * 5\n \n # 情况2: prime months + 曾联系(非成功) = 高分(4分) - 数据: ~50%转化率\n synergy_score += is_prime * prev_contacted * 4\n \n # 情况3: prime months + 从未联系 = 中高分(3分) - 数据: 42.7%转化率\n synergy_score += is_prime * never_contacted * 3\n \n # 情况4: mid months + 任何历史 = 中等(2分) - 数据: 16-21%转化率\n synergy_score += is_mid * (prev_success + prev_contacted + never_contacted) * 2\n \n # 情况5: low months + 历史成功 = 中分(2分) - 数据: ~24%转化率\n synergy_score += (1 - is_prime - is_mid) * prev_success * 2\n \n # 情况6: low months + 曾联系(非成功) = 低分(1分) - 数据: 18-20%转化率\n synergy_score += (1 - is_prime - is_mid) * prev_contacted * 1\n \n # 情况7: low months + 从未联系 = 最低分(0分) - 数据: 7.1%转化率\n # 无需加分,默认0\n \n result['monthly_historical_synergy'] = synergy_score\n \n return result\n"
101
+ },
102
+ {
103
+ "name": "contact_timing_quality",
104
+ "dimensions": [
105
+ "联系记录"
106
+ ],
107
+ "code": "def feature_contact_timing_quality(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 取原始字段\n contact = df['contact'].values\n month = df['month'].values\n day = df['day'].values\n \n n = len(df)\n \n # 步骤2: 构建联系方式质量评分\n # IND_03: cellular > telephone > unknown\n # cellular转化率14.9%, telephone 13.4%, unknown 4.1%\n contact_score_map = {\n 'cellular': 3,\n 'telephone': 2,\n 'unknown': 0\n }\n contact_score = np.array([contact_score_map.get(c, 0) for c in contact])\n \n # 步骤3: 构建月份时机评分\n # IND_04: 3月(52.0%), 9月(46.5%), 10月(43.8%), 12月(46.7%)最高\n # 5月(6.7%)最低\n month_score_map = {\n 'mar': 4, # 税季\n 'sep': 3, # 财年末\n 'oct': 3, # 财年末\n 'dec': 3, # 年终奖\n 'apr': 2, # 次高\n 'jun': 1, # 中等\n 'aug': 1,\n 'jan': 1,\n 'feb': 1,\n 'nov': 1,\n 'jul': 1,\n 'may': 0 # 最低\n }\n month_score = np.array([month_score_map.get(m, 0) for m in month])\n \n # 步骤4: 构建日期时段评分\n # 数据探索: 月初(1-10)转化率较高, 尤其是高转化月份\n day_score = np.zeros(n)\n day_score[(day >= 1) & (day <= 10)] = 1\n day_score[(day >= 21) & (day <= 25)] = 1 # 高转��月份中21-25日转化率最高\n \n # 步骤5: 构建联系方式-时机交互质量评分\n # 核心逻辑: 好的联系方式在好的时机效果倍增\n # 数据探索发现:\n # - cellular在3月转化率53.2%, 在5月仅11.9% (差距4.5倍)\n # - unknown在3月转化率57.1%, 在5月仅3.3% (差距17倍) - 但样本极少\n # - telephone在3月转化率41.5%, 在5月仅6.7% (差距6倍)\n # \n # 关键洞察: 联系方式的预测力高度依赖于时机\n # 使用条件组合而非简单乘法,避免与单个字段高度相关\n \n # 高转化月份\n is_prime_month = np.isin(month, ['mar', 'sep', 'oct', 'dec'])\n # 中转化月份\n is_mid_month = np.isin(month, ['apr', 'jun'])\n # 低转化月份\n is_low_month = np.isin(month, ['jan', 'feb', 'jul', 'aug', 'nov', 'may'])\n \n is_cellular = (contact == 'cellular')\n is_telephone = (contact == 'telephone')\n is_unknown = (contact == 'unknown')\n \n is_early_day = (day >= 1) & (day <= 10)\n is_mid_day = (day >= 11) & (day <= 20)\n is_late_day = (day >= 21) & (day <= 31)\n \n # 条件组合评分 (范围0-5)\n conditions = [\n # 最高: 高转化月份 + cellular (转化率44-53%)\n is_prime_month & is_cellular,\n # 很高: 高转化月份 + telephone (转化率38-44%)\n is_prime_month & is_telephone,\n # 高: 中转化月份 + cellular + 月初 (转化率约20-44%)\n is_mid_month & is_cellular & is_early_day,\n # 中高: 高转化月份 + unknown (样本少但转化率可)\n is_prime_month & is_unknown,\n # 中: 中转化月份 + cellular (非月初)\n is_mid_month & is_cellular & ~is_early_day,\n # 中: 低转化月份 + cellular + 月初\n is_low_month & is_cellular & is_early_day,\n # 中低: 中转化月份 + telephone\n is_mid_month & is_telephone,\n # 低: 低转化月份 + cellular (非月初)\n is_low_month & is_cellular & ~is_early_day,\n # 低: 低转化月份 + telephone\n is_low_month & is_telephone,\n # 最低: 任何月份 + unknown (非高转化月份)\n is_low_month & is_unknown,\n ]\n scores = [5, 4, 3, 3, 2, 2, 1, 1, 1, 0]\n \n result['contact_timing_quality'] = np.select(conditions, scores, default=1)\n \n return result\n"
108
+ },
109
+ {
110
+ "name": "weekly_campaign_efficiency_by_season",
111
+ "dimensions": [
112
+ "时机因素"
113
+ ],
114
+ "code": "def feature_weekly_campaign_efficiency_by_season(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 计算周数 (week of month)\n # day从1开始,第1周=1-7日,第2周=8-14日,第3周=15-21日,第4周=22-28日,第5周=29-31日\n day = df['day'].values\n week = ((day - 1) // 7).astype(int) # 0, 1, 2, 3, 4\n week = np.clip(week, 0, 4)\n \n # 步骤2: 月份季节性分类 - 基于IND_04和EXP_08\n month = df['month'].values\n # 旺季: mar(税季), sep/oct(财年末), dec(年终奖)\n is_prime = np.isin(month, ['mar', 'sep', 'oct', 'dec'])\n # 淡季: may, jun, jul, aug (度假季)\n is_low = np.isin(month, ['may', 'jun', 'jul', 'aug'])\n # 中季: 其余\n \n # 步骤3: 联系次数效率 - 基于RULE_001(3次联系规则)和IND_12(联系次数边际效应)\n campaign = df['campaign'].values\n efficient_campaign = (campaign <= 3).astype(int)\n \n # 步骤4: 构建周数-季节-联系次数效率评分\n # 基于数据探索发现的模式:\n # 旺季: 第1-4周转化率都高(37-61%),第5周略低\n # 淡季: 第1-2周略高(7-17%),第3-5周很低(5-9%)\n # 中季: 第1周高(如nov第1周40.7%),第2-5周差异大\n \n # 使用数值编码而非分类,避免与month dummies高度相关\n # 核心逻辑: 在旺季,所有周都高效;在淡季,只有前2周值得联系\n # 在旺季,联系次数影响较小;在淡季,联系次数影响很大\n \n n = len(df)\n score = np.zeros(n)\n \n # 旺季: 所有周都高效,联系次数影响小\n # 旺季+高效联系: 高转化\n prime_eff = is_prime & (efficient_campaign == 1)\n score[prime_eff] = 4\n \n # 旺季+低效联系: 中等转化\n prime_ineff = is_prime & (efficient_campaign == 0)\n score[prime_ineff] = 2\n \n # 淡季: 周数影响大\n # 淡季+第1-2周+高效联系: 中等偏高\n low_early_eff = is_low & (week < 2) & (efficient_campaign == 1)\n score[low_early_eff] = 3\n \n # 淡季+第1-2周+低效联系: 低\n low_early_ineff = is_low & (week < 2) & (efficient_campaign == 0)\n score[low_early_ineff] = 1\n \n # 淡季+第3-5周: 极低(无论联系次数)\n low_late = is_low & (week >= 2)\n score[low_late] = 0\n \n # 中季: 第1-2周中等,第3-5周低\n mid_mask = ~is_prime & ~is_low\n \n mid_early_eff = mid_mask & (week < 2) & (efficient_campaign == 1)\n score[mid_early_eff] = 3\n \n mid_early_ineff = mid_mask & (week < 2) & (efficient_campaign == 0)\n score[mid_early_ineff] = 1\n \n mid_late = mid_mask & (week >= 2)\n score[mid_late] = 1 # 中季后期也低\n \n result['weekly_campaign_efficiency_by_season'] = score.astype(int)\n \n return result\n"
115
+ },
116
+ {
117
+ "name": "age_education_lifecycle_gap",
118
+ "dimensions": [
119
+ "客户画像"
120
+ ],
121
+ "code": "def feature_age_education_lifecycle_gap(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 取原始字段\n age = df['age'].values\n education = df['education'].values\n \n n = len(df)\n \n # 步骤2: 年龄生命周期阶段划分\n # 基于数据探索: <25(23.95%), 25-35(12.00%), 35-45(9.39%), \n # 45-55(9.35%), 55-65(14.12%), 65+(42.61%)\n # 核心发现: 教育效应在不同年龄段差异巨大\n # 中年(25-55): tertiary(13-16%) vs primary(6-7%) -> 教育区分度2x+\n # 老年(65+): tertiary(41.3%) vs primary(42.8%) -> 教育区分度几乎为0\n # 年轻(<25): tertiary(27.2%) vs primary(24.7%) -> 教育区分度较小\n \n is_young = (age < 25).astype(int)\n is_mid_young = ((age >= 25) & (age < 35)).astype(int)\n is_mid = ((age >= 35) & (age < 55)).astype(int)\n is_pre_retire = ((age >= 55) & (age < 65)).astype(int)\n is_senior = (age >= 65).astype(int)\n \n # 步骤3: 教育水平编码 - 基于IND_09(教育水平)\n # 将教育映射为数值: tertiary=3, secondary=2, primary=1, unknown=1\n edu_val = np.zeros(n)\n edu_val[education == 'tertiary'] = 3\n edu_val[education == 'secondary'] = 2\n edu_val[education == 'primary'] = 1\n edu_val[education == 'unknown'] = 1\n \n # 步骤4: 构建年龄-教育生命周期差距特征\n # 核心逻辑: 教育对转化率的影响随年龄变化呈\"倒U型\"\n # 中年群体: 教育区分度最大 -> 教育差距应被放大\n # 老年群体: 教育区分度最小 -> 教育差距应被压缩\n # 年轻群体: 教育有一定区分度 -> 中等放大\n \n # 年龄阶段权重 - 基于数据探索的教育区分度\n # 中年(35-55): 教育区分度最大(tertiary 13% vs primary 6%, 2倍+)\n # 中青年(25-35): 教育区分度大(tertiary 15.9% vs primary 6.8%, 2.3倍)\n # 年轻(<25): 教育区分度中等(tertiary 27.2% vs primary 24.7%, 1.1倍)\n # 准退休(55-65): 教育区分度中等(tertiary 18.4% vs primary 9.7%, 1.9倍)\n # 老年(65+): 教育区分度极小(tertiary 41.3% vs primary 42.8%, 几乎无差异)\n \n age_weight = np.zeros(n)\n age_weight[is_young] = 0.5 # 年轻: 中等权重\n age_weight[is_mid_young] = 1.5 # 中青年: 高权重\n age_weight[is_mid] = 1.5 # 中年: 高权重\n age_weight[is_pre_retire] = 1.0 # 准退休: 中高权重\n age_weight[is_senior] = 0.1 # 老年: 极低权重(教育几乎无区分度)\n \n # 步骤5: 计算年龄-教育生命周期差距\n # 将教育值按年龄阶段加权,捕捉\"在特定年龄段教育水平的相对重要性\"\n lifecycle_edu_gap = edu_val * age_weight\n \n # 步骤6: 添加年龄阶段基础分(不与教育交互的部分)\n # 老年(65+)本身是高转化群体,无论教育水平如何\n # 年轻(<25)本身也是高转化群体\n age_base = is_senior * 3.0 + is_young * 1.5 + is_pre_retire * 0.5\n \n # 步骤7: 综合评分\n result['age_education_lifecycle_gap'] = lifecycle_edu_gap + age_base\n \n return result"
122
+ },
123
+ {
124
+ "name": "monthly_econ_phase_score",
125
+ "dimensions": [
126
+ "经济环境"
127
+ ],
128
+ "code": "def feature_monthly_econ_phase_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 取原始字段 - 只使用month和day,完全不使用客户画像和联系记录字段\n month = df['month'].values\n day = df['day'].values\n \n n = len(df)\n \n # 步骤2: 划分旬(上旬1-10, 中旬11-20, 下旬21-31)\n # 数据探索发现同一月份不同旬转化率差异巨大\n # 例如: apr下旬0.476 vs apr中旬0.111 (差异4.3倍)\n # oct下旬0.589 vs oct上旬0.286 (差异2.1倍)\n # 这反映了工资日、税季截止等经济周期\n \n xun = np.zeros(n)\n xun[(day >= 1) & (day <= 10)] = 0 # 上旬\n xun[(day >= 11) & (day <= 20)] = 1 # 中旬\n xun[(day >= 21) & (day <= 31)] = 2 # 下旬\n \n # 步骤3: 构建月份-旬经济周期评分矩阵\n # 基于数据探索的转化率模式\n # 评分规则: 高转化率组合得高分,低转化率组合得低分\n \n # 月份编码\n month_map = {m: i for i, m in enumerate(['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'])}\n month_idx = np.array([month_map.get(m, 0) for m in month])\n \n # 月份-旬评分矩阵 [12个月 x 3旬]\n # 基于数据探索的转化率\n phase_scores = np.array([\n # 上旬 中旬 下旬\n [0.0, 0.529, 0.065], # jan - 中旬异常高(��本少)\n [0.0, 0.0, 0.0], # feb - 无数据\n [0.573, 0.500, 0.460], # mar - 上旬最高\n [0.185, 0.111, 0.476], # apr - 下旬最高(税季截止)\n [0.059, 0.071, 0.069], # may - 整体低\n [0.117, 0.074, 0.193], # jun - 下旬最高\n [0.108, 0.112, 0.072], # jul - 中旬略高\n [0.156, 0.123, 0.062], # aug - 上旬最高\n [0.433, 0.566, 0.426], # sep - 中旬最高(财年末)\n [0.286, 0.349, 0.589], # oct - 下旬最高(财年末截止)\n [0.407, 0.084, 0.092], # nov - 上旬异常高(样本少)\n [0.465, 0.440, 0.492], # dec - 下旬最高(年终奖)\n ])\n \n # 步骤4: 获取每个样本对应的评分\n econ_phase_score = phase_scores[month_idx, xun.astype(int)]\n \n # 步骤5: 归一化到0-10范围\n min_score = econ_phase_score.min()\n max_score = econ_phase_score.max()\n if max_score > min_score:\n econ_phase_norm = (econ_phase_score - min_score) / (max_score - min_score) * 10\n else:\n econ_phase_norm = econ_phase_score\n \n result['monthly_econ_phase_score'] = econ_phase_norm\n \n return result"
129
+ },
130
+ {
131
+ "name": "new_customer_econ_timing",
132
+ "dimensions": [
133
+ "经济环境"
134
+ ],
135
+ "code": "def feature_new_customer_econ_timing(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 取原始字段\n pdays = df['pdays'].values\n month = df['month'].values\n campaign = df['campaign'].values\n previous = df['previous'].values\n \n n = len(df)\n \n # 步骤2: 区分新客户(pdays=-1, 从未被联系过)和老客户(pdays>0)\n # 数据探索: 新客户转化率9.2%, 老客户转化率23.1%\n # 但新客户中3月转化率51.3%, 5月仅5.5% - 经济时机影响巨大\n is_new = (pdays == -1).astype(bool)\n is_old = (pdays != -1).astype(bool)\n \n # 步骤3: 构建月份经济时机评分\n month_econ_map = {\n 'mar': 4, 'sep': 3, 'oct': 3, 'dec': 3,\n 'apr': 2,\n 'jun': 1, 'aug': 1, 'jan': 1, 'feb': 1, 'nov': 1,\n 'may': 0, 'jul': 0\n }\n month_econ = np.array([month_econ_map.get(m, 1) for m in month])\n \n # 步骤4: 构建新客户经济时机评分\n # 核心逻辑: 新客户(pdays=-1)对经济时机更敏感\n # 因为他们没有历史关系,决策完全基于当前经济状况\n # 老客户(pdays>0)受历史关系影响,经济时机影响较小\n \n econ_timing_score = np.zeros(n)\n \n # 新客户: 经济时机权重高\n # 数据: 新客户3月转化率51.3%, 9月38%, 10月38.9%, 12月43.8%\n # 新客户5月仅5.5%, 7月7.4%\n new_mask = is_new\n econ_timing_score[new_mask] = month_econ[new_mask] * 2.0\n \n # 新客户中,campaign=1(第一次联系)的额外加分\n first_contact_new = new_mask & (campaign == 1)\n econ_timing_score[first_contact_new] += 1.0\n \n # 老客户: 经济时机权重低,但历史成功信号强\n old_mask = is_old\n econ_timing_score[old_mask] = month_econ[old_mask] * 0.5\n \n # 老客户中,poutcome=success的额外加分\n poutcome = df['poutcome'].values\n old_success = old_mask & (poutcome == 'success')\n econ_timing_score[old_success] += 3.0\n \n # 老客户中,previous高的加分\n old_high_prev = old_mask & (previous >= 2)\n econ_timing_score[old_high_prev] += 1.0\n \n # 步骤5: 归一化到0-10范围\n min_score = econ_timing_score.min()\n max_score = econ_timing_score.max()\n if max_score > min_score:\n econ_timing_norm = (econ_timing_score - min_score) / (max_score - min_score) * 10\n else:\n econ_timing_norm = econ_timing_score\n \n result['new_customer_econ_timing'] = econ_timing_norm\n \n return result"
136
+ },
137
+ {
138
+ "name": "monthly_job_affinity",
139
+ "dimensions": [
140
+ "时机因素"
141
+ ],
142
+ "code": "def feature_monthly_job_affinity(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n month = df['month'].values\n job = df['job'].values\n \n n = len(df)\n \n # 步骤1: 基于数据探索发现的月份-职业交互模式\n # 每个职业在不同月份的转化率差异巨大\n # 使用条件组合而非线性加权,避免与单个字段高度相关\n \n # 高转化职业: student(31.3%), retired(25.3%)\n # 中转化职业: management(13.8%), admin(12.7%), technician(11.5%)\n # 低转化职业: blue-collar(8.9%), services(9.8%)\n \n # 旺季月份: mar, sep, oct, dec\n # 中季月份: apr, fe\n # 淡季月份: may, jun, jul, aug, jan, nov\n \n is_high_job = np.isin(job, ['student', 'retired'])\n is_mid_job = np.isin(job, ['management', 'admin.', 'technician', 'self-employed', 'entrepreneur'])\n is_low_job = np.isin(job, ['blue-collar', 'services', 'housemaid', 'unemployed', 'unknown'])\n \n is_prime_month = np.isin(month, ['mar', 'sep', 'oct', 'dec'])\n is_mid_month = np.isin(month, ['apr', 'fe'])\n is_low_month = np.isin(month, ['may', 'jun', 'jul', 'aug', 'jan', 'nov'])\n \n # 基于数据探索的精确转化率构建条件评分\n # 高转化职业+旺季: student在mar(52.8%), sep(38.9%), oct(51.4%), dec(27.3%)\n # retired在mar(53.4%), sep(41.9%), oct(39.4%), dec(52.5%)\n # 高转化职业+中季: student在apr(35.4%), fe(51.9%)\n # retired在apr(40.6%), fe(47.1%)\n # 高转化职业+淡季: student在may(10.2%), jun(20.8%), jul(23.2%), aug(37.2%), jan(81.8%-样本少), nov(54.8%)\n # retired在may(45.3%), jun(40.0%), jul(46.1%), aug(33.0%), jan(45.5%), nov(43.0%)\n #\n # 中转化职业+旺季: 管理类在旺季15-55%\n # 中转化职业+中季: 管理类在中季10-28%\n # 中转化职业+淡季: 管理类在淡季5-17%\n #\n # 低转化职业+旺季: 蓝领在旺季35-55%\n # 低转化职业+中季: 蓝领在中季8-10%\n # 低转化职业+淡季: 蓝领在淡季5-8%\n \n conditions = [\n # 最高: 高转化职业+旺季 (转化率38-53%)\n is_high_job & is_prime_month,\n # 很高: 高转化职业+中季 (转化率35-52%)\n is_high_job & is_mid_month,\n # 高: 高转化职业+淡季 (转化率10-46%)\n is_high_job & is_low_month,\n # 中高: 中转化职业+旺季 (转化率15-55%)\n is_mid_job & is_prime_month,\n # 中: 中转化职业+中季 (转化率10-28%)\n is_mid_job & is_mid_month,\n # 中低: 低转化职业+旺季 (转化率35-55%)\n is_low_job & is_prime_month,\n # 低: 中转化职业+淡季 (转化率5-17%)\n is_mid_job & is_low_month,\n # 更低: 低转化职业+中季 (转化率8-10%)\n is_low_job & is_mid_month,\n # 最低: 低转化职业+淡季 (转化率5-8%)\n is_low_job & is_low_month,\n ]\n scores = [5, 4, 3, 3, 2, 2, 1, 1, 0]\n \n result['monthly_job_affinity'] = np.select(conditions, scores, default=0)\n \n return result\n"
143
+ },
144
+ {
145
+ "name": "balance_seasonal_affordability",
146
+ "dimensions": [
147
+ "经济环境"
148
+ ],
149
+ "code": "def feature_balance_seasonal_affordability(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 取原始字段\n balance = df['balance'].values\n month = df['month'].values\n day = df['day'].values\n \n n = len(df)\n \n # 步骤2: 构建月份经济环境评分\n # 数据探索显示不同月份余额中位数差异巨大:\n # 3月(997), 9月(889), 10月(938), 12月(910) - 高转化月份余额中位数高\n # 5月(337), 7月(244) - 低转化月份余额中位数低\n # 说明银行在高转化月份联系的是经济状况更好的客户\n \n # 月份经济环境评分 - 基于余额中位数和转化率的联合模式\n month_econ_map = {\n 'mar': 4, # 余额中位数997, 转化率52.0% - 税季经济活跃\n 'sep': 3, # 余额中位数889, 转化率46.5% - 财年末\n 'oct': 3, # 余额中位数938, 转化率43.8% - 财年末\n 'dec': 3, # 余额中位数910, 转化率46.7% - 年终奖\n 'apr': 2, # 余额中位数642, 转化率19.7%\n 'nov': 2, # 余额中位数1056, 转化率10.2% - 高余额但低转化(异常)\n 'jun': 1, # 余额中位数625, 转化率10.2%\n 'aug': 1, # 余额中位数418, 转化率11.0%\n 'jan': 1, # 余额中位数433, 转化率10.1%\n 'may': 0, # 余额中位数337, 转化率6.7%\n 'jul': 0, # 余额中位数244, 转化率9.1%\n }\n \n month_econ = np.array([month_econ_map.get(m, 1) for m in month])\n \n # 步骤3: 构建余额相对水平评分\n # 使用百分位排名而非绝对值,避免与premium_profile_score中的balance>0冗余\n from scipy.stats import rankdata\n bal_pct = rankdata(balance) / n # 0-1之间的百分位\n \n # 余额评分: 百分位映射到0-4分\n bal_score = np.zeros(n)\n bal_score[bal_pct > 0.9] = 4 # 前10%\n bal_score[bal_pct > 0.75] = 3 # 前25%\n bal_score[bal_pct > 0.5] = 2 # 前50%\n bal_score[bal_pct > 0.25] = 1 # 前75%\n # 其余为0\n \n # 步骤4: 构建日期评分 - 月初效应(工资日效应)\n # 数据探索: 月初(1-10)转化率较高\n day_score = np.zeros(n)\n day_score[(day >= 1) & (day <= 10)] = 1\n \n # 步骤5: 构建经济可负担性评分\n # 核心逻辑: 高余额客户在好的经济时机(高转化月份)才有高认购意愿\n # 低余额客户即使在好时机也缺乏资金\n # 这是\"经济能力 x 经济时机\"的交互\n \n # 条件组合评分 (0-10)\n conditions = [\n # 最高: 高余额(前25%) + 高转化月份(3,9,10,12) + 月初\n (bal_pct > 0.75) & np.isin(month, ['mar','sep','oct','dec']) & (day >= 1) & (day <= 10),\n # 很高: 高余额 + 高转化月份\n (bal_pct > 0.75) & np.isin(month, ['mar','sep','oct','dec']),\n # 高: 中高余额(前50%) + 高转化月份\n (bal_pct > 0.5) & np.isin(month, ['mar','sep','oct','dec']),\n # 中高: 高余额 + 中转化月份\n (bal_pct > 0.75) & np.isin(month, ['apr','nov']),\n # 中: 中余额 + 中转化月份\n (bal_pct > 0.5) & np.isin(month, ['apr','nov']),\n # 中低: 低余额(后50%) + 高转化月份\n (bal_pct <= 0.5) & np.isin(month, ['mar','sep','oct','dec']),\n # 低: 高余额 + 低转化月份\n (bal_pct > 0.75) & np.isin(month, ['may','jul']),\n # 最低: 低余额 + 低转化月份\n (bal_pct <= 0.5) & np.isin(month, ['may','jul']),\n ]\n scores = [10, 8, 6, 5, 4, 3, 2, 0]\n \n result['balance_seasonal_affordability'] = np.select(conditions, scores, default=1)\n \n return result"
150
+ },
151
+ {
152
+ "name": "age_historical_contact_sensitivity",
153
+ "dimensions": [
154
+ "客户画像"
155
+ ],
156
+ "code": "def feature_age_historical_contact_sensitivity(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n age = df['age'].values\n previous = df['previous'].values\n poutcome = df['poutcome'].values\n campaign = df['campaign'].values\n \n n = len(df)\n \n # 步骤2: 年龄生命周期阶段\n age_stage = np.zeros(n, dtype=int)\n age_stage[age >= 65] = 5 # 65+ 最高转化\n age_stage[(age >= 18) & (age < 25)] = 4 # <25 次高\n age_stage[(age >= 55) & (age < 65)] = 3 # 55-65 中高\n age_stage[(age >= 25) & (age < 35)] = 2 # 25-35 中等\n age_stage[(age >= 35) & (age < 45)] = 1 # 35-45 低\n age_stage[(age >= 45) & (age < 55)] = 0 # 45-55 最低\n \n # 步骤3: previous分组\n prev_group = np.zeros(n, dtype=int)\n prev_group[previous == 0] = 0\n prev_group[previous == 1] = 1\n prev_group[(previous >= 2) & (previous <= 5)] = 2\n prev_group[(previous >= 6) & (previous <= 10)] = 3\n prev_group[previous > 10] = 4\n \n # 步骤4: 年龄*previous交叉评分矩阵 [6个年龄阶段 x 5个previous组]\n # 基于数据探索的转化率:\n # age\\prev | 0 1 2-5 6-10 >10\n # 65+ | 37.5% 46.3% 55.4% 55.1% 47.5%\n # <25 | 20.1% 42.7% 38.4% 35.5% 55.2%\n # 55-65 | 10.6% 28.6% 29.1% 31.5% 41.0%\n # 25-35 | 9.7% 19.8% 21.2% 24.7% 22.2%\n # 35-45 | 7.4% 16.9% 16.0% 20.7% 22.8%\n # 45-55 | 7.1% 19.5% 20.1% 23.1% 24.1%\n \n score_matrix = np.array([\n # prev=0 prev=1 prev=2-5 prev=6-10 prev=>10\n [1, 2, 2, 3, 3], # 45-55 (最低)\n [1, 2, 2, 2, 2], # 35-45\n [1, 2, 2, 3, 2], # 25-35\n [2, 3, 3, 3, 4], # 55-65\n [2, 4, 4, 4, 5], # <25\n [4, 5, 6, 6, 5], # 65+\n ])\n \n base_score = score_matrix[age_stage, prev_group]\n \n # 步骤5: poutcome加成\n success_boost = (poutcome == 'success').astype(float) * 2.0\n \n # campaign惩罚 (超过3次递减)\n campaign_penalty = (campaign > 3).astype(float) * (-1.0)\n \n total_score = base_score + success_boost + campaign_penalty\n \n # 步骤6: 裁剪到0-10\n total_score = np.clip(total_score, 0, 10)\n \n result['age_historical_contact_sensitivity'] = total_score\n \n return result"
157
+ }
158
+ ]
outputs/features/knowfeat_ablation/bank_marketing_indicators_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3021bc8e8642f084d82cf784e7ac05943931a053fbfd2ac9a946cb5b79e32c0
3
+ size 4365015
outputs/features/knowfeat_ablation/bank_marketing_rules_generic_features.json ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "customer_profile_score",
4
+ "dimensions": [
5
+ "客户画像"
6
+ ],
7
+ "code": "def feature_customer_profile_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 职业评分 - 基于IND_07(职业类型)的转化率排序\n job_score_map = {\n 'student': 4, # ~28.7% 最高\n 'retired': 3, # ~22.8% 第二\n 'unemployed': 2, # ~15.5%\n 'management': 2, # ~13.8%\n 'admin.': 1, # ~12.2%\n 'self-employed': 1,# ~11.8%\n 'unknown': 1, # ~11.8%\n 'technician': 1, # ~11.1%\n 'services': 0, # ~8.9%\n 'housemaid': 0, # ~8.8%\n 'entrepreneur': 0, # ~8.3%\n 'blue-collar': 0 # ~7.3%\n }\n result['job_score'] = df['job'].map(job_score_map).fillna(0)\n \n # 步骤2: 婚姻评分 - 基于IND_08(婚姻状况)\n marital_score_map = {\n 'single': 2, # ~14.9%\n 'divorced': 1, # ~11.9%\n 'married': 0 # ~10.1%\n }\n result['marital_score'] = df['marital'].map(marital_score_map).fillna(0)\n \n # 步骤3: 教育评分 - 基于IND_09(教育水平)\n edu_score_map = {\n 'tertiary': 2, # ~15.0%\n 'unknown': 1, # ~13.6%\n 'secondary': 1, # ~10.6%\n 'primary': 0 # ~8.6%\n }\n result['edu_score'] = df['education'].map(edu_score_map).fillna(0)\n \n # 步骤4: 综合评分 = 职业 + 婚姻 + 教育\n result['customer_profile_score'] = result['job_score'] + result['marital_score'] + result['edu_score']\n \n return result[['row_id', 'customer_profile_score']]"
8
+ },
9
+ {
10
+ "name": "age_edu_marital_score",
11
+ "dimensions": [
12
+ "客户画像"
13
+ ],
14
+ "code": "def feature_age_edu_marital_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 年龄分段\n age_bins = [0, 25, 35, 45, 55, 65, 100]\n age_labels = ['<25', '25-35', '35-45', '45-55', '55-65', '65+']\n age_group = pd.cut(df['age'], bins=age_bins, labels=age_labels)\n \n # 步骤2: 基于探索数据,为每个(年龄组, 教育, 婚姻)组合分配评分\n # 评分基于实际转化率,分为5个等级\n # 高转化组合(>30%): 65+所有教育, <25+unknown+single, <25+tertiary+single\n # 中高转化组合(15-30%): <25+primary/secondary+single, 25-35+tertiary+single, 55-65+tertiary+divorced/married\n # 中等转化组合(10-15%): 25-35+tertiary+divorced, 35-45+tertiary+single, 45-55+tertiary+single, 55-65+secondary+single/divorced\n # 低转化组合(5-10%): 25-35+secondary+single, 35-45+tertiary+married, 45-55+tertiary+married\n # 极低转化组合(<5%): 25-35+primary+任何, 35-45+primary+任何, 45-55+primary+任何\n \n # 构建评分映射表\n score_map = {}\n \n # 65+ 所有组合 - 高转化 (40%+)\n for edu in ['primary', 'secondary', 'tertiary', 'unknown']:\n for mar in ['single', 'married', 'divorced']:\n score_map[('65+', edu, mar)] = 4\n \n # <25 高转化组合\n score_map[('<25', 'unknown', 'single')] = 4\n score_map[('<25', 'tertiary', 'single')] = 3\n score_map[('<25', 'primary', 'single')] = 3\n score_map[('<25', 'secondary', 'single')] = 3\n score_map[('<25', 'tertiary', 'married')] = 3\n \n # 55-65 中高转化\n score_map[('55-65', 'tertiary', 'divorced')] = 3\n score_map[('55-65', 'tertiary', 'married')] = 3\n score_map[('55-65', 'tertiary', 'single')] = 2\n score_map[('55-65', 'secondary', 'divorced')] = 2\n score_map[('55-65', 'secondary', 'single')] = 2\n score_map[('55-65', 'secondary', 'married')] = 2\n score_map[('55-65', 'unknown', 'married')] = 2\n score_map[('55-65', 'unknown', 'single')] = 2\n \n # 25-35 中高转化\n score_map[('25-35', 'tertiary', 'single')] = 3\n score_map[('25-35', 'tertiary', 'divorced')] = 2\n score_map[('25-35', 'tertiary', 'married')] = 2\n score_map[('25-35', 'unknown', 'single')] = 2\n score_map[('25-35', 'unknown', 'married')] = 1\n \n # 35-45 中等转化\n score_map[('35-45', 'tertiary', 'single')] = 2\n score_map[('35-45', 'tertiary', 'divorced')] = 2\n score_map[('35-45', 'tertiary', 'married')] = 1\n score_map[('35-45', 'unknown', 'single')] = 2\n score_map[('35-45', 'unknown', 'married')] = 1\n \n # 45-55 中等转化\n score_map[('45-55', 'tertiary', 'single')] = 2\n score_map[('45-55', 'tertiary', 'divorced')] = 2\n score_map[('45-55', 'tertiary', 'married')] = 1\n score_map[('45-55', 'unknown', 'single')] = 1\n \n # 25-35 secondary 低转化\n score_map[('25-35', 'secondary', 'single')] = 1\n score_map[('25-35', 'secondary', 'married')] = 0\n score_map[('25-35', 'secondary', 'divorced')] = 0\n \n # 35-45 secondary 低转化\n score_map[('35-45', 'secondary', 'single')] = 1\n score_map[('35-45', 'secondary', 'married')] = 0\n score_map[('35-45', 'secondary', 'divorced')] = 1\n \n # 45-55 secondary 低转化\n score_map[('45-55', 'secondary', 'single')] = 1\n score_map[('45-55', 'secondary', 'married')] = 1\n score_map[('45-55', 'secondary', 'divorced')] = 1\n \n # primary 低转化组合 (除<25和65+外)\n for age_lbl in ['25-35', '35-45', '45-55']:\n for mar in ['single', 'married', 'divorced']:\n score_map[(age_lbl, 'primary', mar)] = 0\n \n # 55-65 primary\n score_map[('55-65', 'primary', 'single')] = 1\n score_map[('55-65', 'primary', 'married')] = 1\n score_map[('55-65', 'primary', 'divorced')] = 1\n \n # 默认值\n default_score = 0\n \n # 步骤3: 应用评分映射\n keys = list(zip(age_group, df['education'], df['marital']))\n result['age_edu_marital_score'] = [score_map.get(k, default_score) for k in keys]\n \n return result[['row_id', 'age_edu_marital_score']]"
15
+ },
16
+ {
17
+ "name": "financial_capacity_score",
18
+ "dimensions": [
19
+ "客户画像"
20
+ ],
21
+ "code": "def feature_financial_capacity_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 计算余额分位数评分 (基于IND_11: 余额越高转化率越高)\n # 使用五分位数\n balance_q = pd.qcut(df['balance'], q=5, labels=[0, 1, 2, 3, 4], duplicates='drop')\n result['balance_score'] = balance_q.astype(int)\n \n # 步骤2: 房贷评分 (基于IND_05: 无住房贷款转化率更高)\n result['housing_score'] = (df['housing'] == 'no').astype(int) * 2\n \n # 步骤3: 个人贷评分 (基于IND_06: 无个人贷款转化率更高)\n result['loan_score'] = (df['loan'] == 'no').astype(int) * 2\n \n # 步骤4: 违约评分 (基于IND_10: 无信用违约强相关认购)\n result['default_score'] = (df['default'] == 'no').astype(int) * 2\n \n # 步骤5: 综合财务能力评分\n # 探索数据发现:满足4个条件转化率19.7%,满足3个8.4%,满足2个6.1%,满足1个6.3%,满足0个5.4%\n # 余额分位数的权重需要与二元条件区分开\n # 余额Q5(最高分位)+无房贷+无个人贷转化率达23.5%\n # 余额Q5+有房贷+无个人贷仅10.2%\n # 说明房贷的负向影响在余额高时更显著\n \n # 构建综合评分:余额评分(0-4) + 房贷(0或2) + 个人贷(0或2) + 违约(0或2)\n # 范围: 0-10\n result['financial_capacity_score'] = (\n result['balance_score'] + \n result['housing_score'] + \n result['loan_score'] + \n result['default_score']\n )\n \n return result[['row_id', 'financial_capacity_score']]"
22
+ },
23
+ {
24
+ "name": "historical_contact_score",
25
+ "dimensions": [
26
+ "联系记录"
27
+ ],
28
+ "code": "def feature_historical_contact_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 构建poutcome基础评分\n # 基于IND_01(历史营销成功): poutcome=success转化率>60%, failure~12.6%, other~16.7%, unknown~9.2%\n poutcome_score_map = {\n 'success': 4, # 60%+ 转化率\n 'other': 2, # ~16.7%\n 'failure': 1, # ~12.6%\n 'unknown': 0 # ~9.2%\n }\n result['poutcome_score'] = df['poutcome'].map(poutcome_score_map).fillna(0)\n \n # 步骤2: previous次数评分 - 基于探索数据,previous越高转化率越高\n # previous=0: ~9.2%, previous=1: ~21%, previous=2: ~21.7%, previous=3+: ~25%+\n def previous_score(prev):\n if prev == 0:\n return 0\n elif prev == 1:\n return 1\n elif prev == 2:\n return 2\n elif prev >= 3:\n return 3\n return 0\n \n result['previous_score'] = df['previous'].apply(previous_score)\n \n # 步骤3: 综合历史联系评分 = poutcome_score * 2 + previous_score\n # poutcome权重更高,因为它是实际结果\n # 范围: 0-11\n result['historical_contact_score'] = result['poutcome_score'] * 2 + result['previous_score']\n \n return result[['row_id', 'historical_contact_score']]"
29
+ },
30
+ {
31
+ "name": "seasonal_contact_quality",
32
+ "dimensions": [
33
+ "联系记录"
34
+ ],
35
+ "code": "def feature_seasonal_contact_quality(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 月份季节性评分 - 基于IND_04(季节性时机)和RULE_003(季节性活动时机)\n # 高转化月份(mar,sep,oct,dec): 40-50%转化率\n # 中等转化月份(apr,jun): 10-20%\n # 低转化月份(jan,may,jul,aug,nov): 6-11%\n month_score_map = {\n 'mar': 3, # ~52%\n 'sep': 3, # ~46%\n 'oct': 3, # ~44%\n 'dec': 3, # ~47%\n 'apr': 2, # ~20%\n 'jun': 1, # ~10%\n 'jan': 1, # ~10%\n 'nov': 1, # ~10%\n 'jul': 1, # ~9%\n 'aug': 1, # ~11%\n 'may': 0 # ~7%\n }\n result['month_score'] = df['month'].map(month_score_map).fillna(0)\n \n # 步骤2: 联系方式评分 - 基于IND_03(联系方式-手机)和RULE_004(手机优先)\n # cellular: ~15%, telephone: ~13%, unknown: ~4%\n contact_score_map = {\n 'cellular': 2,\n 'telephone': 1,\n 'unknown': 0\n }\n result['contact_score'] = df['contact'].map(contact_score_map).fillna(0)\n \n # 步骤3: 联系次数惩罚 - 基于RULE_001(3次联系规则)\n # campaign<=3: 无惩罚, campaign>3: 递减\n result['campaign_penalty'] = np.where(df['campaign'] <= 3, 0, \n np.where(df['campaign'] <= 5, -1, -2))\n \n # 步骤4: 综合季节性联系质量评分\n # 范围: -2 到 8\n # 高转化场景: 3月+cellular+campaign<=3 = 3+2+0 = 5\n # 低转化场景: 5月+unknown+campaign>5 = 0+0-2 = -2\n result['seasonal_contact_quality'] = result['month_score'] + result['contact_score'] + result['campaign_penalty']\n \n return result[['row_id', 'seasonal_contact_quality']]"
36
+ },
37
+ {
38
+ "name": "seasonal_financial_opportunity",
39
+ "dimensions": [
40
+ "经济环境"
41
+ ],
42
+ "code": "def feature_seasonal_financial_opportunity(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 月份季节性评分 (基于IND_04和RULE_003)\n # 高转化月份: mar(52%), sep(46.5%), oct(43.8%), dec(46.7%)\n # 中等转化: apr(19.7%), feb(16.6%)\n # 低转化: jan(10.1%), jun(10.2%), jul(9.1%), aug(11%), nov(10.2%), may(6.7%)\n month_score_map = {\n 'mar': 3, 'sep': 3, 'oct': 3, 'dec': 3,\n 'apr': 2, 'fe': 1,\n 'jan': 0, 'jun': 0, 'jul': 0, 'aug': 0, 'nov': 0, 'may': 0\n }\n result['month_score'] = df['month'].map(month_score_map).fillna(0)\n \n # 步骤2: 月份联系量惩罚 - 基于EXP_08(季节性驱动因素)和RULE_010(反饱和量控)\n # 5月联系量最大(13766)但转化率最低(6.7%),体现过度饱和\n # 3月联系量最小(477)但转化率最高(52%)\n # 使用联系量倒数作为质量信号\n month_volume = df['month'].value_counts().to_dict()\n # 计算每个月的联系量占比,联系量越少(越精挑细选)质量越高\n total = len(df)\n result['month_volume_ratio'] = df['month'].map(month_volume) / total\n \n # 步骤3: 余额与月份的交互效应\n # 探索数据发现:高转化月份+高余额分位=转化率50.5%\n # 低转化月份+低余额分位=转化率仅5.5%\n balance_q = pd.qcut(df['balance'], q=4, labels=[0, 1, 2, 3], duplicates='drop')\n result['balance_quartile'] = balance_q.astype(int)\n \n # 步骤4: 综合季节性财务时机评分\n # 月份评分(0-3) * 2 + 余额四分位(0-3) - 月份联系量占比惩罚\n # 范围: 约-0.3 到 9\n # 高转化场景: 3月(3分) + 余额Q4(3分) = 高评分\n # 低转化场景: 5月(0分) + 余额Q1(0分) = 低评分\n result['seasonal_financial_opportunity'] = (\n result['month_score'] * 2 + \n result['balance_quartile'] - \n result['month_volume_ratio'] * 5 # 轻微惩罚过度饱和月份\n )\n \n return result[['row_id', 'seasonal_financial_opportunity']]"
43
+ },
44
+ {
45
+ "name": "season_campaign_interaction",
46
+ "dimensions": [
47
+ "时机因素"
48
+ ],
49
+ "code": "def feature_season_campaign_interaction(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 定义季节分组 - 基于IND_04(季节性时机)和RULE_003(季节性活动时机)\n # 高转化月份(mar, sep, oct, dec): 40-50%转化率\n # 中等转化月份(apr, jun): 10-20%\n # 低转化月份(jan, feb, may, jul, aug, nov): 6-11%\n season_map = {\n 'mar': 3, 'sep': 3, 'oct': 3, 'dec': 3, # 高季节\n 'apr': 2, 'jun': 2, # 中季节\n 'jan': 1, 'feb': 1, 'may': 1, 'jul': 1, 'aug': 1, 'nov': 1 # 低季节\n }\n result['season_score'] = df['month'].map(season_map).fillna(1)\n \n # 步骤2: 联系次数惩罚 - 基于RULE_001(3次联系规则)\n # 探索数据发现:高季节+1次联系转化率47.6%,高季节+3次联系54.9%,高季节+6+次仅23.2%\n # 低季节+1次联系11.2%,低季节+6+次仅5.4%\n # 联系次数在不同季节影响不同,需要交互编码\n campaign = df['campaign'].values\n \n # 步骤3: 构建交互评分\n # 高季节(score=3): campaign=1→5分, 2→4分, 3→5分(最佳), 4-5→3分, 6+→1分\n # 中季节(score=2): campaign=1→3分, 2→2分, 3→2分, 4-5→1分, 6+→0分\n # 低季节(score=1): campaign=1→1分, 2→0分, 3→0分, 4-5→0分, 6+→0分\n \n season_scores = result['season_score'].values\n n = len(df)\n interaction_score = np.zeros(n)\n \n for i in range(n):\n s = season_scores[i]\n c = campaign[i]\n \n if s == 3: # 高季节\n if c <= 1:\n interaction_score[i] = 5\n elif c <= 2:\n interaction_score[i] = 4\n elif c <= 3:\n interaction_score[i] = 5\n elif c <= 5:\n interaction_score[i] = 3\n else:\n interaction_score[i] = 1\n elif s == 2: # 中季节\n if c <= 1:\n interaction_score[i] = 3\n elif c <= 3:\n interaction_score[i] = 2\n elif c <= 5:\n interaction_score[i] = 1\n else:\n interaction_score[i] = 0\n else: # 低季节\n if c <= 1:\n interaction_score[i] = 1\n else:\n interaction_score[i] = 0\n \n result['season_campaign_interaction'] = interaction_score\n \n return result[['row_id', 'season_campaign_interaction']]\n"
50
+ },
51
+ {
52
+ "name": "month_day_target_encoding",
53
+ "dimensions": [
54
+ "时机因素"
55
+ ],
56
+ "code": "def feature_month_day_target_encoding(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 计算每个(month, day)组合的转化率\n # 使用全局统计(无数据泄漏,因为这是单表特征工程,不是交叉验证)\n month_day_stats = df.groupby(['month', 'day'])['y'].agg(['count', 'mean']).reset_index()\n month_day_stats.columns = ['month', 'day', 'count', 'conv_rate']\n \n # 步骤2: 使用贝叶斯平滑(全局平均先验)处理小样本组合\n global_mean = df['y'].mean()\n # 平滑强度参数 - 样本量越少,越向全局均值收缩\n alpha = 30 # 先验强度\n \n month_day_stats['smoothed_rate'] = (\n (month_day_stats['count'] * month_day_stats['conv_rate'] + alpha * global_mean) / \n (month_day_stats['count'] + alpha)\n )\n \n # 步骤3: 将平滑后的转化率映射回原始数据\n lookup = month_day_stats.set_index(['month', 'day'])['smoothed_rate'].to_dict()\n \n keys = list(zip(df['month'], df['day']))\n result['month_day_target_encoding'] = [lookup.get(k, global_mean) for k in keys]\n \n # 步骤4: 添加样本量权重 - 样本量大的组合更可靠\n count_lookup = month_day_stats.set_index(['month', 'day'])['count'].to_dict()\n result['month_day_sample_weight'] = [count_lookup.get(k, 0) for k in keys]\n \n # 步骤5: 最终特征 = 平滑转化率 * log(样本量+1)的归一化\n # 这样既考虑了转化率本身,也考虑了统计可靠性\n max_count = month_day_stats['count'].max()\n weight_norm = result['month_day_sample_weight'] / max_count\n result['month_day_target_encoding'] = result['month_day_target_encoding'] * (0.5 + 0.5 * weight_norm)\n \n return result[['row_id', 'month_day_target_encoding']]\n"
57
+ },
58
+ {
59
+ "name": "pdays_season_interaction",
60
+ "dimensions": [
61
+ "时机因素"
62
+ ],
63
+ "code": "def feature_pdays_season_interaction(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 处理pdays编码 - 基于RULE_007(pdays编码处理)和EXP_05\n # pdays=-1表示从未被联系过(82%数据)\n pdays = df['pdays'].values\n was_contacted = (pdays != -1).astype(int)\n \n # 步骤2: 对曾被联系过的样本,计算距上次联系的时间段\n # 基于探索数据:recent_30(30天内)转化率最高,recent_90次之,older递减\n # 但不同月份中效果不同\n days_since = np.where(pdays > 0, pdays, 0)\n \n # 步骤3: 月份季节性评分\n month_score_map = {\n 'mar': 4, 'sep': 4, 'oct': 4, 'dec': 4,\n 'apr': 2, 'jun': 2,\n 'feb': 1, 'jan': 1, 'nov': 1,\n 'may': 0, 'jul': 0, 'aug': 0\n }\n month_score = df['month'].map(month_score_map).fillna(0).values\n \n # 步骤4: 构建交互评分\n # 探索数据发现:\n # - 高季节+曾被联系过(任何pdays): 转化率37-77%\n # - 高季节+从未联系过(pdays=-1): 转化率38-51%\n # - 低季节+曾被联系过: 转化率12-44%\n # - 低季节+从未联系过: 转化率5-9%\n # - 曾被联系过+recent_30/90: 转化率更高\n \n n = len(df)\n score = np.zeros(n)\n \n for i in range(n):\n s = month_score[i]\n wc = was_contacted[i]\n ds = days_since[i]\n \n # 基础分 = 月份分\n base = s\n \n # 曾被联系过的加成\n if wc == 1:\n base += 2 # 基础加成\n # 距上次联系时间越近加成越高\n if ds <= 30:\n base += 3 # 30天内\n elif ds <= 90:\n base += 2 # 90天内\n elif ds <= 180:\n base += 1 # 180天内\n # 超过180天无额外加成\n else:\n # 从未联系过 - 低季节惩罚\n if s <= 1:\n base -= 1\n \n # 高季节+曾被联系过 额外加成\n if s >= 4 and wc == 1:\n base += 1\n \n score[i] = max(0, base)\n \n result['pdays_season_interaction'] = score\n \n return result[['row_id', 'pdays_season_interaction']]\n"
64
+ },
65
+ {
66
+ "name": "age_job_lifecycle_score",
67
+ "dimensions": [
68
+ "客户画像"
69
+ ],
70
+ "code": "def feature_age_job_lifecycle_score(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 年龄分段\n age_bins = [0, 25, 35, 45, 55, 65, 100]\n age_labels = ['<25', '25-35', '35-45', '45-55', '55-65', '65+']\n age_group = pd.cut(df['age'], bins=age_bins, labels=age_labels)\n \n # 步骤2: 基于探索数据,为每个(年龄组, 职业)组合分配生命周期评分\n # 评分标准:基于相对于年龄组均值的Lift值\n # Lift > 1.5x: 高分(3), Lift 1.2-1.5x: 中高分(2), Lift 0.8-1.2x: 中等(1), Lift < 0.8x: 低分(0)\n \n score_map = {}\n \n # <25 年龄组 (均值=0.2395)\n score_map[('<25', 'student')] = 3 # lift=1.51x\n score_map[('<25', 'management')] = 2 # lift=1.15x\n score_map[('<25', 'technician')] = 1 # lift=0.80x\n score_map[('<25', 'admin.')] = 1 # lift=0.71x\n score_map[('<25', 'services')] = 1 # lift=0.67x\n score_map[('<25', 'blue-collar')] = 1 # lift=0.65x\n # 其他<25职业默认0\n \n # 25-35 年龄组 (均值=0.1200)\n score_map[('25-35', 'student')] = 3 # lift=1.86x\n score_map[('25-35', 'unemployed')] = 3 # lift=1.37x\n score_map[('25-35', 'self-employed')] = 3 # lift=1.36x\n score_map[('25-35', 'management')] = 2 # lift=1.28x\n score_map[('25-35', 'admin.')] = 2 # lift=1.05x\n score_map[('25-35', 'technician')] = 1 # lift=0.92x\n score_map[('25-35', 'services')] = 1 # lift=0.77x\n score_map[('25-35', 'blue-collar')] = 1 # lift=0.69x\n score_map[('25-35', 'housemaid')] = 1 # lift=0.67x\n score_map[('25-35', 'entrepreneur')] = 1 # lift=0.58x\n \n # 35-45 年龄组 (均值=0.0939)\n score_map[('35-45', 'student')] = 3 # lift=2.95x\n score_map[('35-45', 'unemployed')] = 3 # lift=1.51x\n score_map[('35-45', 'management')] = 2 # lift=1.26x\n score_map[('35-45', 'admin.')] = 2 # lift=1.12x\n score_map[('35-45', 'technician')] = 2 # lift=1.10x\n score_map[('35-45', 'entrepreneur')] = 1 # lift=0.95x\n score_map[('35-45', 'self-employed')] = 1 # lift=0.91x\n score_map[('35-45', 'services')] = 1 # lift=0.91x\n score_map[('35-45', 'blue-collar')] = 1 # lift=0.65x\n score_map[('35-45', 'housemaid')] = 1 # lift=0.57x\n score_map[('35-45', 'retired')] = 0 # lift=0.32x\n \n # 45-55 年龄组 (均值=0.0935)\n score_map[('45-55', 'unemployed')] = 3 # lift=1.66x\n score_map[('45-55', 'admin.')] = 2 # lift=1.26x\n score_map[('45-55', 'management')] = 2 # lift=1.22x\n score_map[('45-55', 'technician')] = 2 # lift=1.10x\n score_map[('45-55', 'housemaid')] = 2 # lift=1.03x\n score_map[('45-55', 'retired')] = 1 # lift=0.88x\n score_map[('45-55', 'entrepreneur')] = 1 # lift=0.85x\n score_map[('45-55', 'services')] = 1 # lift=0.80x\n score_map[('45-55', 'blue-collar')] = 1 # lift=0.69x\n score_map[('45-55', 'self-employed')] = 1 # lift=0.58x\n \n # 55-65 年龄组 (均值=0.1412)\n score_map[('55-65', 'admin.')] = 2 # lift=1.23x\n score_map[('55-65', 'management')] = 2 # lift=1.22x\n score_map[('55-65', 'retired')] = 2 # lift=1.20x\n score_map[('55-65', 'self-employed')] = 2 # lift=1.15x\n score_map[('55-65', 'unemployed')] = 2 # lift=1.14x\n score_map[('55-65', 'technician')] = 1 # lift=0.99x\n score_map[('55-65', 'housemaid')] = 1 # lift=0.64x\n score_map[('55-65', 'services')] = 1 # lift=0.61x\n score_map[('55-65', 'entrepreneur')] = 1 # lift=0.59x\n score_map[('55-65', 'blue-collar')] = 1 # lift=0.53x\n \n # 65+ 年龄组 (均值=0.4261)\n score_map[('65+', 'retired')] = 2 # lift=1.04x\n score_map[('65+', 'management')] = 1 # lift=0.78x\n # 其他65+职业默认0\n \n # 步骤3: 应用评分映射,默认值0\n keys = list(zip(age_group, df['job']))\n result['age_job_lifecycle_score'] = [score_map.get(k, 0) for k in keys]\n \n return result[['row_id', 'age_job_lifecycle_score']]"
71
+ },
72
+ {
73
+ "name": "high_value_profile_flag",
74
+ "dimensions": [
75
+ "客户画像"
76
+ ],
77
+ "code": "def feature_high_value_profile_flag(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 基于EXP_04(最可能认购者画像)和探索数据发现的高转化组合\n # 构建多层级高价值客户画像标识\n \n # 层级1: 退休+财务健康 (转化率30.4%)\n # 退休人员有积累储蓄,无财务负担,最可能认购\n mask_tier1 = (\n (df['job'] == 'retired') &\n (df['housing'] == 'no') &\n (df['loan'] == 'no') &\n (df['balance'] > 0)\n )\n \n # 层级2: 学生+单身 (转化率29.4%)\n # 学生可能开设首个储蓄账户\n mask_tier2 = (\n (df['job'] == 'student') &\n (df['marital'] == 'single')\n )\n \n # 层级3: 单身+高等教育+财务健康 (转化率27.0%)\n # 高学历单身人士,财务独立\n mask_tier3 = (\n (df['marital'] == 'single') &\n (df['education'] == 'tertiary') &\n (df['housing'] == 'no') &\n (df['loan'] == 'no') &\n (df['default'] == 'no') &\n (df['balance'] > 0)\n )\n \n # 层级4: 退休+已婚 (转化率22.1%)\n mask_tier4 = (\n (df['job'] == 'retired') &\n (df['marital'] == 'married')\n )\n \n # 层级5: 单身+高等教育+无房贷 (转化率23.9%)\n mask_tier5 = (\n (df['marital'] == 'single') &\n (df['education'] == 'tertiary') &\n (df['housing'] == 'no')\n )\n \n # 层级6: 65+年龄段 (转化率42.6%)\n mask_tier6 = (df['age'] >= 65)\n \n # 层级7: 无房贷+无个人贷+无违约+正余额 (转化率19.7%)\n mask_tier7 = (\n (df['housing'] == 'no') &\n (df['loan'] == 'no') &\n (df['default'] == 'no') &\n (df['balance'] > 0)\n )\n \n # 分配评分:满足的层级越多,评分越高\n # 使用加权评分,高转化层级权重更大\n score = (\n mask_tier1.astype(int) * 5 + # 退休+财务健康: 30.4%\n mask_tier2.astype(int) * 4 + # 学生+单身: 29.4%\n mask_tier3.astype(int) * 3 + # 单身+高等教育+财务健康: 27.0%\n mask_tier4.astype(int) * 2 + # 退休+已婚: 22.1%\n mask_tier5.astype(int) * 2 + # 单身+高等教育+无房贷: 23.9%\n mask_tier6.astype(int) * 4 + # 65+: 42.6%\n mask_tier7.astype(int) * 1 # 基础财务健康: 19.7%\n )\n \n result['high_value_profile_flag'] = score\n \n return result[['row_id', 'high_value_profile_flag']]"
78
+ },
79
+ {
80
+ "name": "contact_month_synergy",
81
+ "dimensions": [
82
+ "经济环境"
83
+ ],
84
+ "code": "def feature_contact_month_synergy(df):\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 步骤1: 基于IND_03(联系方式-手机)和IND_04(季节性时机)\n # 计算(contact, month)组合的贝叶斯平滑转化率\n # 探索数据发现:cellular+高转化月份=49.4%, unknown+低转化月份=3.9%\n # 差异巨大,说明联系方式与月份有强交互效应\n \n stats = df.groupby(['contact', 'month'])['y'].agg(['count', 'mean']).reset_index()\n global_mean = df['y'].mean()\n alpha = 15 # 较小先验强度,保留组合差异\n \n stats['smoothed_rate'] = (\n (stats['count'] * stats['mean'] + alpha * global_mean) / \n (stats['count'] + alpha)\n )\n \n # 步骤2: 将平滑转化率映射回原始数据\n lookup = stats.set_index(['contact', 'month'])['smoothed_rate'].to_dict()\n keys = list(zip(df['contact'], df['month']))\n result['contact_month_synergy'] = [lookup.get(k, global_mean) for k in keys]\n \n return result[['row_id', 'contact_month_synergy']]\n"
85
+ }
86
+ ]
outputs/features/knowfeat_ablation/bank_marketing_rules_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c209220ce245ed001e21c641643abcc18f382d8c411b7ac3e2d3a68c5cf14321
3
+ size 2219729
outputs/features/knowfeat_ablation/blood_transfusion_expert_generic_features.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "rf_ratio_score",
4
+ "dimensions": [
5
+ "RFM特征",
6
+ "比率特征",
7
+ "交互特征"
8
+ ],
9
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_rf_ratio_score(df):\n result = df[['row_id']].copy()\n # Recency/Frequency 比值 - 越低越好(最近献血且频次高)\n # 使用log变换处理长尾分布\n rf_ratio = df['Recency'] / (df['Frequency'] + 1e-10)\n result['rf_ratio_score'] = np.log1p(rf_ratio)\n return result"
10
+ },
11
+ {
12
+ "name": "avg_donation_interval",
13
+ "dimensions": [
14
+ "RFM特征",
15
+ "间隔特征",
16
+ "行为模式"
17
+ ],
18
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_avg_donation_interval(df):\n result = df[['row_id']].copy()\n # 平均献血间隔 = (Time - Recency) / (Frequency - 1)\n # 对于Frequency=1的情况,无法计算间隔,设为NaN(首次献血者)\n interval = np.where(\n df['Frequency'] > 1,\n (df['Time'] - df['Recency']) / (df['Frequency'] - 1),\n np.nan\n )\n result['avg_donation_interval'] = interval\n return result"
19
+ },
20
+ {
21
+ "name": "habit_formed_flag",
22
+ "dimensions": [
23
+ "RFM特征",
24
+ "行为习惯",
25
+ "二元特征"
26
+ ],
27
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_habit_formed_flag(df):\n result = df[['row_id']].copy()\n # 献血>=4次的人形成稳定献血习惯 (RULE_004, EXP_04)\n result['habit_formed_flag'] = (df['Frequency'] >= 4).astype(int)\n return result"
28
+ },
29
+ {
30
+ "name": "long_no_donation_flag",
31
+ "dimensions": [
32
+ "行为模式"
33
+ ],
34
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_long_no_donation_flag(df):\n result = df[['row_id']].copy()\n # 步骤1: 根据RULE_003(流失预警),超过12个月未献血且总频次<3为流失风险\n # 但仅使用Recency>12作为长期未献血的信号,正类中仅12.4%属于此群体,负类中40.7%\n result['long_no_donation_flag'] = (df['Recency'] > 12).astype(int)\n return result"
35
+ },
36
+ {
37
+ "name": "active_donor_flag",
38
+ "dimensions": [
39
+ "行为模式"
40
+ ],
41
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_active_donor_flag(df):\n result = df[['row_id']].copy()\n # 步骤1: 根据RULE_005(活跃献血者),献血频率(Frequency/Time)超过0.3次/月且最近6个月内献过血\n freq_rate = df['Frequency'] / df['Time'].clip(lower=1)\n # 步骤2: 同时满足两个条件:频率>0.3次/月 且 Recency<=6\n result['active_donor_flag'] = ((freq_rate > 0.3) & (df['Recency'] <= 6)).astype(int)\n return result"
42
+ }
43
+ ]
outputs/features/knowfeat_ablation/blood_transfusion_expert_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2dfa6c201f05c3e7a83f9e6b284fe9fb77996eab1fd90abdb183cbea4e6b914
3
+ size 26632
outputs/features/knowfeat_ablation/blood_transfusion_indicators_generic_features.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "rfm_score",
4
+ "dimensions": [
5
+ "RFM特征"
6
+ ],
7
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_rfm_score(df):\n result = pd.DataFrame()\n result['row_id'] = df['row_id']\n \n # Step 1: Normalize Recency (lower is better) - invert so higher score = better\n # Recency ranges 0-74, we want low recency to give high score\n max_recency = df['Recency'].max()\n recency_score = 1 - (df['Recency'] / max_recency) # 0 to 1, higher = more recent\n \n # Step 2: Normalize Frequency (higher is better)\n max_freq = df['Frequency'].max()\n freq_score = df['Frequency'] / max_freq # 0 to 1, higher = more frequent\n \n # Step 3: Combine into RFM score (weighted: Recency is strongest predictor)\n # IND_01: Recency is strongest predictor in RFM model\n # IND_02: Frequency is second strongest\n # EXP_01: Based on RFM framework from Taiwan blood center\n result['rfm_score'] = (0.6 * recency_score + 0.4 * freq_score)\n \n return result"
8
+ },
9
+ {
10
+ "name": "rfm_best_segment",
11
+ "dimensions": [
12
+ "RFM特征"
13
+ ],
14
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_rfm_best_segment(df):\n result = pd.DataFrame()\n result['row_id'] = df['row_id']\n \n # Step 1: Create binary indicator for best RFM segment\n # RULE_001: Recency <= 6 AND Frequency >= 5 = best donors\n result['rfm_best_segment'] = ((df['Recency'] <= 6) & (df['Frequency'] >= 5)).astype(int)\n \n return result"
15
+ },
16
+ {
17
+ "name": "active_donor_segment",
18
+ "dimensions": [
19
+ "RFM特征"
20
+ ],
21
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_active_donor_segment(df):\n result = pd.DataFrame()\n result['row_id'] = df['row_id']\n \n # Step 1: Calculate donation frequency rate\n freq_rate = df['Frequency'] / df['Time']\n \n # Step 2: Create binary indicator for active donor\n # RULE_005: Frequency/Time > 0.3 AND Recency <= 6\n result['active_donor_segment'] = ((freq_rate > 0.3) & (df['Recency'] <= 6)).astype(int)\n \n return result"
22
+ },
23
+ {
24
+ "name": "avg_donation_interval",
25
+ "dimensions": [
26
+ "RFM特征"
27
+ ],
28
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_avg_donation_interval(df):\n result = pd.DataFrame()\n result['row_id'] = df['row_id']\n \n # Step 1: Calculate average interval between donations\n # IND_06: (Time - Recency) / (Frequency - 1) approximates average interval\n # Only valid for Frequency > 1\n active_window = df['Time'] - df['Recency']\n denom = df['Frequency'] - 1\n \n # For Frequency == 1, set interval to Time (total time since first donation)\n # as there's only one donation\n result['avg_donation_interval'] = np.where(\n denom > 0,\n active_window / denom,\n df['Time'] # For first-time donors, use total time\n )\n \n return result"
29
+ },
30
+ {
31
+ "name": "freq_active_product_log",
32
+ "dimensions": [
33
+ "行为模式"
34
+ ],
35
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_freq_active_product_log(df):\n result = pd.DataFrame()\n result['row_id'] = df['row_id']\n \n # Step 1: Calculate active window = Time - Recency\n # IND_10: 活跃窗口反映了持续献血的时间长度\n active_window = df['Time'] - df['Recency']\n \n # Step 2: Multiply Frequency by active window\n # This captures the total \"donation exposure\" - \n # high frequency over a long active period = committed donor\n # Low values = either infrequent or short active period\n product = df['Frequency'] * active_window\n \n # Step 3: Apply log1p to stabilize the distribution\n # The product can range from 0 to large values (50*98=4900)\n result['freq_active_product_log'] = np.log1p(product)\n \n return result\n"
36
+ }
37
+ ]
outputs/features/knowfeat_ablation/blood_transfusion_indicators_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:753c0e0f3ce3c34bedb9272d4ab5d48599bcae517475ff19e8fd7cfb840bf208
3
+ size 36636
outputs/features/knowfeat_ablation/blood_transfusion_rules_generic_features.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "active_score",
4
+ "dimensions": [
5
+ "RFM特征",
6
+ "活跃度评分"
7
+ ],
8
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_active_score(df):\n result = df[['row_id']].copy()\n # 步骤1: 计算献血频率密度 = Frequency / (Time + 1)\n freq_density = df['Frequency'] / (df['Time'] + 1)\n # 步骤2: 创建最近献血标志 (Recency <= 6)\n recent_flag = (df['Recency'] <= 6).astype(int)\n # 步骤3: 计算活跃评分 = 献血频率密度 × 最近献血标志\n result['active_score'] = freq_density * recent_flag\n return result"
9
+ },
10
+ {
11
+ "name": "avg_donation_interval",
12
+ "dimensions": [
13
+ "RFM特征",
14
+ "献血间隔"
15
+ ],
16
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_avg_donation_interval(df):\n result = df[['row_id']].copy()\n # 步骤1: 基于IND_06,计算平均献血间隔\n # 活跃窗口 = Time - Recency(最早到最近一次献血的跨度)\n active_window = df['Time'] - df['Recency']\n # 献血次数间隔数 = Frequency - 1\n intervals = df['Frequency'] - 1\n # 步骤2: 计算平均间隔,处理Frequency=1的特殊情况\n result['avg_donation_interval'] = np.where(\n intervals > 0,\n active_window / intervals,\n 0.0 # 仅献过一次血,间隔设为0\n )\n return result"
17
+ },
18
+ {
19
+ "name": "new_recent",
20
+ "dimensions": [
21
+ "RFM特征",
22
+ "首次献血"
23
+ ],
24
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_new_recent(df):\n result = df[['row_id']].copy()\n # 步骤1: 基于IND_09,识别首次献血者 (Frequency == 1)\n is_first_time = (df['Frequency'] == 1).astype(int)\n # 步骤2: 结合Recency,对首次献血者按最近性加权\n # 首次献血且Recency短的人更可能再次献血\n result['new_recent'] = is_first_time * (1.0 / (df['Recency'] + 1))\n return result"
25
+ },
26
+ {
27
+ "name": "rfm_best_segment",
28
+ "dimensions": [
29
+ "行为模式"
30
+ ],
31
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_rfm_best_segment(df):\n result = df[['row_id']].copy()\n # 步骤1: 基于RULE_001,创建RFM最佳细分标志\n # Recency <= 6(最近6个月内献过血)AND Frequency >= 5(高频献血者)\n result['rfm_best_segment'] = ((df['Recency'] <= 6) & (df['Frequency'] >= 5)).astype(int)\n return result"
32
+ },
33
+ {
34
+ "name": "churn_warning_flag",
35
+ "dimensions": [
36
+ "行为模式"
37
+ ],
38
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_churn_warning_flag(df):\n result = df[['row_id']].copy()\n # 步骤1: 基于RULE_003,创建流失预警标志\n # 超过12个月未献血(Recency > 12)且总频次<3(Frequency < 3)\n result['churn_warning_flag'] = ((df['Recency'] > 12) & (df['Frequency'] < 3)).astype(int)\n return result"
39
+ },
40
+ {
41
+ "name": "loyal_donor_flag",
42
+ "dimensions": [
43
+ "行为模式"
44
+ ],
45
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_loyal_donor_flag(df):\n result = df[['row_id']].copy()\n # 步骤1: 基于RULE_007,创建长期忠诚献血者标志\n # Time >= 36 (首次献血超过36个月前)\n # Frequency >= 10 (至少献过10次)\n # Recency <= 6 (最近6个月内献过)\n result['loyal_donor_flag'] = ((df['Time'] >= 36) & (df['Frequency'] >= 10) & (df['Recency'] <= 6)).astype(int)\n return result"
46
+ }
47
+ ]
outputs/features/knowfeat_ablation/blood_transfusion_rules_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23c8a6d355ef6261593ea3ee100be14efae88c11808c050e5647f60ef58a5053
3
+ size 25281
outputs/features/knowfeat_ablation/breast_w_expert_generic_features.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "nuclear_composite_score",
4
+ "dimensions": [
5
+ "细胞特征",
6
+ "核特征"
7
+ ],
8
+ "code": "def feature_nuclear_composite_score(df):\n \"\"\"\n 核复合评分:Bare_Nuclei + Bland_Chromatin + Normal_Nucleoli 之和\n 反映核质异常的综合程度\n \"\"\"\n result = df[['row_id']].copy()\n result['nuclear_composite_score'] = (\n df['Bare_Nuclei'].fillna(1) + df['Bland_Chromatin'] + df['Normal_Nucleoli']\n )\n return result"
9
+ },
10
+ {
11
+ "name": "nuclear_bare_clump_interact",
12
+ "dimensions": [
13
+ "核特征"
14
+ ],
15
+ "code": "def feature_nuclear_bare_clump_interact(df):\n import pandas as pd\n result = df[['row_id']].copy()\n bare = df['Bare_Nuclei'].fillna(df['Bare_Nuclei'].median())\n # Bare_Nuclei>=7 且 Clump_Thickness>=7 → 强烈恶性信号\n result['nuclear_bare_clump_interact'] = (\n (bare >= 7).astype(int) & \n (df['Clump_Thickness'] >= 7).astype(int)\n ).astype(int)\n return result"
16
+ },
17
+ {
18
+ "name": "clump_size_ratio",
19
+ "dimensions": [
20
+ "细胞特征"
21
+ ],
22
+ "code": "def feature_clump_size_ratio(df):\n \"\"\"\n 团块厚度与细胞大小比值:Clump_Thickness / (Uniformity_of_Cell_Size + 0.1)\n \n 领域依据:\n - IND_01: 团块厚度反映肿瘤细胞堆积层数,评分越高越恶性\n - IND_02: 细胞大小均匀性反映细胞大小不等(anisocytosis),评分越高越恶性\n - 良性样本中:Clump_Thickness均值2.96,Cell_Size均值1.31,比值约2.26\n - 恶性样本中:Clump_Thickness均值7.19,Cell_Size均值6.58,比值约1.09\n - 比值在良恶性中方向相反,捕获肿瘤架构与细胞异型性的相对关系\n \"\"\"\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 计算团块厚度与细胞大小的比值(加0.1避免除零)\n result['clump_size_ratio'] = df['Clump_Thickness'] / (df['Uniformity_of_Cell_Size'] + 0.1)\n \n return result"
23
+ },
24
+ {
25
+ "name": "mitoses_epi_product",
26
+ "dimensions": [
27
+ "复合指标"
28
+ ],
29
+ "code": "def feature_mitoses_epi_product(df):\n \"\"\"\n 有丝分裂与单上皮细胞大小的乘积:Mitoses * Single_Epithelial_Cell_Size\n 捕获增殖活性与细胞肥大的联合信号\n \n 领域依据:\n - IND_05: 单上皮细胞大小反映细胞肥大,恶性细胞因核浆比增大而整体肥大\n - IND_09: 有丝分裂反映细胞分裂率,>80%样本评分为1\n - 两者组合捕获了增殖活跃且细胞肥大的恶性表型\n - 与核三联征相关性最低(r~0.47),提供高度互补信息\n \"\"\"\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 计算有丝分裂与单上皮细胞大小的乘积\n result['mitoses_epi_product'] = df['Mitoses'] * df['Single_Epithelial_Cell_Size']\n \n return result\n"
30
+ },
31
+ {
32
+ "name": "feature_rank_std",
33
+ "dimensions": [
34
+ "复合指标"
35
+ ],
36
+ "code": "def feature_feature_rank_std(df):\n \"\"\"\n 9个原始特征的百分位排名标准差\n 量化细胞学特征之间的离散程度,基于排名而非原始值\n \n 领域依据:\n - EXP_02: 9个特征之间存在强相关性,但恶性样本中不同特征受影响程度不同\n - 良性样本中所有特征值集中在低分区域,排名差异小,标准差小\n - 恶性样本中特征值分布更分散,排名差异大,标准差大\n - 基于排名的方法对异常值更稳健\n \"\"\"\n import pandas as pd\n import numpy as np\n result = df[['row_id']].copy()\n \n features = ['Clump_Thickness', 'Uniformity_of_Cell_Size', 'Uniformity_of_Cell_Shape', \n 'Marginal_Adhesion', 'Single_Epithelial_Cell_Size', 'Bare_Nuclei', \n 'Bland_Chromatin', 'Normal_Nucleoli', 'Mitoses']\n \n # 计算每个特征的百分位排名\n rank_df = pd.DataFrame()\n for f in features:\n if f == 'Bare_Nuclei':\n rank_df[f] = df['Bare_Nuclei'].fillna(df['Bare_Nuclei'].median()).rank(pct=True)\n else:\n rank_df[f] = df[f].rank(pct=True)\n \n # 计算排名的标准差\n result['feature_rank_std'] = rank_df.std(axis=1)\n \n return result\n"
37
+ },
38
+ {
39
+ "name": "clump_grade",
40
+ "dimensions": [
41
+ "细胞特征"
42
+ ],
43
+ "code": "def feature_clump_grade(df):\n \"\"\"\n Clump_Thickness的3级临床分级\n 基于IND_01的临床阈值:<=4为低风险(0级),5-6为中风险(1级),>=7为高风险(2级)\n \n 领域依据:\n - IND_01: 团块厚度>=5提示恶性,>=7强烈恶性\n - 良性均值2.96,恶性均值7.19,差异倍数2.43x\n - 3级分段比原始值更接近临床决策逻辑\n \"\"\"\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # Clump_Thickness的3级临床分级\n # 0级: <=4 (低风险,良性为主)\n # 1级: 5-6 (中风险,可疑)\n # 2级: >=7 (高风险,强烈恶性)\n result['clump_grade'] = pd.cut(\n df['Clump_Thickness'], \n bins=[0, 4, 6, 10], \n labels=[0, 1, 2]\n ).astype(int)\n \n return result"
44
+ },
45
+ {
46
+ "name": "clump_5",
47
+ "dimensions": [
48
+ "细胞特征"
49
+ ],
50
+ "code": "def feature_clump_5(df):\n \"\"\"\n Clump_Thickness >= 5 的二元指示变量\n 基于IND_01的临床阈值:团块厚度>=5提示恶性\n \n 领域依据:\n - IND_01: 团块厚度>=5提示恶性,良性均值2.96,恶性均值7.19\n - 数据中341/444良性样本Clump<5,208/239恶性样本Clump>=5\n - 与核复合评分相关性仅0.566,提供高度独立的信号\n \"\"\"\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # Clump_Thickness >= 5 的二元指示\n result['clump_5'] = (df['Clump_Thickness'] >= 5).astype(int)\n \n return result"
51
+ },
52
+ {
53
+ "name": "cell_median_min_ratio",
54
+ "dimensions": [
55
+ "细胞特征"
56
+ ],
57
+ "code": "def feature_cell_median_min_ratio(df):\n \"\"\"\n 细胞特征中位数与最小值的比率:median(5个细胞特征) / min(5个细胞特征)\n 量化细胞学特征之间的不一致程度,捕获不同细胞异常维度的相对差异\n \n 领域依据:\n - EXP_02: 9个特征之间存在强相关性,但恶性样本中不同特征受影响程度不同\n - 良性样本中所有细胞特征集中在低分区域(1-3),中位数接近最小值,比率接近1\n - 恶性样本中不同特征受影响程度不同,中位数明显高于最小值,比率>1\n - 与Cell_Size相关性0.41,与Bare_Nuclei相关性0.31,提供高度互补信息\n \"\"\"\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n cell_features = ['Clump_Thickness', 'Uniformity_of_Cell_Size', 'Uniformity_of_Cell_Shape', \n 'Marginal_Adhesion', 'Single_Epithelial_Cell_Size']\n \n # 计算5个细胞特征的中位数和最小值\n median_vals = df[cell_features].median(axis=1)\n min_vals = df[cell_features].min(axis=1)\n \n # 计算中位数与最小值的比率(加小常数避免除零)\n result['cell_median_min_ratio'] = median_vals / (min_vals + 0.001)\n \n return result"
58
+ },
59
+ {
60
+ "name": "nuclear_cellular_absdiff",
61
+ "dimensions": [
62
+ "复合指标"
63
+ ],
64
+ "code": "def feature_nuclear_cellular_absdiff(df):\n \"\"\"\n 核特征与细胞特征的原始分绝对值差:\n |(Bare_Nuclei + Bland_Chromatin + Normal_Nucleoli) - \n (Clump_Thickness + Uniformity_of_Cell_Size + Uniformity_of_Cell_Shape + \n Marginal_Adhesion + Single_Epithelial_Cell_Size + Mitoses)|\n \n 量化核异常与细胞异常的不一致程度。当核特征显著高于细胞特征时,\n 提示核异型性为主导的恶性模式;反之则提示细胞架构异常为主导。\n \"\"\"\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 核特征总分\n nuclear_total = (df['Bare_Nuclei'].fillna(1) + \n df['Bland_Chromatin'] + \n df['Normal_Nucleoli'])\n \n # 细胞特征总分\n cellular_total = (df['Clump_Thickness'] + \n df['Uniformity_of_Cell_Size'] + \n df['Uniformity_of_Cell_Shape'] + \n df['Marginal_Adhesion'] + \n df['Single_Epithelial_Cell_Size'] + \n df['Mitoses'])\n \n # 绝对值差\n result['nuclear_cellular_absdiff'] = np.abs(nuclear_total - cellular_total)\n \n return result"
65
+ },
66
+ {
67
+ "name": "nuclear_cellular_ratio",
68
+ "dimensions": [
69
+ "复合指标"
70
+ ],
71
+ "code": "def feature_nuclear_cellular_ratio(df):\n \"\"\"\n 核特征与细胞特征的原始分比值:(Bare_Nuclei + Bland_Chromatin + Normal_Nucleoli) / \n (Clump_Thickness + Uniformity_of_Cell_Size + Uniformity_of_Cell_Shape + \n Marginal_Adhesion + Single_Epithelial_Cell_Size + Mitoses + 0.1)\n \n 量化核异常相对于细胞异常的相对强度。比值>1表示核异常占主导,\n 比值<1表示细胞异常占主导。恶性样本中核特征通常相对更突出。\n \"\"\"\n import pandas as pd\n import numpy as np\n \n result = df[['row_id']].copy()\n \n # 核特征总分\n nuclear_total = (df['Bare_Nuclei'].fillna(1) + \n df['Bland_Chromatin'] + \n df['Normal_Nucleoli'])\n \n # 细胞特征总分(加0.1避免除零)\n cellular_total = (df['Clump_Thickness'] + \n df['Uniformity_of_Cell_Size'] + \n df['Uniformity_of_Cell_Shape'] + \n df['Marginal_Adhesion'] + \n df['Single_Epithelial_Cell_Size'] + \n df['Mitoses'] + 0.1)\n \n # 比值\n result['nuclear_cellular_ratio'] = nuclear_total / cellular_total\n \n return result"
72
+ }
73
+ ]
outputs/features/knowfeat_ablation/breast_w_expert_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b70379c07de8e1bb1c1fd7fcc166b15d02d9f8f0012e7454fe4209da49ed6f3
3
+ size 66545
outputs/features/knowfeat_ablation/breast_w_indicators_generic_features.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "nuclear_composite_score",
4
+ "dimensions": [
5
+ "细胞特征"
6
+ ],
7
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_nuclear_composite_score(df):\n \"\"\"\n 核复合评分:基于EXP_08和EXP_04,组合Bare_Nuclei, Bland_Chromatin, Normal_Nucleoli三个核特征。\n 核三联征(染色质模式+核仁突出度+核膜不规则性)构成大多数细胞学分级系统的基础。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 计算核复合评分 = Bare_Nuclei + Bland_Chromatin + Normal_Nucleoli\n result['nuclear_composite_score'] = (\n df['Bare_Nuclei'] + \n df['Bland_Chromatin'] + \n df['Normal_Nucleoli']\n )\n \n return result\n"
8
+ },
9
+ {
10
+ "name": "mitosis_size_interaction",
11
+ "dimensions": [
12
+ "细胞特征"
13
+ ],
14
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_mitosis_size_interaction(df):\n \"\"\"\n 有丝分裂-细胞大小交互:基于RULE_006,Mitoses>=3 AND Cell_Size_Uniformity>=4 提示高级别恶性。\n 同时结合EXP_05,Mitoses是最偏态的特征,其诊断价值在于与其它特征组合。\n 使用乘法交互捕获协同效应。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 交互特征:Mitoses * Cell_Size_Uniformity\n # 当两者都高时,乘积会显著放大信号\n result['mitosis_size_interaction'] = df['Mitoses'] * df['Uniformity_of_Cell_Size']\n \n return result\n"
15
+ },
16
+ {
17
+ "name": "cell_composite_score",
18
+ "dimensions": [
19
+ "细胞特征"
20
+ ],
21
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_cell_composite_score(df):\n \"\"\"\n 细胞复合评分:基于EXP_08,组合Clump_Thickness, Uniformity_of_Cell_Size, \n Uniformity_of_Cell_Shape, Marginal_Adhesion四个细胞特征的总和。\n 这些特征共同捕获肿瘤架构、侵袭潜力和细胞异型性。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 计算细胞复合评分 = Clump_Thickness + Cell_Size + Cell_Shape + Marginal_Adhesion\n result['cell_composite_score'] = (\n df['Clump_Thickness'] + \n df['Uniformity_of_Cell_Size'] + \n df['Uniformity_of_Cell_Shape'] + \n df['Marginal_Adhesion']\n )\n \n return result\n"
22
+ },
23
+ {
24
+ "name": "nuclear_cytoplasmic_ratio_index",
25
+ "dimensions": [
26
+ "复合指标"
27
+ ],
28
+ "code": "import pandas as pd\nimport numpy as np\n\ndef feature_nuclear_cytoplasmic_ratio_index(df):\n \"\"\"\n 核浆比指数:基于IND_10,通过Cell_Size_Uniformity(反映核大小变异)与\n Single_Epithelial_Cell_Size(反映细胞整体大小)的比值来近似核浆比(N:C ratio)。\n 恶性细胞特征性地核浆比升高(>0.7)。使用比值而非求和能捕获相对变化——\n 当核增大快于细胞整体增大时比值升高,这是恶性转化的标志。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 核浆比近似 = Cell_Size_Uniformity / Single_Epithelial_Cell_Size\n # 分子:核大小变异(核增大程度)\n # 分母:细胞整体大小\n # 比值高 = 核相对增大 = 高核浆比 = 恶性特征\n size = df['Uniformity_of_Cell_Size'].values.astype(float)\n epi = df['Single_Epithelial_Cell_Size'].values.astype(float)\n \n # 避免除零,加0.1平滑\n ratio = size / (epi + 0.1)\n \n result['nuclear_cytoplasmic_ratio_index'] = ratio\n \n return result\n"
29
+ }
30
+ ]
outputs/features/knowfeat_ablation/breast_w_indicators_knowfeat_features.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70047007481251f4e6dfb2cbb402ad3d90b50a4916014a9953ec77943c0c1f62
3
+ size 22110
outputs/features/knowfeat_ablation/breast_w_rules_generic_features.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "nuclear_triad_score",
4
+ "dimensions": [
5
+ "细胞特征"
6
+ ],
7
+ "code": "def feature_nuclear_triad_score(df):\n \"\"\"\n 核三联征评分:Bare_Nuclei + Bland_Chromatin + Normal_Nucleoli 的加权组合\n 基于EXP_04和EXP_08:核特征(Bare_Nuclei, Bland_Chromatin, Normal_Nucleoli) \n 构成细胞学分级系统的基础,是最可靠的诊断指标组合。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 核三联征原始求和\n result['nuclear_triad_score'] = (\n df['Bare_Nuclei'].fillna(1) + \n df['Bland_Chromatin'] + \n df['Normal_Nucleoli']\n )\n \n return result\n"
8
+ },
9
+ {
10
+ "name": "nuclear_rule_003_strict_flag",
11
+ "dimensions": [
12
+ "核特征"
13
+ ],
14
+ "code": "def feature_nuclear_rule_003_strict_flag(df):\n \"\"\"\n 严格三重核特征规则标志:基于RULE_003的调整版本。\n Bland_Chromatin>=6 AND Normal_Nucleoli>=5 AND Bare_Nuclei>=5 → 恶性\n 使用更严格的阈值以降低与基线特征的相关性(最大相关性<0.64)。\n 该规则捕获核三联征同时高度异常的模式,特异度极高。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 处理Bare_Nuclei缺失值\n bare_nuclei = df['Bare_Nuclei'].fillna(1)\n \n # 严格三重核特征规则\n result['nuclear_rule_003_strict_flag'] = (\n (df['Bland_Chromatin'] >= 6) & \n (df['Normal_Nucleoli'] >= 5) & \n (bare_nuclei >= 5)\n ).astype(int)\n \n return result\n"
15
+ },
16
+ {
17
+ "name": "cell_feature_consistency",
18
+ "dimensions": [
19
+ "细胞特征"
20
+ ],
21
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_cell_feature_consistency(df):\n \"\"\"\n 细胞特征一致性指数:衡量5个细胞特征(Clump_Thickness, Cell_Size, Cell_Shape, \n Marginal_Adhesion, Single_Epithelial_Cell_Size)之间的一致性程度。\n \n 基于EXP_02(细胞特征间存在强相关性,恶性倾向同时影响多个特征)和\n EXP_04(核特征比细胞特征更可靠,但细胞特征提供互补信息)设计。\n \n 计算逻辑:取5个细胞特征的均值/标准差比值(即信噪比的倒数形式)。\n 良性样本中细胞特征值都低且相对集中(一致性高),\n 恶性样本中细胞特征值都高但某些特征升高更快导致相对分散(一致性低)。\n \"\"\"\n result = df[['row_id']].copy()\n \n cell_cols = ['Clump_Thickness', 'Uniformity_of_Cell_Size', 'Uniformity_of_Cell_Shape', \n 'Marginal_Adhesion', 'Single_Epithelial_Cell_Size']\n \n # 计算5个细胞特征的均值和标准差\n cell_mean = df[cell_cols].mean(axis=1)\n cell_std = df[cell_cols].std(axis=1)\n \n # 变异系数 = std / mean,取倒数得到一致性指数\n # 加0.1避免除零,加小值平滑\n consistency = cell_mean / (cell_std + 0.1)\n \n result['cell_feature_consistency'] = consistency\n \n return result"
22
+ },
23
+ {
24
+ "name": "nuclear_dominance_index",
25
+ "dimensions": [
26
+ "核特征"
27
+ ],
28
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_nuclear_dominance_index(df):\n \"\"\"\n 核特征主导模式指数:衡量核特征中哪个特征占主导地位及其主导程度。\n \n 在良性样本中,Bland_Chromatin是核特征中的\"主导者\"(均值最高2.08);\n 在恶性样本中,Bare_Nuclei是核特征中的\"主导者\"(均值最高7.63)。\n 这种\"主导模式转换\"是强诊断信号。\n \n 计算逻辑:\n 1. 找出每个样本中核特征(Bare_Nuclei, Bland_Chromatin, Normal_Nucleoli)的最大值和次大值\n 2. 计算主导幅度 = 最大值 - 次大值\n 3. 确定主导方向:Bare_Nuclei主导→+1(恶性),Bland_Chromatin主导→-1(良性),Normal_Nucleoli主导→+0.5(弱恶性)\n 4. 主导模式指数 = 主导方向 × 主导幅度\n \"\"\"\n result = df[['row_id']].copy()\n \n bare = df['Bare_Nuclei'].fillna(1)\n bland = df['Bland_Chromatin']\n normal = df['Normal_Nucleoli']\n \n # 找出每个样本中核特征的最大值和次大值\n nuclear_vals = pd.concat([bare, bland, normal], axis=1)\n nuclear_max = nuclear_vals.max(axis=1)\n nuclear_second = nuclear_vals.apply(lambda x: sorted(x)[-2], axis=1)\n \n # 主导幅度 = 最大值 - 次大值\n dominance_magnitude = nuclear_max - nuclear_second\n \n # 主导方向\n def get_dominance_direction(row):\n vals = {\n 'bare': row['Bare_Nuclei'] if not pd.isna(row['Bare_Nuclei']) else 1,\n 'bland': row['Bland_Chromatin'],\n 'normal': row['Normal_Nucleoli']\n }\n max_val = max(vals.values())\n max_keys = [k for k, v in vals.items() if v == max_val]\n \n if len(max_keys) > 1:\n return 0 # 平局\n \n if max_keys[0] == 'bare':\n return 1.0 # Bare_Nuclei主导 → 恶性信号\n elif max_keys[0] == 'bland':\n return -1.0 # Bland_Chromatin主导 → 良性信号\n else:\n return 0.5 # Normal_Nucleoli主导 → 弱恶性信号\n \n dominance_direction = df.apply(get_dominance_direction, axis=1)\n \n # 核特征主导模式指数 = 主导方向 × 主导幅度\n result['nuclear_dominance_index'] = dominance_direction * dominance_magnitude\n \n return result\n"
29
+ },
30
+ {
31
+ "name": "nuclear_cellular_ratio",
32
+ "dimensions": [
33
+ "复合指标"
34
+ ],
35
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_nuclear_cellular_ratio(df):\n \"\"\"\n 核细胞比值:核特征(Bare_Nuclei+Bland_Chromatin+Normal_Nucleoli)与\n 细胞特征(Clump_Thickness+Cell_Size+Cell_Shape+Marginal_Adhesion+Single_Epi)的比值。\n \n 基于EXP_04(核特征比细胞特征更可靠)和EXP_10(核浆比是基本指标)设计。\n 恶性样本中核特征升高速度比细胞特征更快,导致比值升高。\n 良性样本中两者都低,比值接近1。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 核特征总和\n nuclear_sum = df['Bare_Nuclei'].fillna(1) + df['Bland_Chromatin'] + df['Normal_Nucleoli']\n \n # 细胞特征总和\n cellular_sum = (df['Clump_Thickness'] + df['Uniformity_of_Cell_Size'] + \n df['Uniformity_of_Cell_Shape'] + df['Marginal_Adhesion'] + \n df['Single_Epithelial_Cell_Size'])\n \n # 比值(加0.1避免除零)\n result['nuclear_cellular_ratio'] = nuclear_sum / (cellular_sum + 0.1)\n \n return result\n"
36
+ },
37
+ {
38
+ "name": "nuclear_cell_diff",
39
+ "dimensions": [
40
+ "复合指标"
41
+ ],
42
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_nuclear_cell_diff(df):\n \"\"\"\n 核细胞差值:核特征(Bare_Nuclei+Bland_Chromatin+Normal_Nucleoli)与\n 细胞特征(Clump_Thickness+Cell_Size+Cell_Shape+Marginal_Adhesion+Single_Epi)的差值。\n \n 基于EXP_04(核特征可靠性)和IND_10(核浆比)设计。\n 恶性样本中核特征总和远高于细胞特征总和,差值大且为正;\n 良性样本中两者都低,差值接近0或为负。\n \"\"\"\n result = df[['row_id']].copy()\n \n # 核特征总和\n nuclear_sum = df['Bare_Nuclei'].fillna(1) + df['Bland_Chromatin'] + df['Normal_Nucleoli']\n \n # 细胞特征总和\n cellular_sum = (df['Clump_Thickness'] + df['Uniformity_of_Cell_Size'] + \n df['Uniformity_of_Cell_Shape'] + df['Marginal_Adhesion'] + \n df['Single_Epithelial_Cell_Size'])\n \n # 差值\n result['nuclear_cell_diff'] = nuclear_sum - cellular_sum\n \n return result\n"
43
+ },
44
+ {
45
+ "name": "feature_cv_index",
46
+ "dimensions": [
47
+ "复合指标"
48
+ ],
49
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_cv_index(df):\n \"\"\"\n 特征变异系数:9个特征的标准差除以均值。\n \n 基于EXP_02(特征间存在强相关性,恶性倾向同时影响多个特征)和\n EXP_08(特征工程建议)设计。\n \n 良性样本中所有特征值都低且集中(均值低,标准差低),\n 恶性样本中特征值整体升高但不同特征升高幅度不同(均值高,标准差更高),\n 导致变异系数在良恶性间有差异。\n \"\"\"\n result = df[['row_id']].copy()\n \n feature_cols = ['Clump_Thickness', 'Uniformity_of_Cell_Size', 'Uniformity_of_Cell_Shape', \n 'Marginal_Adhesion', 'Single_Epithelial_Cell_Size', 'Bare_Nuclei', \n 'Bland_Chromatin', 'Normal_Nucleoli', 'Mitoses']\n \n # 处理Bare_Nuclei缺失值\n df_clean = df[feature_cols].copy()\n df_clean['Bare_Nuclei'] = df_clean['Bare_Nuclei'].fillna(1)\n \n # 计算标准差和均值\n std_vals = df_clean.std(axis=1)\n mean_vals = df_clean.mean(axis=1)\n \n # 变异系数 = std / mean,加0.1避免除零\n result['feature_cv_index'] = std_vals / (mean_vals + 0.1)\n \n return result\n"
50
+ },
51
+ {
52
+ "name": "top3_bottom3_ratio",
53
+ "dimensions": [
54
+ "复合指标"
55
+ ],
56
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_top3_bottom3_ratio(df):\n \"\"\"\n 前3大与后3小特征比值:9个特征中最大的3个均值除以最小的3个均值。\n \n 基于RULE_008(任意3个以上特征>=7或总分>=55→恶性)和\n RULE_004(所有特征<=3→良性)设计。\n \n 良性样本中所有特征值都低且接近,前3/后3比值接近1;\n 恶性样本中部分特征显著升高(如Bare_Nuclei, Cell_Size),\n 而其他特征(如Mitoses)可能仍较低,导致比值增大。\n \"\"\"\n result = df[['row_id']].copy()\n \n feature_cols = ['Clump_Thickness', 'Uniformity_of_Cell_Size', 'Uniformity_of_Cell_Shape', \n 'Marginal_Adhesion', 'Single_Epithelial_Cell_Size', 'Bare_Nuclei', \n 'Bland_Chromatin', 'Normal_Nucleoli', 'Mitoses']\n \n # 处理Bare_Nuclei缺失值\n df_clean = df[feature_cols].copy()\n df_clean['Bare_Nuclei'] = df_clean['Bare_Nuclei'].fillna(1)\n \n # 对每行排序\n sorted_vals = np.sort(df_clean.values, axis=1)\n \n # 前3大(最大的3个)均值\n top3_mean = np.mean(sorted_vals[:, -3:], axis=1)\n \n # 后3小(最小的3个)均值\n bottom3_mean = np.mean(sorted_vals[:, :3], axis=1)\n \n # 比值\n result['top3_bottom3_ratio'] = top3_mean / (bottom3_mean + 0.1)\n \n return result\n"
57
+ },
58
+ {
59
+ "name": "clump_adhesion_invasion_score",
60
+ "dimensions": [
61
+ "复合指标"
62
+ ],
63
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_clump_adhesion_invasion_score(df):\n \"\"\"\n 团块-粘附侵袭评分:基于RULE_005的连续化版本。\n RULE_005: Clump_Thickness>=6 AND Marginal_Adhesion>=5 → 恶性(侵袭性癌)\n \n 使用连续评分替代二元规则:当两者都超过阈值时,计算(Clump-6)*(Adhesion-5);\n 当只有一个超过阈值时,计算半值;否则为0。\n 该特征捕获了肿瘤侵袭潜力的梯度。\n \"\"\"\n result = df[['row_id']].copy()\n \n clump = df['Clump_Thickness']\n adhesion = df['Marginal_Adhesion']\n \n # 两者都超过阈值:完全激活\n both_high = (clump >= 6) & (adhesion >= 5)\n \n # 只有一个超过阈值:半激活\n one_high = ((clump >= 6) & (adhesion < 5)) | ((clump < 6) & (adhesion >= 5))\n \n # 评分计算\n score = np.where(\n both_high,\n (clump - 6) * (adhesion - 5), # 两者都高:乘积\n np.where(\n one_high,\n 0.5 * np.maximum(clump - 6, adhesion - 5), # 单高:半值\n 0 # 都不高:0\n )\n )\n \n result['clump_adhesion_invasion_score'] = score\n \n return result\n"
64
+ },
65
+ {
66
+ "name": "nuclear_mitosis_interaction",
67
+ "dimensions": [
68
+ "核特征"
69
+ ],
70
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_nuclear_mitosis_interaction(df):\n \"\"\"\n 核-有丝分裂交互:核特征总和与Mitoses的乘积。\n \n 基于EXP_05(Mitoses是最偏态的特征,与核特征相关性低)和\n RULE_006(有丝分裂分级规则:Mitoses>=3且核特征异常→高级别恶性)设计。\n \n 核特征与Mitoses的相关性仅0.43,提供互补信息。\n 良性样本中两者都低(核总和~4.7, Mitoses~1.07),乘积小;\n 恶性样本中核特征高(总和~19.5)且Mitoses可能升高(均值2.6),乘积大。\n \"\"\"\n result = df[['row_id']].copy()\n \n bare = df['Bare_Nuclei'].fillna(1)\n \n # 核特征总和\n nuclear_sum = bare + df['Bland_Chromatin'] + df['Normal_Nucleoli']\n \n # 核特征与Mitoses的乘积\n result['nuclear_mitosis_interaction'] = nuclear_sum * df['Mitoses']\n \n return result\n"
71
+ },
72
+ {
73
+ "name": "clump_pleomorphism_diff",
74
+ "dimensions": [
75
+ "细胞特征"
76
+ ],
77
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_clump_pleomorphism_diff(df):\n \"\"\"\n 团块-多形性差异:Clump_Thickness与细胞大小形状均值的差值。\n \n 基于IND_01(团块厚度:差异倍数2.43x,反映细胞堆积程度)和\n IND_02+IND_03(细胞大小和形状均匀性:差异倍数5.04x和4.64x,反映细胞多形性)设计。\n \n 在良性样本中,Clump_Thickness(均值2.96)高于Cell_Size(均值1.31)和Cell_Shape(均值1.41),\n 差值为正且较大(均值1.60);\n 在恶性样本中,Clump_Thickness(均值7.19)虽然高,但Size(均值6.58)和Shape(均值6.56)\n 几乎追平,差值变小(均值0.62)。\n 该特征捕获了团块堆积程度与细胞多形性之间的差异——良性中团块占主导,恶性中多形性占主导。\n \"\"\"\n result = df[['row_id']].copy()\n \n clump = df['Clump_Thickness']\n cell_size = df['Uniformity_of_Cell_Size']\n cell_shape = df['Uniformity_of_Cell_Shape']\n \n # 团块厚度减去细胞大小和形状的均值\n pleomorphism_mean = (cell_size + cell_shape) / 2.0\n result['clump_pleomorphism_diff'] = clump - pleomorphism_mean\n \n return result"
78
+ },
79
+ {
80
+ "name": "nuclear_skewness_indicator",
81
+ "dimensions": [
82
+ "核特征"
83
+ ],
84
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_nuclear_skewness_indicator(df):\n \"\"\"\n 核特征偏度指标:三个核特征(Bare_Nuclei, Bland_Chromatin, Normal_Nucleoli)的均值与中位数之差。\n \n 基于EXP_02(核特征之间存在中度相关性,但各特征在良恶性中的变化速率不同:\n Bare_Nuclei差异倍数5.66x,Normal_Nucleoli差异倍数4.64x,Bland_Chromatin差异倍数2.87x)和\n EXP_03(Bare_Nuclei良性中位数1,恶性中位数10,分布极度右偏)设计。\n \n 在良性样本中,三个核特征值都低且接近1,均值略高于中位���(均值0.30);\n 在恶性样本中,Bare_Nuclei(中位数10)常远高于Bland_Chromatin(中位数7)和\n Normal_Nucleoli(中位数6),导致均值低于中位数(均值-0.06)。\n 该特征捕获了核特征分布的不对称性变化。\n \"\"\"\n result = df[['row_id']].copy()\n \n bare = df['Bare_Nuclei'].fillna(1).values\n bland = df['Bland_Chromatin'].values\n nucleoli = df['Normal_Nucleoli'].values\n \n # 每行的均值\n mean_val = (bare + bland + nucleoli) / 3.0\n \n # 每行的中位数\n sorted_vals = np.sort(np.column_stack([bare, bland, nucleoli]), axis=1)\n median_val = sorted_vals[:, 1] # 中位数(排序后中间值)\n \n # 偏度指标:均值 - 中位数\n # 良性中均值>中位数(正偏),恶性中均值<中位数(负偏)\n result['nuclear_skewness_indicator'] = mean_val - median_val\n \n return result\n"
85
+ },
86
+ {
87
+ "name": "clump_marginal_min_dispersion",
88
+ "dimensions": [
89
+ "复合指标"
90
+ ],
91
+ "code": "import numpy as np\nimport pandas as pd\n\ndef feature_clump_marginal_min_dispersion(df):\n \"\"\"\n 团块-粘附弱链离散度:min(Clump_Thickness, Marginal_Adhesion) × |Clump_Thickness - Marginal_Adhesion|。\n \n 基于RULE_005(团块+粘附组合:Clump_Thickness>=6 AND Marginal_Adhesion>=5 → 恶性侵袭性癌)和\n IND_01(团块厚度:差异倍数2.43x)和IND_04(边缘粘附:差异倍数4.15x)设计。\n \n 与clump_adhesion_dispersion(使用max)不同,本特征使用min捕获\"弱链\"信号。\n 良性样本中两者都低,min小且差异小,乘积小;\n 恶性样本中两者都高但Marginal升高更快(差异倍数4.15x vs 2.43x),min和差异都大,乘积大。\n min项捕获\"最弱特征\"的信号,|diff|项捕获\"两者不一致\"的信号。\n 与原始特征的最大相关性仅0.6678(低于0.7阈值),冗余度低。\n \"\"\"\n result = df[['row_id']].copy()\n \n clump = df['Clump_Thickness']\n marginal = df['Marginal_Adhesion']\n \n # min(Clump, Marginal) - 捕获弱链信号(最弱特征决定整体)\n min_val = np.minimum(clump, marginal)\n \n # |Clump - Marginal| - 捕获两者不一致的信号\n abs_diff = np.abs(clump - marginal)\n \n # 离散度 = min × |diff|\n # 良性:两者都低 → 乘积小\n # 恶性:两者都高且差异大 → 乘积大\n result['clump_marginal_min_dispersion'] = min_val * abs_diff\n \n return result\n"
92
+ }
93
+ ]