staran 0.6.0__py3-none-any.whl → 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- staran/__init__.py +10 -0
- staran/tools/__init__.py +5 -5
- staran-1.0.0.dist-info/METADATA +301 -0
- staran-1.0.0.dist-info/RECORD +8 -0
- staran/banks/__init__.py +0 -30
- staran/banks/xinjiang_icbc/__init__.py +0 -90
- staran/engines/__init__.py +0 -65
- staran/engines/base.py +0 -255
- staran/engines/hive.py +0 -163
- staran/engines/spark.py +0 -252
- staran/engines/turing.py +0 -439
- staran/examples/__init__.py +0 -8
- staran/examples/aum_longtail.py +0 -250
- staran/examples/aum_longtail_old.py +0 -487
- staran/features/__init__.py +0 -59
- staran/features/engines.py +0 -284
- staran/features/generator.py +0 -603
- staran/features/manager.py +0 -155
- staran/features/schema.py +0 -193
- staran/models/__init__.py +0 -72
- staran/models/bank_configs.py +0 -269
- staran/models/config.py +0 -271
- staran/models/daifa_models.py +0 -361
- staran/models/registry.py +0 -281
- staran/models/target.py +0 -321
- staran/schemas/__init__.py +0 -27
- staran/schemas/aum/__init__.py +0 -210
- staran/schemas/document_generator.py +0 -350
- staran/tools/document_generator.py +0 -350
- staran-0.6.0.dist-info/METADATA +0 -564
- staran-0.6.0.dist-info/RECORD +0 -33
- {staran-0.6.0.dist-info → staran-1.0.0.dist-info}/WHEEL +0 -0
- {staran-0.6.0.dist-info → staran-1.0.0.dist-info}/licenses/LICENSE +0 -0
- {staran-0.6.0.dist-info → staran-1.0.0.dist-info}/top_level.txt +0 -0
staran/models/registry.py
DELETED
@@ -1,281 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
模型注册和管理模块
|
3
|
-
|
4
|
-
提供模型配置的注册、查询、版本管理等功能
|
5
|
-
"""
|
6
|
-
|
7
|
-
from typing import Dict, Any, List, Optional, Tuple
|
8
|
-
from dataclasses import dataclass
|
9
|
-
from datetime import datetime
|
10
|
-
import json
|
11
|
-
import os
|
12
|
-
|
13
|
-
from .config import ModelConfig
|
14
|
-
from .target import TargetDefinition
|
15
|
-
|
16
|
-
|
17
|
-
@dataclass
|
18
|
-
class ModelEntry:
|
19
|
-
"""模型注册条目"""
|
20
|
-
model_config: ModelConfig
|
21
|
-
target_definition: TargetDefinition
|
22
|
-
registered_at: datetime
|
23
|
-
status: str = "active" # active, inactive, deprecated
|
24
|
-
performance_metrics: Dict[str, float] = None
|
25
|
-
|
26
|
-
def __post_init__(self):
|
27
|
-
if self.performance_metrics is None:
|
28
|
-
self.performance_metrics = {}
|
29
|
-
|
30
|
-
|
31
|
-
class ModelRegistry:
|
32
|
-
"""模型注册表"""
|
33
|
-
|
34
|
-
_models: Dict[str, ModelEntry] = {}
|
35
|
-
_version_history: Dict[str, List[str]] = {} # 模型名称 -> 版本列表
|
36
|
-
|
37
|
-
@classmethod
|
38
|
-
def register(cls, model_config: ModelConfig, target_definition: TargetDefinition) -> str:
|
39
|
-
"""
|
40
|
-
注册一个新模型
|
41
|
-
|
42
|
-
Args:
|
43
|
-
model_config: 模型配置
|
44
|
-
target_definition: 目标变量定义
|
45
|
-
|
46
|
-
Returns:
|
47
|
-
模型的唯一标识符
|
48
|
-
"""
|
49
|
-
model_id = f"{model_config.name}_{model_config.version}"
|
50
|
-
|
51
|
-
# 检查是否已存在
|
52
|
-
if model_id in cls._models:
|
53
|
-
raise ValueError(f"模型 {model_id} 已存在")
|
54
|
-
|
55
|
-
# 创建模型条目
|
56
|
-
entry = ModelEntry(
|
57
|
-
model_config=model_config,
|
58
|
-
target_definition=target_definition,
|
59
|
-
registered_at=datetime.now()
|
60
|
-
)
|
61
|
-
|
62
|
-
# 注册模型
|
63
|
-
cls._models[model_id] = entry
|
64
|
-
|
65
|
-
# 更新版本历史
|
66
|
-
if model_config.name not in cls._version_history:
|
67
|
-
cls._version_history[model_config.name] = []
|
68
|
-
cls._version_history[model_config.name].append(model_config.version)
|
69
|
-
|
70
|
-
print(f"✅ 模型 {model_id} 注册成功")
|
71
|
-
return model_id
|
72
|
-
|
73
|
-
@classmethod
|
74
|
-
def get_model(cls, model_name: str, version: str = None) -> Optional[ModelEntry]:
|
75
|
-
"""
|
76
|
-
获取模型条目
|
77
|
-
|
78
|
-
Args:
|
79
|
-
model_name: 模型名称
|
80
|
-
version: 版本号,如果不指定则返回最新版本
|
81
|
-
|
82
|
-
Returns:
|
83
|
-
模型条目或None
|
84
|
-
"""
|
85
|
-
if version:
|
86
|
-
model_id = f"{model_name}_{version}"
|
87
|
-
return cls._models.get(model_id)
|
88
|
-
else:
|
89
|
-
# 获取最新版本
|
90
|
-
versions = cls._version_history.get(model_name, [])
|
91
|
-
if not versions:
|
92
|
-
return None
|
93
|
-
|
94
|
-
latest_version = max(versions) # 简单的字符串比较,实际应该用版本比较
|
95
|
-
model_id = f"{model_name}_{latest_version}"
|
96
|
-
return cls._models.get(model_id)
|
97
|
-
|
98
|
-
@classmethod
|
99
|
-
def get_model_config(cls, model_name: str, version: str = None) -> Optional[ModelConfig]:
|
100
|
-
"""获取模型配置"""
|
101
|
-
entry = cls.get_model(model_name, version)
|
102
|
-
return entry.model_config if entry else None
|
103
|
-
|
104
|
-
@classmethod
|
105
|
-
def get_target_definition(cls, model_name: str, version: str = None) -> Optional[TargetDefinition]:
|
106
|
-
"""获取目标变量定义"""
|
107
|
-
entry = cls.get_model(model_name, version)
|
108
|
-
return entry.target_definition if entry else None
|
109
|
-
|
110
|
-
@classmethod
|
111
|
-
def list_models(cls) -> List[Dict[str, Any]]:
|
112
|
-
"""列出所有注册的模型"""
|
113
|
-
result = []
|
114
|
-
for model_id, entry in cls._models.items():
|
115
|
-
result.append({
|
116
|
-
'model_id': model_id,
|
117
|
-
'name': entry.model_config.name,
|
118
|
-
'version': entry.model_config.version,
|
119
|
-
'type': entry.model_config.model_type.value,
|
120
|
-
'algorithm': entry.model_config.algorithm.value,
|
121
|
-
'bank_code': entry.model_config.bank_code,
|
122
|
-
'status': entry.status,
|
123
|
-
'registered_at': entry.registered_at.isoformat(),
|
124
|
-
'description': entry.model_config.description
|
125
|
-
})
|
126
|
-
return result
|
127
|
-
|
128
|
-
@classmethod
|
129
|
-
def list_versions(cls, model_name: str) -> List[str]:
|
130
|
-
"""列出模型的所有版本"""
|
131
|
-
return cls._version_history.get(model_name, [])
|
132
|
-
|
133
|
-
@classmethod
|
134
|
-
def update_status(cls, model_name: str, status: str, version: str = None):
|
135
|
-
"""更新模型状态"""
|
136
|
-
entry = cls.get_model(model_name, version)
|
137
|
-
if entry:
|
138
|
-
entry.status = status
|
139
|
-
print(f"✅ 模型 {model_name} 状态更新为: {status}")
|
140
|
-
else:
|
141
|
-
print(f"❌ 模型 {model_name} 不存在")
|
142
|
-
|
143
|
-
@classmethod
|
144
|
-
def update_performance(cls, model_name: str, metrics: Dict[str, float], version: str = None):
|
145
|
-
"""更新模型性能指标"""
|
146
|
-
entry = cls.get_model(model_name, version)
|
147
|
-
if entry:
|
148
|
-
entry.performance_metrics.update(metrics)
|
149
|
-
print(f"✅ 模型 {model_name} 性能指标已更新")
|
150
|
-
else:
|
151
|
-
print(f"❌ 模型 {model_name} 不存在")
|
152
|
-
|
153
|
-
@classmethod
|
154
|
-
def get_model_summary(cls, model_name: str, version: str = None) -> Optional[Dict[str, Any]]:
|
155
|
-
"""获取模型详细信息摘要"""
|
156
|
-
entry = cls.get_model(model_name, version)
|
157
|
-
if not entry:
|
158
|
-
return None
|
159
|
-
|
160
|
-
model_config = entry.model_config
|
161
|
-
target_def = entry.target_definition
|
162
|
-
|
163
|
-
return {
|
164
|
-
'basic_info': {
|
165
|
-
'name': model_config.name,
|
166
|
-
'version': model_config.version,
|
167
|
-
'type': model_config.model_type.value,
|
168
|
-
'algorithm': model_config.algorithm.value,
|
169
|
-
'description': model_config.description,
|
170
|
-
'created_by': model_config.created_by,
|
171
|
-
'bank_code': model_config.bank_code
|
172
|
-
},
|
173
|
-
'feature_config': {
|
174
|
-
'schema_name': model_config.feature_config.schema_name,
|
175
|
-
'table_types': model_config.feature_config.table_types,
|
176
|
-
'feature_selection': model_config.feature_config.feature_selection,
|
177
|
-
'feature_engineering': model_config.feature_config.feature_engineering
|
178
|
-
},
|
179
|
-
'target_config': {
|
180
|
-
'name': target_def.name,
|
181
|
-
'type': target_def.target_type.value,
|
182
|
-
'column': target_def.target_column,
|
183
|
-
'description': target_def.description
|
184
|
-
},
|
185
|
-
'training_config': model_config.training_config,
|
186
|
-
'hyperparameters': model_config.hyperparameters,
|
187
|
-
'evaluation_metrics': model_config.evaluation_metrics,
|
188
|
-
'registry_info': {
|
189
|
-
'status': entry.status,
|
190
|
-
'registered_at': entry.registered_at.isoformat(),
|
191
|
-
'performance_metrics': entry.performance_metrics
|
192
|
-
}
|
193
|
-
}
|
194
|
-
|
195
|
-
@classmethod
|
196
|
-
def save_to_file(cls, filepath: str):
|
197
|
-
"""保存注册表到文件"""
|
198
|
-
data = {
|
199
|
-
'models': {},
|
200
|
-
'version_history': cls._version_history,
|
201
|
-
'saved_at': datetime.now().isoformat()
|
202
|
-
}
|
203
|
-
|
204
|
-
# 序列化模型数据
|
205
|
-
for model_id, entry in cls._models.items():
|
206
|
-
data['models'][model_id] = {
|
207
|
-
'model_config': entry.model_config.to_dict(),
|
208
|
-
'target_definition': entry.target_definition.to_dict(),
|
209
|
-
'registered_at': entry.registered_at.isoformat(),
|
210
|
-
'status': entry.status,
|
211
|
-
'performance_metrics': entry.performance_metrics
|
212
|
-
}
|
213
|
-
|
214
|
-
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
215
|
-
with open(filepath, 'w', encoding='utf-8') as f:
|
216
|
-
json.dump(data, f, indent=2, ensure_ascii=False)
|
217
|
-
|
218
|
-
print(f"✅ 模型注册表已保存到: {filepath}")
|
219
|
-
|
220
|
-
@classmethod
|
221
|
-
def load_from_file(cls, filepath: str):
|
222
|
-
"""从文件加载注册表"""
|
223
|
-
if not os.path.exists(filepath):
|
224
|
-
print(f"❌ 文件不存在: {filepath}")
|
225
|
-
return
|
226
|
-
|
227
|
-
with open(filepath, 'r', encoding='utf-8') as f:
|
228
|
-
data = json.load(f)
|
229
|
-
|
230
|
-
cls._version_history = data.get('version_history', {})
|
231
|
-
cls._models = {}
|
232
|
-
|
233
|
-
# 反序列化模型数据
|
234
|
-
for model_id, entry_data in data.get('models', {}).items():
|
235
|
-
model_config = ModelConfig.from_dict(entry_data['model_config'])
|
236
|
-
target_definition = TargetDefinition(
|
237
|
-
**entry_data['target_definition']
|
238
|
-
)
|
239
|
-
|
240
|
-
entry = ModelEntry(
|
241
|
-
model_config=model_config,
|
242
|
-
target_definition=target_definition,
|
243
|
-
registered_at=datetime.fromisoformat(entry_data['registered_at']),
|
244
|
-
status=entry_data.get('status', 'active'),
|
245
|
-
performance_metrics=entry_data.get('performance_metrics', {})
|
246
|
-
)
|
247
|
-
|
248
|
-
cls._models[model_id] = entry
|
249
|
-
|
250
|
-
print(f"✅ 从 {filepath} 加载了 {len(cls._models)} 个模型")
|
251
|
-
|
252
|
-
|
253
|
-
# 便捷函数
|
254
|
-
def register_model(model_config: ModelConfig, target_definition: TargetDefinition) -> str:
|
255
|
-
"""注册模型的便捷函数"""
|
256
|
-
return ModelRegistry.register(model_config, target_definition)
|
257
|
-
|
258
|
-
|
259
|
-
def get_model_config(model_name: str, version: str = None) -> Optional[ModelConfig]:
|
260
|
-
"""获取模型配置的便捷函数"""
|
261
|
-
return ModelRegistry.get_model_config(model_name, version)
|
262
|
-
|
263
|
-
|
264
|
-
def get_target_definition(model_name: str, version: str = None) -> Optional[TargetDefinition]:
|
265
|
-
"""获取目标变量定义的便捷函数"""
|
266
|
-
return ModelRegistry.get_target_definition(model_name, version)
|
267
|
-
|
268
|
-
|
269
|
-
def list_available_models() -> List[Dict[str, Any]]:
|
270
|
-
"""列出可用模型的便捷函数"""
|
271
|
-
return ModelRegistry.list_models()
|
272
|
-
|
273
|
-
|
274
|
-
def save_model_registry(filepath: str = "./models/model_registry.json"):
|
275
|
-
"""保存模型注册表的便捷函数"""
|
276
|
-
ModelRegistry.save_to_file(filepath)
|
277
|
-
|
278
|
-
|
279
|
-
def load_model_registry(filepath: str = "./models/model_registry.json"):
|
280
|
-
"""加载模型注册表的便捷函数"""
|
281
|
-
ModelRegistry.load_from_file(filepath)
|
staran/models/target.py
DELETED
@@ -1,321 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
目标变量定义模块
|
3
|
-
|
4
|
-
提供基于SQL的目标变量定义和生成功能
|
5
|
-
"""
|
6
|
-
|
7
|
-
from enum import Enum
|
8
|
-
from typing import Dict, Any, List, Optional, Union
|
9
|
-
from dataclasses import dataclass, field
|
10
|
-
from datetime import datetime
|
11
|
-
import re
|
12
|
-
|
13
|
-
|
14
|
-
class TargetType(Enum):
|
15
|
-
"""目标变量类型"""
|
16
|
-
BINARY_CLASSIFICATION = "binary_classification" # 二分类
|
17
|
-
MULTI_CLASSIFICATION = "multi_classification" # 多分类
|
18
|
-
REGRESSION = "regression" # 回归
|
19
|
-
RANKING = "ranking" # 排序
|
20
|
-
CLUSTERING = "clustering" # 聚类
|
21
|
-
SQL_BASED = "sql_based" # 基于SQL的自定义目标
|
22
|
-
|
23
|
-
|
24
|
-
class TargetEncoding(Enum):
|
25
|
-
"""目标变量编码方式"""
|
26
|
-
NONE = "none" # 不编码
|
27
|
-
LABEL_ENCODING = "label" # 标签编码
|
28
|
-
ONE_HOT = "one_hot" # 独热编码
|
29
|
-
ORDINAL = "ordinal" # 序数编码
|
30
|
-
BINARY = "binary" # 二进制编码
|
31
|
-
|
32
|
-
|
33
|
-
@dataclass
|
34
|
-
class TargetDefinition:
|
35
|
-
"""目标变量定义类"""
|
36
|
-
# 基本信息
|
37
|
-
name: str # 目标变量名称
|
38
|
-
target_type: TargetType # 目标类型
|
39
|
-
description: str = "" # 描述
|
40
|
-
|
41
|
-
# SQL定义 (核心功能)
|
42
|
-
sql_query: str = "" # 生成目标变量的SQL查询
|
43
|
-
target_column: str = "target" # 目标列名
|
44
|
-
|
45
|
-
# 数据信息
|
46
|
-
data_type: str = "float" # 数据类型
|
47
|
-
encoding: TargetEncoding = TargetEncoding.NONE # 编码方式
|
48
|
-
|
49
|
-
# 分类相关
|
50
|
-
class_labels: List[str] = field(default_factory=list) # 类别标签
|
51
|
-
class_weights: Dict[str, float] = field(default_factory=dict) # 类别权重
|
52
|
-
|
53
|
-
# 回归相关
|
54
|
-
min_value: Optional[float] = None # 最小值
|
55
|
-
max_value: Optional[float] = None # 最大值
|
56
|
-
normalization: bool = False # 是否标准化
|
57
|
-
|
58
|
-
# 时间相关
|
59
|
-
time_window: str = "" # 时间窗口 (如 "30_days", "3_months")
|
60
|
-
prediction_horizon: str = "" # 预测时间范围
|
61
|
-
|
62
|
-
# 银行特定
|
63
|
-
bank_code: str = "generic" # 银行代码
|
64
|
-
business_rules: Dict[str, Any] = field(default_factory=dict) # 业务规则
|
65
|
-
|
66
|
-
# 元数据
|
67
|
-
created_at: datetime = field(default_factory=datetime.now)
|
68
|
-
created_by: str = "system"
|
69
|
-
version: str = "1.0.0"
|
70
|
-
tags: List[str] = field(default_factory=list)
|
71
|
-
|
72
|
-
# 验证配置
|
73
|
-
validation_rules: Dict[str, Any] = field(default_factory=dict)
|
74
|
-
|
75
|
-
def __post_init__(self):
|
76
|
-
"""初始化后处理"""
|
77
|
-
if not self.sql_query and self.target_type != TargetType.SQL_BASED:
|
78
|
-
self.sql_query = self._generate_default_sql()
|
79
|
-
|
80
|
-
# 验证SQL语法
|
81
|
-
if self.sql_query:
|
82
|
-
self._validate_sql()
|
83
|
-
|
84
|
-
def _generate_default_sql(self) -> str:
|
85
|
-
"""根据目标类型生成默认SQL"""
|
86
|
-
if self.target_type == TargetType.BINARY_CLASSIFICATION:
|
87
|
-
return f"""
|
88
|
-
SELECT party_id,
|
89
|
-
CASE WHEN condition THEN 1 ELSE 0 END as {self.target_column}
|
90
|
-
FROM source_table
|
91
|
-
WHERE data_dt = '{{data_dt}}'
|
92
|
-
"""
|
93
|
-
elif self.target_type == TargetType.REGRESSION:
|
94
|
-
return f"""
|
95
|
-
SELECT party_id,
|
96
|
-
target_value as {self.target_column}
|
97
|
-
FROM source_table
|
98
|
-
WHERE data_dt = '{{data_dt}}'
|
99
|
-
"""
|
100
|
-
else:
|
101
|
-
return ""
|
102
|
-
|
103
|
-
def _validate_sql(self):
|
104
|
-
"""验证SQL语法基本正确性"""
|
105
|
-
sql = self.sql_query.strip().upper()
|
106
|
-
|
107
|
-
# 基本SQL结构检查 (支持WITH语句)
|
108
|
-
if not (sql.startswith('SELECT') or sql.startswith('WITH')):
|
109
|
-
raise ValueError("SQL查询必须以SELECT或WITH开始")
|
110
|
-
|
111
|
-
# 检查是否包含目标列
|
112
|
-
if self.target_column.upper() not in sql:
|
113
|
-
print(f"警告: SQL中未找到目标列 '{self.target_column}'")
|
114
|
-
|
115
|
-
# 检查参数占位符
|
116
|
-
placeholders = re.findall(r'\{(\w+)\}', self.sql_query)
|
117
|
-
if placeholders:
|
118
|
-
print(f"发现参数占位符: {placeholders}")
|
119
|
-
|
120
|
-
def generate_sql(self, **params) -> str:
|
121
|
-
"""
|
122
|
-
生成最终的SQL查询,替换参数占位符
|
123
|
-
|
124
|
-
Args:
|
125
|
-
**params: SQL参数字典
|
126
|
-
|
127
|
-
Returns:
|
128
|
-
最终的SQL查询字符串
|
129
|
-
"""
|
130
|
-
sql = self.sql_query
|
131
|
-
|
132
|
-
# 替换参数占位符
|
133
|
-
for key, value in params.items():
|
134
|
-
placeholder = f"{{{key}}}"
|
135
|
-
sql = sql.replace(placeholder, str(value))
|
136
|
-
|
137
|
-
return sql
|
138
|
-
|
139
|
-
def get_sample_sql(self, data_dt: str = "20250728") -> str:
|
140
|
-
"""获取示例SQL"""
|
141
|
-
return self.generate_sql(data_dt=data_dt)
|
142
|
-
|
143
|
-
def validate_target_values(self, values: List[Any]) -> bool:
|
144
|
-
"""验证目标值是否符合定义"""
|
145
|
-
if self.target_type == TargetType.BINARY_CLASSIFICATION:
|
146
|
-
unique_values = set(values)
|
147
|
-
return unique_values.issubset({0, 1, 0.0, 1.0})
|
148
|
-
|
149
|
-
elif self.target_type == TargetType.MULTI_CLASSIFICATION:
|
150
|
-
if self.class_labels:
|
151
|
-
unique_values = set(values)
|
152
|
-
return unique_values.issubset(set(self.class_labels))
|
153
|
-
|
154
|
-
elif self.target_type == TargetType.REGRESSION:
|
155
|
-
if self.min_value is not None and self.max_value is not None:
|
156
|
-
return all(self.min_value <= v <= self.max_value for v in values)
|
157
|
-
|
158
|
-
return True
|
159
|
-
|
160
|
-
def to_dict(self) -> Dict[str, Any]:
|
161
|
-
"""转换为字典格式"""
|
162
|
-
return {
|
163
|
-
'name': self.name,
|
164
|
-
'target_type': self.target_type.value,
|
165
|
-
'description': self.description,
|
166
|
-
'sql_query': self.sql_query,
|
167
|
-
'target_column': self.target_column,
|
168
|
-
'data_type': self.data_type,
|
169
|
-
'encoding': self.encoding.value,
|
170
|
-
'class_labels': self.class_labels,
|
171
|
-
'class_weights': self.class_weights,
|
172
|
-
'min_value': self.min_value,
|
173
|
-
'max_value': self.max_value,
|
174
|
-
'normalization': self.normalization,
|
175
|
-
'time_window': self.time_window,
|
176
|
-
'prediction_horizon': self.prediction_horizon,
|
177
|
-
'bank_code': self.bank_code,
|
178
|
-
'business_rules': self.business_rules,
|
179
|
-
'created_at': self.created_at.isoformat(),
|
180
|
-
'created_by': self.created_by,
|
181
|
-
'version': self.version,
|
182
|
-
'tags': self.tags,
|
183
|
-
'validation_rules': self.validation_rules
|
184
|
-
}
|
185
|
-
|
186
|
-
|
187
|
-
def create_target_definition(
|
188
|
-
name: str,
|
189
|
-
target_type: str,
|
190
|
-
sql_query: str,
|
191
|
-
target_column: str = "target",
|
192
|
-
bank_code: str = "generic",
|
193
|
-
**kwargs
|
194
|
-
) -> TargetDefinition:
|
195
|
-
"""
|
196
|
-
创建目标变量定义的便捷函数
|
197
|
-
|
198
|
-
Args:
|
199
|
-
name: 目标变量名称
|
200
|
-
target_type: 目标类型
|
201
|
-
sql_query: SQL查询
|
202
|
-
target_column: 目标列名
|
203
|
-
bank_code: 银行代码
|
204
|
-
**kwargs: 其他配置参数
|
205
|
-
|
206
|
-
Returns:
|
207
|
-
TargetDefinition实例
|
208
|
-
"""
|
209
|
-
return TargetDefinition(
|
210
|
-
name=name,
|
211
|
-
target_type=TargetType(target_type),
|
212
|
-
sql_query=sql_query,
|
213
|
-
target_column=target_column,
|
214
|
-
bank_code=bank_code,
|
215
|
-
**kwargs
|
216
|
-
)
|
217
|
-
|
218
|
-
|
219
|
-
# 预定义的目标变量模板
|
220
|
-
TARGET_TEMPLATES = {
|
221
|
-
"aum_longtail_purchase": {
|
222
|
-
"target_type": "binary_classification",
|
223
|
-
"description": "AUM长尾客户未来购买预测",
|
224
|
-
"sql_query": """
|
225
|
-
SELECT
|
226
|
-
a.party_id,
|
227
|
-
CASE
|
228
|
-
WHEN b.purchase_amount > 0 THEN 1
|
229
|
-
ELSE 0
|
230
|
-
END as target
|
231
|
-
FROM
|
232
|
-
bi_hlwj_dfcw_f1_f4_wy a
|
233
|
-
LEFT JOIN (
|
234
|
-
SELECT party_id, SUM(productamount_sum) as purchase_amount
|
235
|
-
FROM bi_hlwj_dfcw_f1_f4_wy
|
236
|
-
WHERE data_dt BETWEEN '{start_dt}' AND '{end_dt}'
|
237
|
-
GROUP BY party_id
|
238
|
-
) b ON a.party_id = b.party_id
|
239
|
-
WHERE a.data_dt = '{feature_dt}'
|
240
|
-
""",
|
241
|
-
"target_column": "target",
|
242
|
-
"time_window": "30_days",
|
243
|
-
"class_labels": ["no_purchase", "purchase"]
|
244
|
-
},
|
245
|
-
|
246
|
-
"customer_value_prediction": {
|
247
|
-
"target_type": "regression",
|
248
|
-
"description": "客户价值预测",
|
249
|
-
"sql_query": """
|
250
|
-
SELECT
|
251
|
-
party_id,
|
252
|
-
asset_total_bal as target
|
253
|
-
FROM
|
254
|
-
bi_hlwj_zi_chan_avg_wy
|
255
|
-
WHERE
|
256
|
-
data_dt = '{target_dt}'
|
257
|
-
""",
|
258
|
-
"target_column": "target",
|
259
|
-
"data_type": "float",
|
260
|
-
"normalization": True
|
261
|
-
},
|
262
|
-
|
263
|
-
"risk_level_classification": {
|
264
|
-
"target_type": "multi_classification",
|
265
|
-
"description": "风险等级分类",
|
266
|
-
"sql_query": """
|
267
|
-
SELECT
|
268
|
-
party_id,
|
269
|
-
CASE
|
270
|
-
WHEN asset_total_bal < 10000 THEN 'low_risk'
|
271
|
-
WHEN asset_total_bal < 100000 THEN 'medium_risk'
|
272
|
-
ELSE 'high_risk'
|
273
|
-
END as target
|
274
|
-
FROM
|
275
|
-
bi_hlwj_zi_chan_avg_wy
|
276
|
-
WHERE
|
277
|
-
data_dt = '{data_dt}'
|
278
|
-
""",
|
279
|
-
"target_column": "target",
|
280
|
-
"class_labels": ["low_risk", "medium_risk", "high_risk"]
|
281
|
-
}
|
282
|
-
}
|
283
|
-
|
284
|
-
|
285
|
-
def create_preset_target(preset_name: str, **overrides) -> TargetDefinition:
|
286
|
-
"""
|
287
|
-
基于预设模板创建目标变量定义
|
288
|
-
|
289
|
-
Args:
|
290
|
-
preset_name: 预设模板名称
|
291
|
-
**overrides: 覆盖的配置参数
|
292
|
-
|
293
|
-
Returns:
|
294
|
-
TargetDefinition实例
|
295
|
-
"""
|
296
|
-
if preset_name not in TARGET_TEMPLATES:
|
297
|
-
raise ValueError(f"未知的目标变量模板: {preset_name}")
|
298
|
-
|
299
|
-
template = TARGET_TEMPLATES[preset_name].copy()
|
300
|
-
template.update(overrides)
|
301
|
-
|
302
|
-
return create_target_definition(
|
303
|
-
name=preset_name,
|
304
|
-
**template
|
305
|
-
)
|
306
|
-
|
307
|
-
|
308
|
-
def create_icbc_target(name: str, sql_query: str, target_type: str = "binary_classification", **kwargs) -> TargetDefinition:
|
309
|
-
"""创建工商银行专用目标变量定义"""
|
310
|
-
return create_target_definition(
|
311
|
-
name=name,
|
312
|
-
target_type=target_type,
|
313
|
-
sql_query=sql_query,
|
314
|
-
bank_code="icbc",
|
315
|
-
business_rules={
|
316
|
-
"data_retention_days": 90,
|
317
|
-
"privacy_compliance": True,
|
318
|
-
"audit_required": True
|
319
|
-
},
|
320
|
-
**kwargs
|
321
|
-
)
|
staran/schemas/__init__.py
DELETED
@@ -1,27 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Staran Schemas模块 - 新疆工行代发长尾客户表结构定义
|
3
|
-
|
4
|
-
提供新疆工行代发长尾客户的标准化表结构定义和字段管理功能。
|
5
|
-
|
6
|
-
主要功能:
|
7
|
-
- 代发长尾客户表结构定义
|
8
|
-
- 业务字段含义管理
|
9
|
-
- 新疆工行专用配置
|
10
|
-
- 表结构文档生成
|
11
|
-
"""
|
12
|
-
|
13
|
-
from ..tools.document_generator import SchemaDocumentGenerator
|
14
|
-
from .aum import *
|
15
|
-
|
16
|
-
__all__ = [
|
17
|
-
'SchemaDocumentGenerator',
|
18
|
-
# 新疆工行代发长尾客户表
|
19
|
-
'XinjiangICBCDaifaLongtailBehaviorSchema',
|
20
|
-
'XinjiangICBCDaifaLongtailAssetAvgSchema',
|
21
|
-
'XinjiangICBCDaifaLongtailAssetConfigSchema',
|
22
|
-
'XinjiangICBCDaifaLongtailMonthlyStatSchema',
|
23
|
-
'get_xinjiang_icbc_daifa_longtail_schemas',
|
24
|
-
'export_xinjiang_icbc_daifa_longtail_docs'
|
25
|
-
]
|
26
|
-
|
27
|
-
__version__ = "0.6.0"
|