churnkit 0.75.0a1__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.
Files changed (302) hide show
  1. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/00_start_here.ipynb +647 -0
  2. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01_data_discovery.ipynb +1165 -0
  3. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_a_temporal_text_deep_dive.ipynb +961 -0
  4. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_temporal_deep_dive.ipynb +1690 -0
  5. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01b_temporal_quality.ipynb +679 -0
  6. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01c_temporal_patterns.ipynb +3305 -0
  7. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01d_event_aggregation.ipynb +1463 -0
  8. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02_column_deep_dive.ipynb +1430 -0
  9. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02a_text_columns_deep_dive.ipynb +854 -0
  10. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/03_quality_assessment.ipynb +1639 -0
  11. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/04_relationship_analysis.ipynb +1890 -0
  12. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/05_multi_dataset.ipynb +1457 -0
  13. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/06_feature_opportunities.ipynb +1624 -0
  14. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/07_modeling_readiness.ipynb +780 -0
  15. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/08_baseline_experiments.ipynb +979 -0
  16. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/09_business_alignment.ipynb +572 -0
  17. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/10_spec_generation.ipynb +1179 -0
  18. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/11_scoring_validation.ipynb +1418 -0
  19. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/12_view_documentation.ipynb +151 -0
  20. churnkit-0.75.0a1.dist-info/METADATA +229 -0
  21. churnkit-0.75.0a1.dist-info/RECORD +302 -0
  22. churnkit-0.75.0a1.dist-info/WHEEL +4 -0
  23. churnkit-0.75.0a1.dist-info/entry_points.txt +2 -0
  24. churnkit-0.75.0a1.dist-info/licenses/LICENSE +202 -0
  25. customer_retention/__init__.py +37 -0
  26. customer_retention/analysis/__init__.py +0 -0
  27. customer_retention/analysis/auto_explorer/__init__.py +62 -0
  28. customer_retention/analysis/auto_explorer/exploration_manager.py +470 -0
  29. customer_retention/analysis/auto_explorer/explorer.py +258 -0
  30. customer_retention/analysis/auto_explorer/findings.py +291 -0
  31. customer_retention/analysis/auto_explorer/layered_recommendations.py +485 -0
  32. customer_retention/analysis/auto_explorer/recommendation_builder.py +148 -0
  33. customer_retention/analysis/auto_explorer/recommendations.py +418 -0
  34. customer_retention/analysis/business/__init__.py +26 -0
  35. customer_retention/analysis/business/ab_test_designer.py +144 -0
  36. customer_retention/analysis/business/fairness_analyzer.py +166 -0
  37. customer_retention/analysis/business/intervention_matcher.py +121 -0
  38. customer_retention/analysis/business/report_generator.py +222 -0
  39. customer_retention/analysis/business/risk_profile.py +199 -0
  40. customer_retention/analysis/business/roi_analyzer.py +139 -0
  41. customer_retention/analysis/diagnostics/__init__.py +20 -0
  42. customer_retention/analysis/diagnostics/calibration_analyzer.py +133 -0
  43. customer_retention/analysis/diagnostics/cv_analyzer.py +144 -0
  44. customer_retention/analysis/diagnostics/error_analyzer.py +107 -0
  45. customer_retention/analysis/diagnostics/leakage_detector.py +394 -0
  46. customer_retention/analysis/diagnostics/noise_tester.py +140 -0
  47. customer_retention/analysis/diagnostics/overfitting_analyzer.py +190 -0
  48. customer_retention/analysis/diagnostics/segment_analyzer.py +122 -0
  49. customer_retention/analysis/discovery/__init__.py +8 -0
  50. customer_retention/analysis/discovery/config_generator.py +49 -0
  51. customer_retention/analysis/discovery/discovery_flow.py +19 -0
  52. customer_retention/analysis/discovery/type_inferencer.py +147 -0
  53. customer_retention/analysis/interpretability/__init__.py +13 -0
  54. customer_retention/analysis/interpretability/cohort_analyzer.py +185 -0
  55. customer_retention/analysis/interpretability/counterfactual.py +175 -0
  56. customer_retention/analysis/interpretability/individual_explainer.py +141 -0
  57. customer_retention/analysis/interpretability/pdp_generator.py +103 -0
  58. customer_retention/analysis/interpretability/shap_explainer.py +106 -0
  59. customer_retention/analysis/jupyter_save_hook.py +28 -0
  60. customer_retention/analysis/notebook_html_exporter.py +136 -0
  61. customer_retention/analysis/notebook_progress.py +60 -0
  62. customer_retention/analysis/plotly_preprocessor.py +154 -0
  63. customer_retention/analysis/recommendations/__init__.py +54 -0
  64. customer_retention/analysis/recommendations/base.py +158 -0
  65. customer_retention/analysis/recommendations/cleaning/__init__.py +11 -0
  66. customer_retention/analysis/recommendations/cleaning/consistency.py +107 -0
  67. customer_retention/analysis/recommendations/cleaning/deduplicate.py +94 -0
  68. customer_retention/analysis/recommendations/cleaning/impute.py +67 -0
  69. customer_retention/analysis/recommendations/cleaning/outlier.py +71 -0
  70. customer_retention/analysis/recommendations/datetime/__init__.py +3 -0
  71. customer_retention/analysis/recommendations/datetime/extract.py +149 -0
  72. customer_retention/analysis/recommendations/encoding/__init__.py +3 -0
  73. customer_retention/analysis/recommendations/encoding/categorical.py +114 -0
  74. customer_retention/analysis/recommendations/pipeline.py +74 -0
  75. customer_retention/analysis/recommendations/registry.py +76 -0
  76. customer_retention/analysis/recommendations/selection/__init__.py +3 -0
  77. customer_retention/analysis/recommendations/selection/drop_column.py +56 -0
  78. customer_retention/analysis/recommendations/transform/__init__.py +4 -0
  79. customer_retention/analysis/recommendations/transform/power.py +94 -0
  80. customer_retention/analysis/recommendations/transform/scale.py +112 -0
  81. customer_retention/analysis/visualization/__init__.py +15 -0
  82. customer_retention/analysis/visualization/chart_builder.py +2619 -0
  83. customer_retention/analysis/visualization/console.py +122 -0
  84. customer_retention/analysis/visualization/display.py +171 -0
  85. customer_retention/analysis/visualization/number_formatter.py +36 -0
  86. customer_retention/artifacts/__init__.py +3 -0
  87. customer_retention/artifacts/fit_artifact_registry.py +146 -0
  88. customer_retention/cli.py +93 -0
  89. customer_retention/core/__init__.py +0 -0
  90. customer_retention/core/compat/__init__.py +193 -0
  91. customer_retention/core/compat/detection.py +99 -0
  92. customer_retention/core/compat/ops.py +48 -0
  93. customer_retention/core/compat/pandas_backend.py +57 -0
  94. customer_retention/core/compat/spark_backend.py +75 -0
  95. customer_retention/core/components/__init__.py +11 -0
  96. customer_retention/core/components/base.py +79 -0
  97. customer_retention/core/components/components/__init__.py +13 -0
  98. customer_retention/core/components/components/deployer.py +26 -0
  99. customer_retention/core/components/components/explainer.py +26 -0
  100. customer_retention/core/components/components/feature_eng.py +33 -0
  101. customer_retention/core/components/components/ingester.py +34 -0
  102. customer_retention/core/components/components/profiler.py +34 -0
  103. customer_retention/core/components/components/trainer.py +38 -0
  104. customer_retention/core/components/components/transformer.py +36 -0
  105. customer_retention/core/components/components/validator.py +37 -0
  106. customer_retention/core/components/enums.py +33 -0
  107. customer_retention/core/components/orchestrator.py +94 -0
  108. customer_retention/core/components/registry.py +59 -0
  109. customer_retention/core/config/__init__.py +39 -0
  110. customer_retention/core/config/column_config.py +95 -0
  111. customer_retention/core/config/experiments.py +71 -0
  112. customer_retention/core/config/pipeline_config.py +117 -0
  113. customer_retention/core/config/source_config.py +83 -0
  114. customer_retention/core/utils/__init__.py +28 -0
  115. customer_retention/core/utils/leakage.py +85 -0
  116. customer_retention/core/utils/severity.py +53 -0
  117. customer_retention/core/utils/statistics.py +90 -0
  118. customer_retention/generators/__init__.py +0 -0
  119. customer_retention/generators/notebook_generator/__init__.py +167 -0
  120. customer_retention/generators/notebook_generator/base.py +55 -0
  121. customer_retention/generators/notebook_generator/cell_builder.py +49 -0
  122. customer_retention/generators/notebook_generator/config.py +47 -0
  123. customer_retention/generators/notebook_generator/databricks_generator.py +48 -0
  124. customer_retention/generators/notebook_generator/local_generator.py +48 -0
  125. customer_retention/generators/notebook_generator/project_init.py +174 -0
  126. customer_retention/generators/notebook_generator/runner.py +150 -0
  127. customer_retention/generators/notebook_generator/script_generator.py +110 -0
  128. customer_retention/generators/notebook_generator/stages/__init__.py +19 -0
  129. customer_retention/generators/notebook_generator/stages/base_stage.py +86 -0
  130. customer_retention/generators/notebook_generator/stages/s01_ingestion.py +100 -0
  131. customer_retention/generators/notebook_generator/stages/s02_profiling.py +95 -0
  132. customer_retention/generators/notebook_generator/stages/s03_cleaning.py +180 -0
  133. customer_retention/generators/notebook_generator/stages/s04_transformation.py +165 -0
  134. customer_retention/generators/notebook_generator/stages/s05_feature_engineering.py +115 -0
  135. customer_retention/generators/notebook_generator/stages/s06_feature_selection.py +97 -0
  136. customer_retention/generators/notebook_generator/stages/s07_model_training.py +176 -0
  137. customer_retention/generators/notebook_generator/stages/s08_deployment.py +81 -0
  138. customer_retention/generators/notebook_generator/stages/s09_monitoring.py +112 -0
  139. customer_retention/generators/notebook_generator/stages/s10_batch_inference.py +642 -0
  140. customer_retention/generators/notebook_generator/stages/s11_feature_store.py +348 -0
  141. customer_retention/generators/orchestration/__init__.py +23 -0
  142. customer_retention/generators/orchestration/code_generator.py +196 -0
  143. customer_retention/generators/orchestration/context.py +147 -0
  144. customer_retention/generators/orchestration/data_materializer.py +188 -0
  145. customer_retention/generators/orchestration/databricks_exporter.py +411 -0
  146. customer_retention/generators/orchestration/doc_generator.py +311 -0
  147. customer_retention/generators/pipeline_generator/__init__.py +26 -0
  148. customer_retention/generators/pipeline_generator/findings_parser.py +727 -0
  149. customer_retention/generators/pipeline_generator/generator.py +142 -0
  150. customer_retention/generators/pipeline_generator/models.py +166 -0
  151. customer_retention/generators/pipeline_generator/renderer.py +2125 -0
  152. customer_retention/generators/spec_generator/__init__.py +37 -0
  153. customer_retention/generators/spec_generator/databricks_generator.py +433 -0
  154. customer_retention/generators/spec_generator/generic_generator.py +373 -0
  155. customer_retention/generators/spec_generator/mlflow_pipeline_generator.py +685 -0
  156. customer_retention/generators/spec_generator/pipeline_spec.py +298 -0
  157. customer_retention/integrations/__init__.py +0 -0
  158. customer_retention/integrations/adapters/__init__.py +13 -0
  159. customer_retention/integrations/adapters/base.py +10 -0
  160. customer_retention/integrations/adapters/factory.py +25 -0
  161. customer_retention/integrations/adapters/feature_store/__init__.py +6 -0
  162. customer_retention/integrations/adapters/feature_store/base.py +57 -0
  163. customer_retention/integrations/adapters/feature_store/databricks.py +94 -0
  164. customer_retention/integrations/adapters/feature_store/feast_adapter.py +97 -0
  165. customer_retention/integrations/adapters/feature_store/local.py +75 -0
  166. customer_retention/integrations/adapters/mlflow/__init__.py +6 -0
  167. customer_retention/integrations/adapters/mlflow/base.py +32 -0
  168. customer_retention/integrations/adapters/mlflow/databricks.py +54 -0
  169. customer_retention/integrations/adapters/mlflow/experiment_tracker.py +161 -0
  170. customer_retention/integrations/adapters/mlflow/local.py +50 -0
  171. customer_retention/integrations/adapters/storage/__init__.py +5 -0
  172. customer_retention/integrations/adapters/storage/base.py +33 -0
  173. customer_retention/integrations/adapters/storage/databricks.py +76 -0
  174. customer_retention/integrations/adapters/storage/local.py +59 -0
  175. customer_retention/integrations/feature_store/__init__.py +47 -0
  176. customer_retention/integrations/feature_store/definitions.py +215 -0
  177. customer_retention/integrations/feature_store/manager.py +744 -0
  178. customer_retention/integrations/feature_store/registry.py +412 -0
  179. customer_retention/integrations/iteration/__init__.py +28 -0
  180. customer_retention/integrations/iteration/context.py +212 -0
  181. customer_retention/integrations/iteration/feedback_collector.py +184 -0
  182. customer_retention/integrations/iteration/orchestrator.py +168 -0
  183. customer_retention/integrations/iteration/recommendation_tracker.py +341 -0
  184. customer_retention/integrations/iteration/signals.py +212 -0
  185. customer_retention/integrations/llm_context/__init__.py +4 -0
  186. customer_retention/integrations/llm_context/context_builder.py +201 -0
  187. customer_retention/integrations/llm_context/prompts.py +100 -0
  188. customer_retention/integrations/streaming/__init__.py +103 -0
  189. customer_retention/integrations/streaming/batch_integration.py +149 -0
  190. customer_retention/integrations/streaming/early_warning_model.py +227 -0
  191. customer_retention/integrations/streaming/event_schema.py +214 -0
  192. customer_retention/integrations/streaming/online_store_writer.py +249 -0
  193. customer_retention/integrations/streaming/realtime_scorer.py +261 -0
  194. customer_retention/integrations/streaming/trigger_engine.py +293 -0
  195. customer_retention/integrations/streaming/window_aggregator.py +393 -0
  196. customer_retention/stages/__init__.py +0 -0
  197. customer_retention/stages/cleaning/__init__.py +9 -0
  198. customer_retention/stages/cleaning/base.py +28 -0
  199. customer_retention/stages/cleaning/missing_handler.py +160 -0
  200. customer_retention/stages/cleaning/outlier_handler.py +204 -0
  201. customer_retention/stages/deployment/__init__.py +28 -0
  202. customer_retention/stages/deployment/batch_scorer.py +106 -0
  203. customer_retention/stages/deployment/champion_challenger.py +299 -0
  204. customer_retention/stages/deployment/model_registry.py +182 -0
  205. customer_retention/stages/deployment/retraining_trigger.py +245 -0
  206. customer_retention/stages/features/__init__.py +73 -0
  207. customer_retention/stages/features/behavioral_features.py +266 -0
  208. customer_retention/stages/features/customer_segmentation.py +505 -0
  209. customer_retention/stages/features/feature_definitions.py +265 -0
  210. customer_retention/stages/features/feature_engineer.py +551 -0
  211. customer_retention/stages/features/feature_manifest.py +340 -0
  212. customer_retention/stages/features/feature_selector.py +239 -0
  213. customer_retention/stages/features/interaction_features.py +160 -0
  214. customer_retention/stages/features/temporal_features.py +243 -0
  215. customer_retention/stages/ingestion/__init__.py +9 -0
  216. customer_retention/stages/ingestion/load_result.py +32 -0
  217. customer_retention/stages/ingestion/loaders.py +195 -0
  218. customer_retention/stages/ingestion/source_registry.py +130 -0
  219. customer_retention/stages/modeling/__init__.py +31 -0
  220. customer_retention/stages/modeling/baseline_trainer.py +139 -0
  221. customer_retention/stages/modeling/cross_validator.py +125 -0
  222. customer_retention/stages/modeling/data_splitter.py +205 -0
  223. customer_retention/stages/modeling/feature_scaler.py +99 -0
  224. customer_retention/stages/modeling/hyperparameter_tuner.py +107 -0
  225. customer_retention/stages/modeling/imbalance_handler.py +282 -0
  226. customer_retention/stages/modeling/mlflow_logger.py +95 -0
  227. customer_retention/stages/modeling/model_comparator.py +149 -0
  228. customer_retention/stages/modeling/model_evaluator.py +138 -0
  229. customer_retention/stages/modeling/threshold_optimizer.py +131 -0
  230. customer_retention/stages/monitoring/__init__.py +37 -0
  231. customer_retention/stages/monitoring/alert_manager.py +328 -0
  232. customer_retention/stages/monitoring/drift_detector.py +201 -0
  233. customer_retention/stages/monitoring/performance_monitor.py +242 -0
  234. customer_retention/stages/preprocessing/__init__.py +5 -0
  235. customer_retention/stages/preprocessing/transformer_manager.py +284 -0
  236. customer_retention/stages/profiling/__init__.py +256 -0
  237. customer_retention/stages/profiling/categorical_distribution.py +269 -0
  238. customer_retention/stages/profiling/categorical_target_analyzer.py +274 -0
  239. customer_retention/stages/profiling/column_profiler.py +527 -0
  240. customer_retention/stages/profiling/distribution_analysis.py +483 -0
  241. customer_retention/stages/profiling/drift_detector.py +310 -0
  242. customer_retention/stages/profiling/feature_capacity.py +507 -0
  243. customer_retention/stages/profiling/pattern_analysis_config.py +513 -0
  244. customer_retention/stages/profiling/profile_result.py +212 -0
  245. customer_retention/stages/profiling/quality_checks.py +1632 -0
  246. customer_retention/stages/profiling/relationship_detector.py +256 -0
  247. customer_retention/stages/profiling/relationship_recommender.py +454 -0
  248. customer_retention/stages/profiling/report_generator.py +520 -0
  249. customer_retention/stages/profiling/scd_analyzer.py +151 -0
  250. customer_retention/stages/profiling/segment_analyzer.py +632 -0
  251. customer_retention/stages/profiling/segment_aware_outlier.py +265 -0
  252. customer_retention/stages/profiling/target_level_analyzer.py +217 -0
  253. customer_retention/stages/profiling/temporal_analyzer.py +388 -0
  254. customer_retention/stages/profiling/temporal_coverage.py +488 -0
  255. customer_retention/stages/profiling/temporal_feature_analyzer.py +692 -0
  256. customer_retention/stages/profiling/temporal_feature_engineer.py +703 -0
  257. customer_retention/stages/profiling/temporal_pattern_analyzer.py +636 -0
  258. customer_retention/stages/profiling/temporal_quality_checks.py +278 -0
  259. customer_retention/stages/profiling/temporal_target_analyzer.py +241 -0
  260. customer_retention/stages/profiling/text_embedder.py +87 -0
  261. customer_retention/stages/profiling/text_processor.py +115 -0
  262. customer_retention/stages/profiling/text_reducer.py +60 -0
  263. customer_retention/stages/profiling/time_series_profiler.py +303 -0
  264. customer_retention/stages/profiling/time_window_aggregator.py +376 -0
  265. customer_retention/stages/profiling/type_detector.py +382 -0
  266. customer_retention/stages/profiling/window_recommendation.py +288 -0
  267. customer_retention/stages/temporal/__init__.py +166 -0
  268. customer_retention/stages/temporal/access_guard.py +180 -0
  269. customer_retention/stages/temporal/cutoff_analyzer.py +235 -0
  270. customer_retention/stages/temporal/data_preparer.py +178 -0
  271. customer_retention/stages/temporal/point_in_time_join.py +134 -0
  272. customer_retention/stages/temporal/point_in_time_registry.py +148 -0
  273. customer_retention/stages/temporal/scenario_detector.py +163 -0
  274. customer_retention/stages/temporal/snapshot_manager.py +259 -0
  275. customer_retention/stages/temporal/synthetic_coordinator.py +66 -0
  276. customer_retention/stages/temporal/timestamp_discovery.py +531 -0
  277. customer_retention/stages/temporal/timestamp_manager.py +255 -0
  278. customer_retention/stages/transformation/__init__.py +13 -0
  279. customer_retention/stages/transformation/binary_handler.py +85 -0
  280. customer_retention/stages/transformation/categorical_encoder.py +245 -0
  281. customer_retention/stages/transformation/datetime_transformer.py +97 -0
  282. customer_retention/stages/transformation/numeric_transformer.py +181 -0
  283. customer_retention/stages/transformation/pipeline.py +257 -0
  284. customer_retention/stages/validation/__init__.py +60 -0
  285. customer_retention/stages/validation/adversarial_scoring_validator.py +205 -0
  286. customer_retention/stages/validation/business_sense_gate.py +173 -0
  287. customer_retention/stages/validation/data_quality_gate.py +235 -0
  288. customer_retention/stages/validation/data_validators.py +511 -0
  289. customer_retention/stages/validation/feature_quality_gate.py +183 -0
  290. customer_retention/stages/validation/gates.py +117 -0
  291. customer_retention/stages/validation/leakage_gate.py +352 -0
  292. customer_retention/stages/validation/model_validity_gate.py +213 -0
  293. customer_retention/stages/validation/pipeline_validation_runner.py +264 -0
  294. customer_retention/stages/validation/quality_scorer.py +544 -0
  295. customer_retention/stages/validation/rule_generator.py +57 -0
  296. customer_retention/stages/validation/scoring_pipeline_validator.py +446 -0
  297. customer_retention/stages/validation/timeseries_detector.py +769 -0
  298. customer_retention/transforms/__init__.py +47 -0
  299. customer_retention/transforms/artifact_store.py +50 -0
  300. customer_retention/transforms/executor.py +157 -0
  301. customer_retention/transforms/fitted.py +92 -0
  302. customer_retention/transforms/ops.py +148 -0
@@ -0,0 +1,149 @@
1
+ """Model comparison and selection for customer retention prediction."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from sklearn.metrics import (
7
+ accuracy_score,
8
+ average_precision_score,
9
+ f1_score,
10
+ precision_score,
11
+ recall_score,
12
+ roc_auc_score,
13
+ )
14
+
15
+ from customer_retention.core.compat import DataFrame, Series
16
+
17
+
18
+ @dataclass
19
+ class ModelMetrics:
20
+ pr_auc: float
21
+ roc_auc: float
22
+ f1: float
23
+ precision: float
24
+ recall: float
25
+ accuracy: float
26
+ train_test_gap: Optional[float] = None
27
+ cv_std: Optional[float] = None
28
+
29
+
30
+ @dataclass
31
+ class ComparisonResult:
32
+ model_metrics: Dict[str, ModelMetrics]
33
+ ranking: List[str]
34
+ best_model_name: str
35
+ comparison_table: DataFrame
36
+ selection_reason: str
37
+
38
+
39
+ class ModelComparator:
40
+ def __init__(
41
+ self,
42
+ primary_metric: str = "pr_auc",
43
+ weights: Optional[Dict[str, float]] = None,
44
+ ):
45
+ self.primary_metric = primary_metric
46
+ self.weights = weights or {
47
+ "pr_auc": 0.40,
48
+ "generalization_gap": 0.20,
49
+ "cv_stability": 0.15,
50
+ "business_cost": 0.15,
51
+ "training_time": 0.05,
52
+ "interpretability": 0.05,
53
+ }
54
+
55
+ def compare(
56
+ self,
57
+ models: Dict[str, Any],
58
+ X_test: DataFrame,
59
+ y_test: Series,
60
+ X_train: Optional[DataFrame] = None,
61
+ y_train: Optional[Series] = None,
62
+ ) -> ComparisonResult:
63
+ model_metrics = {}
64
+
65
+ for name, model in models.items():
66
+ metrics = self._evaluate_model(model, X_test, y_test, X_train, y_train)
67
+ model_metrics[name] = metrics
68
+
69
+ ranking = self._rank_models(model_metrics)
70
+ best_model_name = ranking[0]
71
+ comparison_table = self._build_comparison_table(model_metrics, ranking)
72
+ selection_reason = self._generate_selection_reason(best_model_name, model_metrics)
73
+
74
+ return ComparisonResult(
75
+ model_metrics=model_metrics,
76
+ ranking=ranking,
77
+ best_model_name=best_model_name,
78
+ comparison_table=comparison_table,
79
+ selection_reason=selection_reason,
80
+ )
81
+
82
+ def _evaluate_model(
83
+ self,
84
+ model,
85
+ X_test: DataFrame,
86
+ y_test: Series,
87
+ X_train: Optional[DataFrame],
88
+ y_train: Optional[Series],
89
+ ) -> ModelMetrics:
90
+ y_pred = model.predict(X_test)
91
+ y_proba = model.predict_proba(X_test)[:, 1]
92
+
93
+ pr_auc = average_precision_score(y_test, y_proba)
94
+ roc_auc = roc_auc_score(y_test, y_proba)
95
+
96
+ train_test_gap = None
97
+ if X_train is not None and y_train is not None:
98
+ y_train_proba = model.predict_proba(X_train)[:, 1]
99
+ train_pr_auc = average_precision_score(y_train, y_train_proba)
100
+ train_test_gap = train_pr_auc - pr_auc
101
+
102
+ return ModelMetrics(
103
+ pr_auc=pr_auc,
104
+ roc_auc=roc_auc,
105
+ f1=f1_score(y_test, y_pred, zero_division=0),
106
+ precision=precision_score(y_test, y_pred, zero_division=0),
107
+ recall=recall_score(y_test, y_pred, zero_division=0),
108
+ accuracy=accuracy_score(y_test, y_pred),
109
+ train_test_gap=train_test_gap,
110
+ )
111
+
112
+ def _rank_models(self, model_metrics: Dict[str, ModelMetrics]) -> List[str]:
113
+ scores = {}
114
+ for name, metrics in model_metrics.items():
115
+ scores[name] = getattr(metrics, self.primary_metric)
116
+
117
+ return sorted(scores.keys(), key=lambda x: scores[x], reverse=True)
118
+
119
+ def _build_comparison_table(
120
+ self,
121
+ model_metrics: Dict[str, ModelMetrics],
122
+ ranking: List[str],
123
+ ) -> DataFrame:
124
+ rows = []
125
+ for name in ranking:
126
+ metrics = model_metrics[name]
127
+ rows.append({
128
+ "model": name,
129
+ "pr_auc": metrics.pr_auc,
130
+ "roc_auc": metrics.roc_auc,
131
+ "f1": metrics.f1,
132
+ "precision": metrics.precision,
133
+ "recall": metrics.recall,
134
+ "accuracy": metrics.accuracy,
135
+ "train_test_gap": metrics.train_test_gap,
136
+ })
137
+
138
+ return DataFrame(rows).set_index("model")
139
+
140
+ def _generate_selection_reason(
141
+ self,
142
+ best_model_name: str,
143
+ model_metrics: Dict[str, ModelMetrics],
144
+ ) -> str:
145
+ metrics = model_metrics[best_model_name]
146
+ return (
147
+ f"Selected {best_model_name} based on highest {self.primary_metric} "
148
+ f"({getattr(metrics, self.primary_metric):.4f})"
149
+ )
@@ -0,0 +1,138 @@
1
+ """Model evaluation metrics for customer retention prediction."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, Optional
5
+
6
+ import numpy as np
7
+ from sklearn.metrics import (
8
+ accuracy_score,
9
+ average_precision_score,
10
+ balanced_accuracy_score,
11
+ brier_score_loss,
12
+ classification_report,
13
+ confusion_matrix,
14
+ f1_score,
15
+ log_loss,
16
+ precision_recall_curve,
17
+ precision_score,
18
+ recall_score,
19
+ roc_auc_score,
20
+ roc_curve,
21
+ )
22
+
23
+ from customer_retention.core.compat import DataFrame, Series
24
+
25
+
26
+ @dataclass
27
+ class EvaluationResult:
28
+ metrics: Dict[str, float]
29
+ confusion_matrix: np.ndarray
30
+ classification_report: Dict[str, Any]
31
+ curves: Dict[str, Dict[str, np.ndarray]]
32
+ threshold: float
33
+ predictions: np.ndarray
34
+ probabilities: np.ndarray
35
+ dataset_name: Optional[str] = None
36
+
37
+
38
+ class ModelEvaluator:
39
+ def __init__(self, threshold: float = 0.5, positive_class: int = 1):
40
+ self.threshold = threshold
41
+ self.positive_class = positive_class
42
+
43
+ def evaluate(
44
+ self,
45
+ model,
46
+ X: DataFrame,
47
+ y: Series,
48
+ dataset_name: Optional[str] = None,
49
+ ) -> EvaluationResult:
50
+ probabilities = model.predict_proba(X)[:, self.positive_class]
51
+ predictions = (probabilities >= self.threshold).astype(int)
52
+
53
+ metrics = self._compute_metrics(y, predictions, probabilities)
54
+ cm = confusion_matrix(y, predictions)
55
+ report = classification_report(y, predictions, output_dict=True)
56
+ curves = self._compute_curves(y, probabilities)
57
+
58
+ return EvaluationResult(
59
+ metrics=metrics,
60
+ confusion_matrix=cm,
61
+ classification_report=report,
62
+ curves=curves,
63
+ threshold=self.threshold,
64
+ predictions=predictions,
65
+ probabilities=probabilities,
66
+ dataset_name=dataset_name,
67
+ )
68
+
69
+ def _compute_metrics(
70
+ self,
71
+ y_true: Series,
72
+ y_pred: np.ndarray,
73
+ y_proba: np.ndarray,
74
+ ) -> Dict[str, float]:
75
+ metrics = {
76
+ "accuracy": accuracy_score(y_true, y_pred),
77
+ "balanced_accuracy": balanced_accuracy_score(y_true, y_pred),
78
+ "precision": precision_score(y_true, y_pred, zero_division=0),
79
+ "recall": recall_score(y_true, y_pred, zero_division=0),
80
+ "f1": f1_score(y_true, y_pred, zero_division=0),
81
+ "roc_auc": roc_auc_score(y_true, y_proba),
82
+ "pr_auc": average_precision_score(y_true, y_proba),
83
+ "average_precision": average_precision_score(y_true, y_proba),
84
+ "brier_score": brier_score_loss(y_true, y_proba),
85
+ "log_loss": log_loss(y_true, y_proba),
86
+ }
87
+
88
+ lift_gain = self._compute_lift_gain(y_true, y_proba)
89
+ metrics.update(lift_gain)
90
+
91
+ return metrics
92
+
93
+ def _compute_curves(
94
+ self,
95
+ y_true: Series,
96
+ y_proba: np.ndarray,
97
+ ) -> Dict[str, Dict[str, np.ndarray]]:
98
+ fpr, tpr, roc_thresholds = roc_curve(y_true, y_proba)
99
+ precision, recall, pr_thresholds = precision_recall_curve(y_true, y_proba)
100
+
101
+ return {
102
+ "roc_curve": {
103
+ "fpr": fpr,
104
+ "tpr": tpr,
105
+ "thresholds": roc_thresholds,
106
+ },
107
+ "pr_curve": {
108
+ "precision": precision,
109
+ "recall": recall,
110
+ "thresholds": pr_thresholds,
111
+ },
112
+ }
113
+
114
+ def _compute_lift_gain(
115
+ self,
116
+ y_true: Series,
117
+ y_proba: np.ndarray,
118
+ ) -> Dict[str, float]:
119
+ y_true = np.array(y_true)
120
+ sorted_indices = np.argsort(y_proba)[::-1]
121
+ y_sorted = y_true[sorted_indices]
122
+
123
+ n_total = len(y_true)
124
+ n_positive = y_true.sum()
125
+ baseline_rate = n_positive / n_total
126
+
127
+ metrics = {}
128
+ for k in [10, 20]:
129
+ top_k_idx = int(n_total * k / 100)
130
+ top_k_positive = y_sorted[:top_k_idx].sum()
131
+
132
+ lift = (top_k_positive / top_k_idx) / baseline_rate if top_k_idx > 0 else 0
133
+ gain = top_k_positive / n_positive if n_positive > 0 else 0
134
+
135
+ metrics[f"lift_at_{k}"] = lift
136
+ metrics[f"gain_at_{k}"] = gain
137
+
138
+ return metrics
@@ -0,0 +1,131 @@
1
+ """Threshold optimization for classification models."""
2
+
3
+ from dataclasses import dataclass
4
+ from enum import Enum
5
+ from typing import Any, Dict, Optional
6
+
7
+ import numpy as np
8
+ from sklearn.metrics import confusion_matrix, f1_score, fbeta_score, precision_score, recall_score
9
+
10
+ from customer_retention.core.compat import DataFrame, Series
11
+
12
+
13
+ class OptimizationObjective(Enum):
14
+ MIN_COST = "min_cost"
15
+ MAX_F1 = "max_f1"
16
+ MAX_F2 = "max_f2"
17
+ TARGET_RECALL = "target_recall"
18
+ TARGET_PRECISION = "target_precision"
19
+
20
+
21
+ @dataclass
22
+ class ThresholdResult:
23
+ optimal_threshold: float
24
+ threshold_metrics: Dict[str, float]
25
+ cost_at_threshold: Optional[float]
26
+ comparison_default: Dict[str, Any]
27
+
28
+
29
+ class ThresholdOptimizer:
30
+ def __init__(
31
+ self,
32
+ objective: OptimizationObjective = OptimizationObjective.MAX_F1,
33
+ cost_fn: float = 100,
34
+ cost_fp: float = 10,
35
+ target_recall: Optional[float] = None,
36
+ target_precision: Optional[float] = None,
37
+ threshold_step: float = 0.01,
38
+ ):
39
+ self.objective = objective
40
+ self.cost_fn = cost_fn
41
+ self.cost_fp = cost_fp
42
+ self.target_recall = target_recall
43
+ self.target_precision = target_precision
44
+ self.threshold_step = threshold_step
45
+
46
+ def optimize(self, model, X: DataFrame, y: Series) -> ThresholdResult:
47
+ probabilities = model.predict_proba(X)[:, 1]
48
+ thresholds = np.arange(0.01, 1.0, self.threshold_step)
49
+
50
+ best_threshold = 0.5
51
+ best_score = float("-inf") if self.objective != OptimizationObjective.MIN_COST else float("inf")
52
+
53
+ for threshold in thresholds:
54
+ predictions = (probabilities >= threshold).astype(int)
55
+ score = self._calculate_score(y, predictions, probabilities, threshold)
56
+
57
+ if self._is_better_score(score, best_score):
58
+ best_score = score
59
+ best_threshold = threshold
60
+
61
+ optimal_predictions = (probabilities >= best_threshold).astype(int)
62
+ threshold_metrics = self._calculate_metrics(y, optimal_predictions)
63
+ cost_at_threshold = self._calculate_cost(y, optimal_predictions)
64
+ comparison_default = self._compare_with_default(y, probabilities, best_threshold)
65
+
66
+ return ThresholdResult(
67
+ optimal_threshold=best_threshold,
68
+ threshold_metrics=threshold_metrics,
69
+ cost_at_threshold=cost_at_threshold,
70
+ comparison_default=comparison_default,
71
+ )
72
+
73
+ def _calculate_score(self, y_true, y_pred, y_proba, threshold) -> float:
74
+ if self.objective == OptimizationObjective.MIN_COST:
75
+ return self._calculate_cost(y_true, y_pred)
76
+
77
+ if self.objective == OptimizationObjective.MAX_F1:
78
+ return f1_score(y_true, y_pred, zero_division=0)
79
+
80
+ if self.objective == OptimizationObjective.MAX_F2:
81
+ return fbeta_score(y_true, y_pred, beta=2, zero_division=0)
82
+
83
+ if self.objective == OptimizationObjective.TARGET_RECALL:
84
+ recall = recall_score(y_true, y_pred, zero_division=0)
85
+ if recall >= self.target_recall:
86
+ return precision_score(y_true, y_pred, zero_division=0)
87
+ return float("-inf")
88
+
89
+ if self.objective == OptimizationObjective.TARGET_PRECISION:
90
+ precision = precision_score(y_true, y_pred, zero_division=0)
91
+ if precision >= self.target_precision:
92
+ return recall_score(y_true, y_pred, zero_division=0)
93
+ return float("-inf")
94
+
95
+ return f1_score(y_true, y_pred, zero_division=0)
96
+
97
+ def _is_better_score(self, score: float, best_score: float) -> bool:
98
+ if self.objective == OptimizationObjective.MIN_COST:
99
+ return score < best_score
100
+ return score > best_score
101
+
102
+ def _calculate_cost(self, y_true, y_pred) -> float:
103
+ cm = confusion_matrix(y_true, y_pred)
104
+ tn, fp, fn, tp = cm.ravel()
105
+ return fn * self.cost_fn + fp * self.cost_fp
106
+
107
+ def _calculate_metrics(self, y_true, y_pred) -> Dict[str, float]:
108
+ return {
109
+ "precision": precision_score(y_true, y_pred, zero_division=0),
110
+ "recall": recall_score(y_true, y_pred, zero_division=0),
111
+ "f1": f1_score(y_true, y_pred, zero_division=0),
112
+ "f2": fbeta_score(y_true, y_pred, beta=2, zero_division=0),
113
+ }
114
+
115
+ def _compare_with_default(
116
+ self,
117
+ y_true: Series,
118
+ y_proba: np.ndarray,
119
+ optimal_threshold: float,
120
+ ) -> Dict[str, Any]:
121
+ default_threshold = 0.5
122
+ default_preds = (y_proba >= default_threshold).astype(int)
123
+ optimal_preds = (y_proba >= optimal_threshold).astype(int)
124
+
125
+ return {
126
+ "default_threshold": default_threshold,
127
+ "default_f1": f1_score(y_true, default_preds, zero_division=0),
128
+ "default_cost": self._calculate_cost(y_true, default_preds),
129
+ "optimal_f1": f1_score(y_true, optimal_preds, zero_division=0),
130
+ "optimal_cost": self._calculate_cost(y_true, optimal_preds),
131
+ }
@@ -0,0 +1,37 @@
1
+ from customer_retention.core.components.enums import Severity
2
+
3
+ from .alert_manager import (
4
+ Alert,
5
+ AlertChannel,
6
+ AlertCondition,
7
+ AlertConfig,
8
+ AlertLevel,
9
+ AlertManager,
10
+ AlertResult,
11
+ EmailSender,
12
+ SlackSender,
13
+ )
14
+ from .drift_detector import DriftConfig, DriftDetector, DriftResult, DriftType, FeatureDriftResult, TargetDriftResult
15
+ from .performance_monitor import (
16
+ CalibrationCurve,
17
+ DistributionAnalysis,
18
+ DistributionComparison,
19
+ MonitoringConfig,
20
+ PerformanceMonitor,
21
+ PerformanceResult,
22
+ PerformanceStatus,
23
+ ProportionAnalysis,
24
+ ProxyMetrics,
25
+ TrendReport,
26
+ )
27
+
28
+ __all__ = [
29
+ "Severity",
30
+ "DriftDetector", "DriftType", "DriftResult",
31
+ "DriftConfig", "FeatureDriftResult", "TargetDriftResult",
32
+ "PerformanceMonitor", "PerformanceResult", "PerformanceStatus",
33
+ "ProxyMetrics", "MonitoringConfig", "CalibrationCurve", "DistributionAnalysis",
34
+ "ProportionAnalysis", "DistributionComparison", "TrendReport",
35
+ "AlertManager", "Alert", "AlertLevel", "AlertChannel",
36
+ "AlertConfig", "AlertCondition", "AlertResult", "EmailSender", "SlackSender"
37
+ ]