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.
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/00_start_here.ipynb +647 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01_data_discovery.ipynb +1165 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_a_temporal_text_deep_dive.ipynb +961 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_temporal_deep_dive.ipynb +1690 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01b_temporal_quality.ipynb +679 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01c_temporal_patterns.ipynb +3305 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01d_event_aggregation.ipynb +1463 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02_column_deep_dive.ipynb +1430 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02a_text_columns_deep_dive.ipynb +854 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/03_quality_assessment.ipynb +1639 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/04_relationship_analysis.ipynb +1890 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/05_multi_dataset.ipynb +1457 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/06_feature_opportunities.ipynb +1624 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/07_modeling_readiness.ipynb +780 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/08_baseline_experiments.ipynb +979 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/09_business_alignment.ipynb +572 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/10_spec_generation.ipynb +1179 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/11_scoring_validation.ipynb +1418 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/12_view_documentation.ipynb +151 -0
- churnkit-0.75.0a1.dist-info/METADATA +229 -0
- churnkit-0.75.0a1.dist-info/RECORD +302 -0
- churnkit-0.75.0a1.dist-info/WHEEL +4 -0
- churnkit-0.75.0a1.dist-info/entry_points.txt +2 -0
- churnkit-0.75.0a1.dist-info/licenses/LICENSE +202 -0
- customer_retention/__init__.py +37 -0
- customer_retention/analysis/__init__.py +0 -0
- customer_retention/analysis/auto_explorer/__init__.py +62 -0
- customer_retention/analysis/auto_explorer/exploration_manager.py +470 -0
- customer_retention/analysis/auto_explorer/explorer.py +258 -0
- customer_retention/analysis/auto_explorer/findings.py +291 -0
- customer_retention/analysis/auto_explorer/layered_recommendations.py +485 -0
- customer_retention/analysis/auto_explorer/recommendation_builder.py +148 -0
- customer_retention/analysis/auto_explorer/recommendations.py +418 -0
- customer_retention/analysis/business/__init__.py +26 -0
- customer_retention/analysis/business/ab_test_designer.py +144 -0
- customer_retention/analysis/business/fairness_analyzer.py +166 -0
- customer_retention/analysis/business/intervention_matcher.py +121 -0
- customer_retention/analysis/business/report_generator.py +222 -0
- customer_retention/analysis/business/risk_profile.py +199 -0
- customer_retention/analysis/business/roi_analyzer.py +139 -0
- customer_retention/analysis/diagnostics/__init__.py +20 -0
- customer_retention/analysis/diagnostics/calibration_analyzer.py +133 -0
- customer_retention/analysis/diagnostics/cv_analyzer.py +144 -0
- customer_retention/analysis/diagnostics/error_analyzer.py +107 -0
- customer_retention/analysis/diagnostics/leakage_detector.py +394 -0
- customer_retention/analysis/diagnostics/noise_tester.py +140 -0
- customer_retention/analysis/diagnostics/overfitting_analyzer.py +190 -0
- customer_retention/analysis/diagnostics/segment_analyzer.py +122 -0
- customer_retention/analysis/discovery/__init__.py +8 -0
- customer_retention/analysis/discovery/config_generator.py +49 -0
- customer_retention/analysis/discovery/discovery_flow.py +19 -0
- customer_retention/analysis/discovery/type_inferencer.py +147 -0
- customer_retention/analysis/interpretability/__init__.py +13 -0
- customer_retention/analysis/interpretability/cohort_analyzer.py +185 -0
- customer_retention/analysis/interpretability/counterfactual.py +175 -0
- customer_retention/analysis/interpretability/individual_explainer.py +141 -0
- customer_retention/analysis/interpretability/pdp_generator.py +103 -0
- customer_retention/analysis/interpretability/shap_explainer.py +106 -0
- customer_retention/analysis/jupyter_save_hook.py +28 -0
- customer_retention/analysis/notebook_html_exporter.py +136 -0
- customer_retention/analysis/notebook_progress.py +60 -0
- customer_retention/analysis/plotly_preprocessor.py +154 -0
- customer_retention/analysis/recommendations/__init__.py +54 -0
- customer_retention/analysis/recommendations/base.py +158 -0
- customer_retention/analysis/recommendations/cleaning/__init__.py +11 -0
- customer_retention/analysis/recommendations/cleaning/consistency.py +107 -0
- customer_retention/analysis/recommendations/cleaning/deduplicate.py +94 -0
- customer_retention/analysis/recommendations/cleaning/impute.py +67 -0
- customer_retention/analysis/recommendations/cleaning/outlier.py +71 -0
- customer_retention/analysis/recommendations/datetime/__init__.py +3 -0
- customer_retention/analysis/recommendations/datetime/extract.py +149 -0
- customer_retention/analysis/recommendations/encoding/__init__.py +3 -0
- customer_retention/analysis/recommendations/encoding/categorical.py +114 -0
- customer_retention/analysis/recommendations/pipeline.py +74 -0
- customer_retention/analysis/recommendations/registry.py +76 -0
- customer_retention/analysis/recommendations/selection/__init__.py +3 -0
- customer_retention/analysis/recommendations/selection/drop_column.py +56 -0
- customer_retention/analysis/recommendations/transform/__init__.py +4 -0
- customer_retention/analysis/recommendations/transform/power.py +94 -0
- customer_retention/analysis/recommendations/transform/scale.py +112 -0
- customer_retention/analysis/visualization/__init__.py +15 -0
- customer_retention/analysis/visualization/chart_builder.py +2619 -0
- customer_retention/analysis/visualization/console.py +122 -0
- customer_retention/analysis/visualization/display.py +171 -0
- customer_retention/analysis/visualization/number_formatter.py +36 -0
- customer_retention/artifacts/__init__.py +3 -0
- customer_retention/artifacts/fit_artifact_registry.py +146 -0
- customer_retention/cli.py +93 -0
- customer_retention/core/__init__.py +0 -0
- customer_retention/core/compat/__init__.py +193 -0
- customer_retention/core/compat/detection.py +99 -0
- customer_retention/core/compat/ops.py +48 -0
- customer_retention/core/compat/pandas_backend.py +57 -0
- customer_retention/core/compat/spark_backend.py +75 -0
- customer_retention/core/components/__init__.py +11 -0
- customer_retention/core/components/base.py +79 -0
- customer_retention/core/components/components/__init__.py +13 -0
- customer_retention/core/components/components/deployer.py +26 -0
- customer_retention/core/components/components/explainer.py +26 -0
- customer_retention/core/components/components/feature_eng.py +33 -0
- customer_retention/core/components/components/ingester.py +34 -0
- customer_retention/core/components/components/profiler.py +34 -0
- customer_retention/core/components/components/trainer.py +38 -0
- customer_retention/core/components/components/transformer.py +36 -0
- customer_retention/core/components/components/validator.py +37 -0
- customer_retention/core/components/enums.py +33 -0
- customer_retention/core/components/orchestrator.py +94 -0
- customer_retention/core/components/registry.py +59 -0
- customer_retention/core/config/__init__.py +39 -0
- customer_retention/core/config/column_config.py +95 -0
- customer_retention/core/config/experiments.py +71 -0
- customer_retention/core/config/pipeline_config.py +117 -0
- customer_retention/core/config/source_config.py +83 -0
- customer_retention/core/utils/__init__.py +28 -0
- customer_retention/core/utils/leakage.py +85 -0
- customer_retention/core/utils/severity.py +53 -0
- customer_retention/core/utils/statistics.py +90 -0
- customer_retention/generators/__init__.py +0 -0
- customer_retention/generators/notebook_generator/__init__.py +167 -0
- customer_retention/generators/notebook_generator/base.py +55 -0
- customer_retention/generators/notebook_generator/cell_builder.py +49 -0
- customer_retention/generators/notebook_generator/config.py +47 -0
- customer_retention/generators/notebook_generator/databricks_generator.py +48 -0
- customer_retention/generators/notebook_generator/local_generator.py +48 -0
- customer_retention/generators/notebook_generator/project_init.py +174 -0
- customer_retention/generators/notebook_generator/runner.py +150 -0
- customer_retention/generators/notebook_generator/script_generator.py +110 -0
- customer_retention/generators/notebook_generator/stages/__init__.py +19 -0
- customer_retention/generators/notebook_generator/stages/base_stage.py +86 -0
- customer_retention/generators/notebook_generator/stages/s01_ingestion.py +100 -0
- customer_retention/generators/notebook_generator/stages/s02_profiling.py +95 -0
- customer_retention/generators/notebook_generator/stages/s03_cleaning.py +180 -0
- customer_retention/generators/notebook_generator/stages/s04_transformation.py +165 -0
- customer_retention/generators/notebook_generator/stages/s05_feature_engineering.py +115 -0
- customer_retention/generators/notebook_generator/stages/s06_feature_selection.py +97 -0
- customer_retention/generators/notebook_generator/stages/s07_model_training.py +176 -0
- customer_retention/generators/notebook_generator/stages/s08_deployment.py +81 -0
- customer_retention/generators/notebook_generator/stages/s09_monitoring.py +112 -0
- customer_retention/generators/notebook_generator/stages/s10_batch_inference.py +642 -0
- customer_retention/generators/notebook_generator/stages/s11_feature_store.py +348 -0
- customer_retention/generators/orchestration/__init__.py +23 -0
- customer_retention/generators/orchestration/code_generator.py +196 -0
- customer_retention/generators/orchestration/context.py +147 -0
- customer_retention/generators/orchestration/data_materializer.py +188 -0
- customer_retention/generators/orchestration/databricks_exporter.py +411 -0
- customer_retention/generators/orchestration/doc_generator.py +311 -0
- customer_retention/generators/pipeline_generator/__init__.py +26 -0
- customer_retention/generators/pipeline_generator/findings_parser.py +727 -0
- customer_retention/generators/pipeline_generator/generator.py +142 -0
- customer_retention/generators/pipeline_generator/models.py +166 -0
- customer_retention/generators/pipeline_generator/renderer.py +2125 -0
- customer_retention/generators/spec_generator/__init__.py +37 -0
- customer_retention/generators/spec_generator/databricks_generator.py +433 -0
- customer_retention/generators/spec_generator/generic_generator.py +373 -0
- customer_retention/generators/spec_generator/mlflow_pipeline_generator.py +685 -0
- customer_retention/generators/spec_generator/pipeline_spec.py +298 -0
- customer_retention/integrations/__init__.py +0 -0
- customer_retention/integrations/adapters/__init__.py +13 -0
- customer_retention/integrations/adapters/base.py +10 -0
- customer_retention/integrations/adapters/factory.py +25 -0
- customer_retention/integrations/adapters/feature_store/__init__.py +6 -0
- customer_retention/integrations/adapters/feature_store/base.py +57 -0
- customer_retention/integrations/adapters/feature_store/databricks.py +94 -0
- customer_retention/integrations/adapters/feature_store/feast_adapter.py +97 -0
- customer_retention/integrations/adapters/feature_store/local.py +75 -0
- customer_retention/integrations/adapters/mlflow/__init__.py +6 -0
- customer_retention/integrations/adapters/mlflow/base.py +32 -0
- customer_retention/integrations/adapters/mlflow/databricks.py +54 -0
- customer_retention/integrations/adapters/mlflow/experiment_tracker.py +161 -0
- customer_retention/integrations/adapters/mlflow/local.py +50 -0
- customer_retention/integrations/adapters/storage/__init__.py +5 -0
- customer_retention/integrations/adapters/storage/base.py +33 -0
- customer_retention/integrations/adapters/storage/databricks.py +76 -0
- customer_retention/integrations/adapters/storage/local.py +59 -0
- customer_retention/integrations/feature_store/__init__.py +47 -0
- customer_retention/integrations/feature_store/definitions.py +215 -0
- customer_retention/integrations/feature_store/manager.py +744 -0
- customer_retention/integrations/feature_store/registry.py +412 -0
- customer_retention/integrations/iteration/__init__.py +28 -0
- customer_retention/integrations/iteration/context.py +212 -0
- customer_retention/integrations/iteration/feedback_collector.py +184 -0
- customer_retention/integrations/iteration/orchestrator.py +168 -0
- customer_retention/integrations/iteration/recommendation_tracker.py +341 -0
- customer_retention/integrations/iteration/signals.py +212 -0
- customer_retention/integrations/llm_context/__init__.py +4 -0
- customer_retention/integrations/llm_context/context_builder.py +201 -0
- customer_retention/integrations/llm_context/prompts.py +100 -0
- customer_retention/integrations/streaming/__init__.py +103 -0
- customer_retention/integrations/streaming/batch_integration.py +149 -0
- customer_retention/integrations/streaming/early_warning_model.py +227 -0
- customer_retention/integrations/streaming/event_schema.py +214 -0
- customer_retention/integrations/streaming/online_store_writer.py +249 -0
- customer_retention/integrations/streaming/realtime_scorer.py +261 -0
- customer_retention/integrations/streaming/trigger_engine.py +293 -0
- customer_retention/integrations/streaming/window_aggregator.py +393 -0
- customer_retention/stages/__init__.py +0 -0
- customer_retention/stages/cleaning/__init__.py +9 -0
- customer_retention/stages/cleaning/base.py +28 -0
- customer_retention/stages/cleaning/missing_handler.py +160 -0
- customer_retention/stages/cleaning/outlier_handler.py +204 -0
- customer_retention/stages/deployment/__init__.py +28 -0
- customer_retention/stages/deployment/batch_scorer.py +106 -0
- customer_retention/stages/deployment/champion_challenger.py +299 -0
- customer_retention/stages/deployment/model_registry.py +182 -0
- customer_retention/stages/deployment/retraining_trigger.py +245 -0
- customer_retention/stages/features/__init__.py +73 -0
- customer_retention/stages/features/behavioral_features.py +266 -0
- customer_retention/stages/features/customer_segmentation.py +505 -0
- customer_retention/stages/features/feature_definitions.py +265 -0
- customer_retention/stages/features/feature_engineer.py +551 -0
- customer_retention/stages/features/feature_manifest.py +340 -0
- customer_retention/stages/features/feature_selector.py +239 -0
- customer_retention/stages/features/interaction_features.py +160 -0
- customer_retention/stages/features/temporal_features.py +243 -0
- customer_retention/stages/ingestion/__init__.py +9 -0
- customer_retention/stages/ingestion/load_result.py +32 -0
- customer_retention/stages/ingestion/loaders.py +195 -0
- customer_retention/stages/ingestion/source_registry.py +130 -0
- customer_retention/stages/modeling/__init__.py +31 -0
- customer_retention/stages/modeling/baseline_trainer.py +139 -0
- customer_retention/stages/modeling/cross_validator.py +125 -0
- customer_retention/stages/modeling/data_splitter.py +205 -0
- customer_retention/stages/modeling/feature_scaler.py +99 -0
- customer_retention/stages/modeling/hyperparameter_tuner.py +107 -0
- customer_retention/stages/modeling/imbalance_handler.py +282 -0
- customer_retention/stages/modeling/mlflow_logger.py +95 -0
- customer_retention/stages/modeling/model_comparator.py +149 -0
- customer_retention/stages/modeling/model_evaluator.py +138 -0
- customer_retention/stages/modeling/threshold_optimizer.py +131 -0
- customer_retention/stages/monitoring/__init__.py +37 -0
- customer_retention/stages/monitoring/alert_manager.py +328 -0
- customer_retention/stages/monitoring/drift_detector.py +201 -0
- customer_retention/stages/monitoring/performance_monitor.py +242 -0
- customer_retention/stages/preprocessing/__init__.py +5 -0
- customer_retention/stages/preprocessing/transformer_manager.py +284 -0
- customer_retention/stages/profiling/__init__.py +256 -0
- customer_retention/stages/profiling/categorical_distribution.py +269 -0
- customer_retention/stages/profiling/categorical_target_analyzer.py +274 -0
- customer_retention/stages/profiling/column_profiler.py +527 -0
- customer_retention/stages/profiling/distribution_analysis.py +483 -0
- customer_retention/stages/profiling/drift_detector.py +310 -0
- customer_retention/stages/profiling/feature_capacity.py +507 -0
- customer_retention/stages/profiling/pattern_analysis_config.py +513 -0
- customer_retention/stages/profiling/profile_result.py +212 -0
- customer_retention/stages/profiling/quality_checks.py +1632 -0
- customer_retention/stages/profiling/relationship_detector.py +256 -0
- customer_retention/stages/profiling/relationship_recommender.py +454 -0
- customer_retention/stages/profiling/report_generator.py +520 -0
- customer_retention/stages/profiling/scd_analyzer.py +151 -0
- customer_retention/stages/profiling/segment_analyzer.py +632 -0
- customer_retention/stages/profiling/segment_aware_outlier.py +265 -0
- customer_retention/stages/profiling/target_level_analyzer.py +217 -0
- customer_retention/stages/profiling/temporal_analyzer.py +388 -0
- customer_retention/stages/profiling/temporal_coverage.py +488 -0
- customer_retention/stages/profiling/temporal_feature_analyzer.py +692 -0
- customer_retention/stages/profiling/temporal_feature_engineer.py +703 -0
- customer_retention/stages/profiling/temporal_pattern_analyzer.py +636 -0
- customer_retention/stages/profiling/temporal_quality_checks.py +278 -0
- customer_retention/stages/profiling/temporal_target_analyzer.py +241 -0
- customer_retention/stages/profiling/text_embedder.py +87 -0
- customer_retention/stages/profiling/text_processor.py +115 -0
- customer_retention/stages/profiling/text_reducer.py +60 -0
- customer_retention/stages/profiling/time_series_profiler.py +303 -0
- customer_retention/stages/profiling/time_window_aggregator.py +376 -0
- customer_retention/stages/profiling/type_detector.py +382 -0
- customer_retention/stages/profiling/window_recommendation.py +288 -0
- customer_retention/stages/temporal/__init__.py +166 -0
- customer_retention/stages/temporal/access_guard.py +180 -0
- customer_retention/stages/temporal/cutoff_analyzer.py +235 -0
- customer_retention/stages/temporal/data_preparer.py +178 -0
- customer_retention/stages/temporal/point_in_time_join.py +134 -0
- customer_retention/stages/temporal/point_in_time_registry.py +148 -0
- customer_retention/stages/temporal/scenario_detector.py +163 -0
- customer_retention/stages/temporal/snapshot_manager.py +259 -0
- customer_retention/stages/temporal/synthetic_coordinator.py +66 -0
- customer_retention/stages/temporal/timestamp_discovery.py +531 -0
- customer_retention/stages/temporal/timestamp_manager.py +255 -0
- customer_retention/stages/transformation/__init__.py +13 -0
- customer_retention/stages/transformation/binary_handler.py +85 -0
- customer_retention/stages/transformation/categorical_encoder.py +245 -0
- customer_retention/stages/transformation/datetime_transformer.py +97 -0
- customer_retention/stages/transformation/numeric_transformer.py +181 -0
- customer_retention/stages/transformation/pipeline.py +257 -0
- customer_retention/stages/validation/__init__.py +60 -0
- customer_retention/stages/validation/adversarial_scoring_validator.py +205 -0
- customer_retention/stages/validation/business_sense_gate.py +173 -0
- customer_retention/stages/validation/data_quality_gate.py +235 -0
- customer_retention/stages/validation/data_validators.py +511 -0
- customer_retention/stages/validation/feature_quality_gate.py +183 -0
- customer_retention/stages/validation/gates.py +117 -0
- customer_retention/stages/validation/leakage_gate.py +352 -0
- customer_retention/stages/validation/model_validity_gate.py +213 -0
- customer_retention/stages/validation/pipeline_validation_runner.py +264 -0
- customer_retention/stages/validation/quality_scorer.py +544 -0
- customer_retention/stages/validation/rule_generator.py +57 -0
- customer_retention/stages/validation/scoring_pipeline_validator.py +446 -0
- customer_retention/stages/validation/timeseries_detector.py +769 -0
- customer_retention/transforms/__init__.py +47 -0
- customer_retention/transforms/artifact_store.py +50 -0
- customer_retention/transforms/executor.py +157 -0
- customer_retention/transforms/fitted.py +92 -0
- customer_retention/transforms/ops.py +148 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Dict, List, Optional, Union
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from customer_retention.core.compat import DataFrame, pd
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AggregationType(str, Enum):
|
|
13
|
+
SUM = "sum"
|
|
14
|
+
MEAN = "mean"
|
|
15
|
+
MAX = "max"
|
|
16
|
+
MIN = "min"
|
|
17
|
+
COUNT = "count"
|
|
18
|
+
STD = "std"
|
|
19
|
+
MEDIAN = "median"
|
|
20
|
+
FIRST = "first"
|
|
21
|
+
LAST = "last"
|
|
22
|
+
MODE = "mode"
|
|
23
|
+
NUNIQUE = "nunique"
|
|
24
|
+
MODE_RATIO = "mode_ratio"
|
|
25
|
+
ENTROPY = "entropy"
|
|
26
|
+
VALUE_COUNTS = "value_counts"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
CATEGORICAL_AGG_FUNCS = {"mode", "nunique", "mode_ratio", "entropy", "value_counts"}
|
|
30
|
+
NUMERIC_AGG_FUNCS = {"sum", "mean", "max", "min", "count", "std", "median", "first", "last"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class TimeWindow:
|
|
35
|
+
name: str
|
|
36
|
+
days: Optional[int]
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def from_string(cls, window_str: str) -> "TimeWindow":
|
|
40
|
+
window_str = window_str.lower().strip()
|
|
41
|
+
if window_str == "all_time":
|
|
42
|
+
return cls(name="all_time", days=None)
|
|
43
|
+
if window_str.endswith("d"):
|
|
44
|
+
return cls(name=window_str, days=int(window_str[:-1]))
|
|
45
|
+
if window_str.endswith("h"):
|
|
46
|
+
return cls(name=window_str, days=int(window_str[:-1]) / 24)
|
|
47
|
+
if window_str.endswith("w"):
|
|
48
|
+
return cls(name=window_str, days=int(window_str[:-1]) * 7)
|
|
49
|
+
raise ValueError(f"Unknown window format: {window_str}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class AggregationPlan:
|
|
54
|
+
entity_column: str
|
|
55
|
+
time_column: str
|
|
56
|
+
windows: List[TimeWindow]
|
|
57
|
+
value_columns: List[str]
|
|
58
|
+
agg_funcs: List[str]
|
|
59
|
+
feature_columns: List[str] = field(default_factory=list)
|
|
60
|
+
include_event_count: bool = True
|
|
61
|
+
include_recency: bool = False
|
|
62
|
+
include_tenure: bool = False
|
|
63
|
+
value_counts_categories: Dict[str, List[str]] = field(default_factory=dict)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class TimeWindowAggregator:
|
|
67
|
+
def __init__(self, entity_column: str, time_column: str):
|
|
68
|
+
self.entity_column = entity_column
|
|
69
|
+
self.time_column = time_column
|
|
70
|
+
|
|
71
|
+
def aggregate(
|
|
72
|
+
self, df: DataFrame, windows: Optional[List[str]] = None,
|
|
73
|
+
value_columns: Optional[List[str]] = None, agg_funcs: Optional[List[str]] = None,
|
|
74
|
+
reference_date: Optional[pd.Timestamp] = None, include_event_count: bool = False,
|
|
75
|
+
include_recency: bool = False, include_tenure: bool = False,
|
|
76
|
+
exclude_columns: Optional[List[str]] = None,
|
|
77
|
+
) -> DataFrame:
|
|
78
|
+
if len(df) == 0:
|
|
79
|
+
return pd.DataFrame()
|
|
80
|
+
|
|
81
|
+
df = df.copy()
|
|
82
|
+
df[self.time_column] = pd.to_datetime(df[self.time_column])
|
|
83
|
+
reference_date = self._validate_reference_date(df, reference_date)
|
|
84
|
+
parsed_windows = [TimeWindow.from_string(w) for w in (windows or ["30d"])]
|
|
85
|
+
|
|
86
|
+
exclude_set = set(exclude_columns) if exclude_columns else set()
|
|
87
|
+
if value_columns:
|
|
88
|
+
value_columns = [c for c in value_columns if c not in exclude_set]
|
|
89
|
+
|
|
90
|
+
entities = df[self.entity_column].unique()
|
|
91
|
+
result_data = {self.entity_column: entities}
|
|
92
|
+
|
|
93
|
+
if include_event_count or (value_columns is None and agg_funcs is None):
|
|
94
|
+
for window in parsed_windows:
|
|
95
|
+
result_data[f"event_count_{window.name}"] = self._compute_event_counts(
|
|
96
|
+
df, entities, window, reference_date)
|
|
97
|
+
|
|
98
|
+
if value_columns and agg_funcs:
|
|
99
|
+
self._add_value_aggregations(
|
|
100
|
+
result_data, df, entities, parsed_windows, value_columns, agg_funcs, reference_date)
|
|
101
|
+
|
|
102
|
+
if include_recency:
|
|
103
|
+
result_data["days_since_last_event"] = self._compute_recency(df, entities, reference_date)
|
|
104
|
+
if include_tenure:
|
|
105
|
+
result_data["days_since_first_event"] = self._compute_tenure(df, entities, reference_date)
|
|
106
|
+
|
|
107
|
+
result = pd.DataFrame(result_data)
|
|
108
|
+
result.attrs["aggregation_reference_date"] = (
|
|
109
|
+
reference_date.isoformat() if hasattr(reference_date, "isoformat") else str(reference_date))
|
|
110
|
+
result.attrs["aggregation_timestamp"] = pd.Timestamp.now().isoformat()
|
|
111
|
+
return result
|
|
112
|
+
|
|
113
|
+
def _add_value_aggregations(
|
|
114
|
+
self, result_data: Dict, df: DataFrame, entities: np.ndarray,
|
|
115
|
+
windows: List[TimeWindow], value_columns: List[str], agg_funcs: List[str],
|
|
116
|
+
reference_date: pd.Timestamp,
|
|
117
|
+
) -> None:
|
|
118
|
+
for window in windows:
|
|
119
|
+
for col in value_columns:
|
|
120
|
+
for func in agg_funcs:
|
|
121
|
+
if func == "value_counts":
|
|
122
|
+
result_data.update(self._compute_value_counts(df, entities, col, window, reference_date))
|
|
123
|
+
else:
|
|
124
|
+
result_data[f"{col}_{func}_{window.name}"] = self._compute_aggregation(
|
|
125
|
+
df, entities, col, func, window, reference_date)
|
|
126
|
+
|
|
127
|
+
def generate_plan(
|
|
128
|
+
self, df: DataFrame, windows: List[str], value_columns: List[str], agg_funcs: List[str],
|
|
129
|
+
include_event_count: bool = True, include_recency: bool = False, include_tenure: bool = False,
|
|
130
|
+
exclude_columns: Optional[List[str]] = None,
|
|
131
|
+
) -> AggregationPlan:
|
|
132
|
+
parsed_windows = [TimeWindow.from_string(w) for w in windows]
|
|
133
|
+
exclude_set = set(exclude_columns) if exclude_columns else set()
|
|
134
|
+
value_columns = [c for c in value_columns if c not in exclude_set]
|
|
135
|
+
|
|
136
|
+
feature_columns, value_counts_categories = self._build_feature_column_list(
|
|
137
|
+
df, parsed_windows, value_columns, agg_funcs, include_event_count, include_recency, include_tenure)
|
|
138
|
+
|
|
139
|
+
return AggregationPlan(
|
|
140
|
+
entity_column=self.entity_column, time_column=self.time_column, windows=parsed_windows,
|
|
141
|
+
value_columns=value_columns, agg_funcs=agg_funcs, feature_columns=feature_columns,
|
|
142
|
+
include_event_count=include_event_count, include_recency=include_recency,
|
|
143
|
+
include_tenure=include_tenure, value_counts_categories=value_counts_categories)
|
|
144
|
+
|
|
145
|
+
def _build_feature_column_list(
|
|
146
|
+
self, df: DataFrame, windows: List[TimeWindow], value_columns: List[str],
|
|
147
|
+
agg_funcs: List[str], include_event_count: bool, include_recency: bool, include_tenure: bool,
|
|
148
|
+
) -> tuple:
|
|
149
|
+
feature_columns = []
|
|
150
|
+
value_counts_categories: Dict[str, List[str]] = {}
|
|
151
|
+
|
|
152
|
+
if include_event_count:
|
|
153
|
+
feature_columns.extend(f"event_count_{w.name}" for w in windows)
|
|
154
|
+
|
|
155
|
+
for window in windows:
|
|
156
|
+
for col in value_columns:
|
|
157
|
+
for func in agg_funcs:
|
|
158
|
+
if func == "value_counts":
|
|
159
|
+
unique_vals = list(df[col].dropna().unique())
|
|
160
|
+
value_counts_categories[col] = unique_vals
|
|
161
|
+
feature_columns.extend(f"{col}_{val}_count_{window.name}" for val in unique_vals)
|
|
162
|
+
else:
|
|
163
|
+
feature_columns.append(f"{col}_{func}_{window.name}")
|
|
164
|
+
|
|
165
|
+
if include_recency:
|
|
166
|
+
feature_columns.append("days_since_last_event")
|
|
167
|
+
if include_tenure:
|
|
168
|
+
feature_columns.append("days_since_first_event")
|
|
169
|
+
|
|
170
|
+
return feature_columns, value_counts_categories
|
|
171
|
+
|
|
172
|
+
def _validate_reference_date(self, df: DataFrame, reference_date: Optional[pd.Timestamp]) -> pd.Timestamp:
|
|
173
|
+
data_min, data_max = df[self.time_column].min(), df[self.time_column].max()
|
|
174
|
+
current_date = pd.Timestamp.now()
|
|
175
|
+
|
|
176
|
+
if reference_date is None:
|
|
177
|
+
warnings.warn(
|
|
178
|
+
f"reference_date not provided, defaulting to data max ({data_max}). "
|
|
179
|
+
"For production use, provide explicit reference_date for PIT correctness. "
|
|
180
|
+
"This ensures features are computed as-of a specific point in time.",
|
|
181
|
+
UserWarning, stacklevel=3)
|
|
182
|
+
return data_max
|
|
183
|
+
|
|
184
|
+
if reference_date > current_date:
|
|
185
|
+
warnings.warn(
|
|
186
|
+
f"reference_date ({reference_date}) is in the future (current: {current_date}). "
|
|
187
|
+
"This may indicate incorrect date handling. Features will use future data.",
|
|
188
|
+
UserWarning, stacklevel=3)
|
|
189
|
+
|
|
190
|
+
if reference_date < data_min:
|
|
191
|
+
warnings.warn(
|
|
192
|
+
f"reference_date ({reference_date}) is before all data ({data_min}). "
|
|
193
|
+
"All time-windowed features will be empty or zero.",
|
|
194
|
+
UserWarning, stacklevel=3)
|
|
195
|
+
|
|
196
|
+
return reference_date
|
|
197
|
+
|
|
198
|
+
def _compute_event_counts(
|
|
199
|
+
self, df: DataFrame, entities: np.ndarray, window: TimeWindow, reference_date: pd.Timestamp,
|
|
200
|
+
) -> np.ndarray:
|
|
201
|
+
filtered_df = self._filter_by_window(df, window, reference_date)
|
|
202
|
+
counts = filtered_df.groupby(self.entity_column).size()
|
|
203
|
+
return np.array([counts.get(e, 0) for e in entities])
|
|
204
|
+
|
|
205
|
+
def _filter_by_window(self, df: DataFrame, window: TimeWindow, reference_date: pd.Timestamp) -> DataFrame:
|
|
206
|
+
if window.days is None:
|
|
207
|
+
return df
|
|
208
|
+
cutoff = reference_date - pd.Timedelta(days=window.days)
|
|
209
|
+
return df[df[self.time_column] >= cutoff]
|
|
210
|
+
|
|
211
|
+
def _compute_aggregation(
|
|
212
|
+
self,
|
|
213
|
+
df: DataFrame,
|
|
214
|
+
entities: np.ndarray,
|
|
215
|
+
value_column: str,
|
|
216
|
+
agg_func: str,
|
|
217
|
+
window: TimeWindow,
|
|
218
|
+
reference_date: pd.Timestamp,
|
|
219
|
+
) -> np.ndarray:
|
|
220
|
+
filtered_df = self._filter_by_window(df, window, reference_date)
|
|
221
|
+
if len(filtered_df) == 0:
|
|
222
|
+
default = 0 if agg_func in ["sum", "count", "nunique"] else np.nan
|
|
223
|
+
return np.full(len(entities), default)
|
|
224
|
+
|
|
225
|
+
is_numeric = pd.api.types.is_numeric_dtype(df[value_column])
|
|
226
|
+
if agg_func in CATEGORICAL_AGG_FUNCS:
|
|
227
|
+
return self._compute_categorical_agg(filtered_df, entities, value_column, agg_func)
|
|
228
|
+
elif agg_func in NUMERIC_AGG_FUNCS and not is_numeric:
|
|
229
|
+
return np.full(len(entities), np.nan)
|
|
230
|
+
return self._compute_numeric_agg(filtered_df, entities, value_column, agg_func)
|
|
231
|
+
|
|
232
|
+
def _compute_numeric_agg(
|
|
233
|
+
self, filtered_df: DataFrame, entities: np.ndarray, value_column: str, agg_func: str
|
|
234
|
+
) -> np.ndarray:
|
|
235
|
+
if agg_func == "count":
|
|
236
|
+
agg_result = filtered_df.groupby(self.entity_column)[value_column].count()
|
|
237
|
+
else:
|
|
238
|
+
agg_result = filtered_df.groupby(self.entity_column)[value_column].agg(agg_func)
|
|
239
|
+
default = 0 if agg_func in ["sum", "count"] else np.nan
|
|
240
|
+
return np.array([agg_result.get(e, default) for e in entities])
|
|
241
|
+
|
|
242
|
+
def _compute_categorical_agg(
|
|
243
|
+
self, filtered_df: DataFrame, entities: np.ndarray, value_column: str, agg_func: str
|
|
244
|
+
) -> np.ndarray:
|
|
245
|
+
if agg_func == "mode":
|
|
246
|
+
return self._agg_mode(filtered_df, entities, value_column)
|
|
247
|
+
elif agg_func == "nunique":
|
|
248
|
+
return self._agg_nunique(filtered_df, entities, value_column)
|
|
249
|
+
elif agg_func == "mode_ratio":
|
|
250
|
+
return self._agg_mode_ratio(filtered_df, entities, value_column)
|
|
251
|
+
elif agg_func == "entropy":
|
|
252
|
+
return self._agg_entropy(filtered_df, entities, value_column)
|
|
253
|
+
return np.full(len(entities), np.nan)
|
|
254
|
+
|
|
255
|
+
def _agg_mode(self, df: DataFrame, entities: np.ndarray, col: str) -> np.ndarray:
|
|
256
|
+
def get_mode(x):
|
|
257
|
+
if len(x) == 0:
|
|
258
|
+
return None
|
|
259
|
+
return x.value_counts().idxmax()
|
|
260
|
+
|
|
261
|
+
mode_result = df.groupby(self.entity_column)[col].apply(get_mode)
|
|
262
|
+
return np.array([mode_result.get(e, None) for e in entities], dtype=object)
|
|
263
|
+
|
|
264
|
+
def _agg_nunique(self, df: DataFrame, entities: np.ndarray, col: str) -> np.ndarray:
|
|
265
|
+
nunique_result = df.groupby(self.entity_column)[col].nunique()
|
|
266
|
+
return np.array([nunique_result.get(e, 0) for e in entities])
|
|
267
|
+
|
|
268
|
+
def _agg_mode_ratio(self, df: DataFrame, entities: np.ndarray, col: str) -> np.ndarray:
|
|
269
|
+
def get_mode_ratio(x):
|
|
270
|
+
if len(x) == 0:
|
|
271
|
+
return np.nan
|
|
272
|
+
counts = x.value_counts()
|
|
273
|
+
return counts.iloc[0] / len(x)
|
|
274
|
+
|
|
275
|
+
ratio_result = df.groupby(self.entity_column)[col].apply(get_mode_ratio)
|
|
276
|
+
return np.array([ratio_result.get(e, np.nan) for e in entities])
|
|
277
|
+
|
|
278
|
+
def _agg_entropy(self, df: DataFrame, entities: np.ndarray, col: str) -> np.ndarray:
|
|
279
|
+
def calc_entropy(x):
|
|
280
|
+
if len(x) == 0:
|
|
281
|
+
return np.nan
|
|
282
|
+
probs = x.value_counts(normalize=True)
|
|
283
|
+
if len(probs) == 1:
|
|
284
|
+
return 0.0
|
|
285
|
+
return -np.sum(probs * np.log2(probs))
|
|
286
|
+
|
|
287
|
+
entropy_result = df.groupby(self.entity_column)[col].apply(calc_entropy)
|
|
288
|
+
return np.array([entropy_result.get(e, np.nan) for e in entities])
|
|
289
|
+
|
|
290
|
+
def _compute_value_counts(
|
|
291
|
+
self, df: DataFrame, entities: np.ndarray, col: str, window: TimeWindow, reference_date: pd.Timestamp
|
|
292
|
+
) -> Dict[str, np.ndarray]:
|
|
293
|
+
filtered_df = self._filter_by_window(df, window, reference_date)
|
|
294
|
+
unique_values = df[col].dropna().unique()
|
|
295
|
+
result = {}
|
|
296
|
+
for val in unique_values:
|
|
297
|
+
col_name = f"{col}_{val}_count_{window.name}"
|
|
298
|
+
if len(filtered_df) == 0:
|
|
299
|
+
result[col_name] = np.zeros(len(entities))
|
|
300
|
+
else:
|
|
301
|
+
counts = filtered_df[filtered_df[col] == val].groupby(self.entity_column).size()
|
|
302
|
+
result[col_name] = np.array([counts.get(e, 0) for e in entities])
|
|
303
|
+
return result
|
|
304
|
+
|
|
305
|
+
def _compute_recency(self, df: DataFrame, entities: np.ndarray, reference_date: pd.Timestamp) -> np.ndarray:
|
|
306
|
+
last_dates = df.groupby(self.entity_column)[self.time_column].max()
|
|
307
|
+
days_since_last = (reference_date - last_dates).dt.days
|
|
308
|
+
return np.array([days_since_last.get(e, np.nan) for e in entities])
|
|
309
|
+
|
|
310
|
+
def _compute_tenure(self, df: DataFrame, entities: np.ndarray, reference_date: pd.Timestamp) -> np.ndarray:
|
|
311
|
+
first_dates = df.groupby(self.entity_column)[self.time_column].min()
|
|
312
|
+
days_since_first = (reference_date - first_dates).dt.days
|
|
313
|
+
return np.array([days_since_first.get(e, np.nan) for e in entities])
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def save_aggregated_parquet(df: DataFrame, path: Union[str, Path]) -> Dict[str, str]:
|
|
317
|
+
import pyarrow as pa
|
|
318
|
+
import pyarrow.parquet as pq
|
|
319
|
+
|
|
320
|
+
path = Path(path)
|
|
321
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
322
|
+
|
|
323
|
+
metadata = _extract_temporal_metadata(df)
|
|
324
|
+
|
|
325
|
+
df_clean = df.copy()
|
|
326
|
+
df_clean.attrs = {}
|
|
327
|
+
table = pa.Table.from_pandas(df_clean)
|
|
328
|
+
|
|
329
|
+
if metadata:
|
|
330
|
+
existing_metadata = table.schema.metadata or {}
|
|
331
|
+
encoded_metadata = {k.encode("utf-8"): v.encode("utf-8") for k, v in metadata.items()}
|
|
332
|
+
encoded_metadata.update(existing_metadata)
|
|
333
|
+
table = table.replace_schema_metadata(encoded_metadata)
|
|
334
|
+
|
|
335
|
+
pq.write_table(table, path)
|
|
336
|
+
return metadata
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _extract_temporal_metadata(df: DataFrame) -> Dict[str, str]:
|
|
340
|
+
metadata = {}
|
|
341
|
+
for key in ["aggregation_reference_date", "aggregation_timestamp"]:
|
|
342
|
+
if key in df.attrs:
|
|
343
|
+
value = df.attrs[key]
|
|
344
|
+
metadata[key] = value.isoformat() if hasattr(value, "isoformat") else str(value)
|
|
345
|
+
return metadata
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def save_aggregated_delta(df: DataFrame, path: Union[str, Path]) -> Dict[str, str]:
|
|
349
|
+
import json as _json
|
|
350
|
+
|
|
351
|
+
path = Path(path)
|
|
352
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
353
|
+
|
|
354
|
+
metadata = _extract_temporal_metadata(df)
|
|
355
|
+
|
|
356
|
+
try:
|
|
357
|
+
from customer_retention.integrations.adapters.factory import get_delta
|
|
358
|
+
storage = get_delta(force_local=True)
|
|
359
|
+
storage.write(df.copy(), str(path))
|
|
360
|
+
except ImportError:
|
|
361
|
+
df.to_parquet(str(path) + ".parquet", index=False)
|
|
362
|
+
|
|
363
|
+
if metadata:
|
|
364
|
+
sidecar_path = path.parent / f"{path.name}_temporal_metadata.json"
|
|
365
|
+
with open(sidecar_path, "w") as f:
|
|
366
|
+
_json.dump(metadata, f, indent=2)
|
|
367
|
+
|
|
368
|
+
return metadata
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def save_aggregated(df: DataFrame, path: Union[str, Path]) -> Dict[str, str]:
|
|
372
|
+
try:
|
|
373
|
+
from customer_retention.integrations.adapters.factory import get_delta # noqa: F401
|
|
374
|
+
return save_aggregated_delta(df, path)
|
|
375
|
+
except ImportError:
|
|
376
|
+
return save_aggregated_parquet(df, path)
|