upgini 1.2.171a4287.dev1__tar.gz → 1.2.172a4366.dev1__tar.gz

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 (94) hide show
  1. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/PKG-INFO +4 -4
  2. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/README.md +3 -3
  3. upgini-1.2.172a4366.dev1/src/upgini/__about__.py +1 -0
  4. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/data_source/data_source_publisher.py +8 -0
  5. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/features_enricher.py +97 -21
  6. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/metadata.py +5 -4
  7. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/report/assemble.py +3 -13
  8. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/report/data.py +4 -4
  9. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/report/html.py +25 -9
  10. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/report/template.html +56 -33
  11. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/psi.py +145 -35
  12. upgini-1.2.171a4287.dev1/src/upgini/__about__.py +0 -1
  13. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/.gitignore +0 -0
  14. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/LICENSE +0 -0
  15. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/pyproject.toml +0 -0
  16. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/__init__.py +0 -0
  17. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/ads.py +0 -0
  18. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/ads_management/__init__.py +0 -0
  19. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/ads_management/ads_manager.py +0 -0
  20. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/__init__.py +0 -0
  21. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/all_operators.py +0 -0
  22. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/binary.py +0 -0
  23. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/date.py +0 -0
  24. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/feature.py +0 -0
  25. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/groupby.py +0 -0
  26. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/operand.py +0 -0
  27. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/operator.py +0 -0
  28. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/__init__.py +0 -0
  29. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/base.py +0 -0
  30. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/cross.py +0 -0
  31. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/delta.py +0 -0
  32. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/lag.py +0 -0
  33. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/numpy_kernels.py +0 -0
  34. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/roll.py +0 -0
  35. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/trend.py +0 -0
  36. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/timeseries/volatility.py +0 -0
  37. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/unary.py +0 -0
  38. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/utils.py +0 -0
  39. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/autofe/vector.py +0 -0
  40. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/data_source/__init__.py +0 -0
  41. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/dataset.py +0 -0
  42. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/errors.py +0 -0
  43. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/http.py +0 -0
  44. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/mdc/__init__.py +0 -0
  45. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/mdc/context.py +0 -0
  46. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/metrics.py +0 -0
  47. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/normalizer/__init__.py +0 -0
  48. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/normalizer/normalize_utils.py +0 -0
  49. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/report/__init__.py +0 -0
  50. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/report/stats.py +0 -0
  51. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/resource_bundle/__init__.py +0 -0
  52. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/resource_bundle/exceptions.py +0 -0
  53. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/resource_bundle/strings.properties +0 -0
  54. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/resource_bundle/strings_widget.properties +0 -0
  55. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/sampler/__init__.py +0 -0
  56. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/sampler/base.py +0 -0
  57. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/sampler/random_under_sampler.py +0 -0
  58. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/sampler/utils.py +0 -0
  59. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/search_task.py +0 -0
  60. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/spinner.py +0 -0
  61. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/Roboto-Regular.ttf +0 -0
  62. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/__init__.py +0 -0
  63. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/base_search_key_detector.py +0 -0
  64. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/blocked_time_series.py +0 -0
  65. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/config.py +0 -0
  66. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/country_utils.py +0 -0
  67. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/cpu_utils.py +0 -0
  68. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/custom_loss_utils.py +0 -0
  69. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/cv_utils.py +0 -0
  70. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/datetime_utils.py +0 -0
  71. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/deduplicate_utils.py +0 -0
  72. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/display_utils.py +0 -0
  73. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/email_utils.py +0 -0
  74. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/fallback_progress_bar.py +0 -0
  75. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/feature_info.py +0 -0
  76. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/features_validator.py +0 -0
  77. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/format.py +0 -0
  78. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/hash_utils.py +0 -0
  79. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/ip_utils.py +0 -0
  80. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/mstats.py +0 -0
  81. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/one_hot_encoder.py +0 -0
  82. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/phone_utils.py +0 -0
  83. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/postal_code_utils.py +0 -0
  84. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/progress_bar.py +0 -0
  85. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/pyarrow_utils.py +0 -0
  86. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/sample_utils.py +0 -0
  87. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/search_key_derivations.py +0 -0
  88. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/sklearn_ext.py +0 -0
  89. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/sort.py +0 -0
  90. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/target_utils.py +0 -0
  91. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/track_info.py +0 -0
  92. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/ts_utils.py +0 -0
  93. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/utils/warning_counter.py +0 -0
  94. {upgini-1.2.171a4287.dev1 → upgini-1.2.172a4366.dev1}/src/upgini/version_validator.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: upgini
3
- Version: 1.2.171a4287.dev1
3
+ Version: 1.2.172a4366.dev1
4
4
  Summary: Intelligent data search & enrichment for Machine Learning
5
5
  Project-URL: Bug Reports, https://github.com/upgini/upgini/issues
6
6
  Project-URL: Homepage, https://upgini.com/
@@ -752,7 +752,7 @@ enricher.fit(
752
752
 
753
753
  ### Control feature stability with PSI parameters
754
754
 
755
- `FeaturesEnricher` supports Population Stability Index (PSI) calculation on eval_set to evaluate feature stability over time. You can control this behavior using stability parameters in `fit` and `fit_transform` methods:
755
+ `FeaturesEnricher` supports Population Stability Index (PSI) to evaluate how much feature distributions move. With an eval set, PSI compares the full training distribution to the full eval distribution. If several eval sets are passed, one is selected: the set that ends latest among those that start on or after the first training date, or, when every eval set starts earlier, the set whose start is closest to training. With no eval set, the training set is split into time intervals and each later interval is compared with the earliest one. You can control this behavior using stability parameters in `fit` and `fit_transform` methods:
756
756
 
757
757
  ```python
758
758
  enricher = FeaturesEnricher(
@@ -776,9 +776,9 @@ enriched_df = enricher.fit_transform(
776
776
 
777
777
  **Stability parameters:**
778
778
  - `stability_threshold` (float, default=0.2): PSI threshold value. Features with PSI above this threshold will be excluded from the final feature set, except original client features when `select_features=False`. Lower values mean stricter stability requirements.
779
- - `stability_agg_func` (str, default="max"): Function to aggregate PSI values across time intervals. Options: "max" (most conservative), "min" (least conservative), "mean" (balanced approach).
779
+ - `stability_agg_func` (str, default="max"): Function to aggregate PSI values across training time intervals, used when no eval set is passed. Options: "max" (most conservative), "min" (least conservative), "mean" (balanced approach). A single train-versus-eval PSI is already one number, so the aggregation does not change it.
780
780
 
781
- **PSI (Population Stability Index)** measures how much feature distribution changes over time. Lower PSI values indicate more stable features, which are generally more reliable for production ML models. PSI is calculated on the eval_set, which should contain the most recent dates relative to the training dataset.
781
+ **PSI (Population Stability Index)** measures how much a feature distribution changes. Lower PSI values indicate more stable features, which are generally more reliable for production ML models.
782
782
 
783
783
  ### Use custom loss function in feature selection & metrics calculation
784
784
 
@@ -707,7 +707,7 @@ enricher.fit(
707
707
 
708
708
  ### Control feature stability with PSI parameters
709
709
 
710
- `FeaturesEnricher` supports Population Stability Index (PSI) calculation on eval_set to evaluate feature stability over time. You can control this behavior using stability parameters in `fit` and `fit_transform` methods:
710
+ `FeaturesEnricher` supports Population Stability Index (PSI) to evaluate how much feature distributions move. With an eval set, PSI compares the full training distribution to the full eval distribution. If several eval sets are passed, one is selected: the set that ends latest among those that start on or after the first training date, or, when every eval set starts earlier, the set whose start is closest to training. With no eval set, the training set is split into time intervals and each later interval is compared with the earliest one. You can control this behavior using stability parameters in `fit` and `fit_transform` methods:
711
711
 
712
712
  ```python
713
713
  enricher = FeaturesEnricher(
@@ -731,9 +731,9 @@ enriched_df = enricher.fit_transform(
731
731
 
732
732
  **Stability parameters:**
733
733
  - `stability_threshold` (float, default=0.2): PSI threshold value. Features with PSI above this threshold will be excluded from the final feature set, except original client features when `select_features=False`. Lower values mean stricter stability requirements.
734
- - `stability_agg_func` (str, default="max"): Function to aggregate PSI values across time intervals. Options: "max" (most conservative), "min" (least conservative), "mean" (balanced approach).
734
+ - `stability_agg_func` (str, default="max"): Function to aggregate PSI values across training time intervals, used when no eval set is passed. Options: "max" (most conservative), "min" (least conservative), "mean" (balanced approach). A single train-versus-eval PSI is already one number, so the aggregation does not change it.
735
735
 
736
- **PSI (Population Stability Index)** measures how much feature distribution changes over time. Lower PSI values indicate more stable features, which are generally more reliable for production ML models. PSI is calculated on the eval_set, which should contain the most recent dates relative to the training dataset.
736
+ **PSI (Population Stability Index)** measures how much a feature distribution changes. Lower PSI values indicate more stable features, which are generally more reliable for production ML models.
737
737
 
738
738
  ### Use custom loss function in feature selection & metrics calculation
739
739
 
@@ -0,0 +1 @@
1
+ __version__ = "1.2.172a4366.dev1"
@@ -37,6 +37,8 @@ class DataSourcePublisher:
37
37
  FINAL_STATUSES = ["COMPLETED", "FAILED", "TIMED_OUT"]
38
38
  ACCEPTABLE_UPDATE_FREQUENCIES = ["Daily", "Weekly", "Monthly", "Quarterly", "Annually"]
39
39
  DEFAULT_GENERATE_EMBEDDINGS = dict()
40
+ SEARCH_AVG_DATE_FIELD = "search_avg_date"
41
+ AVAILABLE_ONLY_FROM_RUSSIA_FIELD = "available_only_from_russia"
40
42
 
41
43
  def __init__(self, api_key: Optional[str] = None, endpoint: Optional[str] = None, logs_enabled=True):
42
44
  self._rest_client = get_rest_client(endpoint, api_key)
@@ -448,6 +450,8 @@ class DataSourcePublisher:
448
450
  target_user_email: str,
449
451
  selected_features: Optional[List[str]] = None,
450
452
  exclude_features: Optional[List[str]] = None,
453
+ search_avg_date: Optional[str] = None,
454
+ available_only_from_russia: Optional[bool] = None,
451
455
  ) -> str:
452
456
  if not search_ids:
453
457
  raise Exception("Empty search ids list")
@@ -463,6 +467,10 @@ class DataSourcePublisher:
463
467
  request["selected_features"] = selected_features
464
468
  if exclude_features:
465
469
  request["exclude_features"] = exclude_features
470
+ if isinstance(search_avg_date, str) and search_avg_date.strip():
471
+ request[self.SEARCH_AVG_DATE_FIELD] = search_avg_date.strip()
472
+ if isinstance(available_only_from_russia, bool):
473
+ request[self.AVAILABLE_ONLY_FROM_RUSSIA_FIELD] = available_only_from_russia
466
474
 
467
475
  response = self._rest_client.union_search_tasks(request, "trace_id")
468
476
  print(response)
@@ -1122,6 +1122,7 @@ class FeaturesEnricher(TransformerMixin):
1122
1122
  _cv,
1123
1123
  columns_renaming,
1124
1124
  _,
1125
+ _,
1125
1126
  ) = prepared_data
1126
1127
 
1127
1128
  gc.collect()
@@ -1556,16 +1557,13 @@ class FeaturesEnricher(TransformerMixin):
1556
1557
  date_column = self._get_date_column(search_keys)
1557
1558
  has_date = date_column is not None and date_column in validated_X.columns
1558
1559
  if not has_date:
1559
- self.logger.info("No date column for OOT PSI calculation")
1560
- return
1561
- if not validated_eval_set:
1562
- self.logger.info("No eval set for OOT PSI calculation")
1560
+ self.logger.info("No date column for PSI calculation")
1563
1561
  return
1564
- if validated_X[date_column].nunique() <= 1:
1565
- self.logger.warning("Constant date for OOT PSI calculation")
1562
+ if not validated_eval_set and validated_X[date_column].nunique() <= 1:
1563
+ self.logger.warning("Constant date for train PSI calculation")
1566
1564
  return
1567
1565
  if self.cv is not None and self.cv.is_time_series():
1568
- self.logger.warning("Time series CV is not supported for OOT PSI calculation")
1566
+ self.logger.warning("Time series CV is not supported for PSI calculation")
1569
1567
  return
1570
1568
 
1571
1569
  cat_features_from_backend = self.__get_categorical_features()
@@ -1604,18 +1602,19 @@ class FeaturesEnricher(TransformerMixin):
1604
1602
  (
1605
1603
  validated_X,
1606
1604
  _,
1607
- y_sorted,
1608
- _,
1609
1605
  _,
1606
+ fitting_enriched_X,
1607
+ enriched_y_sorted,
1610
1608
  fitting_eval_set_dict,
1611
1609
  search_keys,
1612
1610
  _,
1613
1611
  _,
1614
1612
  columns_renaming,
1615
1613
  eval_set_dates,
1614
+ train_dates,
1616
1615
  ) = prepared_data
1617
1616
 
1618
- model_task_type = self.model_task_type or define_task(y_sorted, has_date, self.logger, silent=True)
1617
+ model_task_type = self.model_task_type or define_task(enriched_y_sorted, has_date, self.logger, silent=True)
1619
1618
  cat_features = self._get_cat_features_for_psi(
1620
1619
  client_cat_features=client_cat_features,
1621
1620
  cat_features_from_backend=cat_features_from_backend,
@@ -1627,8 +1626,11 @@ class FeaturesEnricher(TransformerMixin):
1627
1626
  unstable_features = self._check_stability(
1628
1627
  validated_X,
1629
1628
  validated_eval_set,
1629
+ fitting_enriched_X,
1630
+ enriched_y_sorted,
1630
1631
  fitting_eval_set_dict,
1631
1632
  eval_set_dates,
1633
+ train_dates,
1632
1634
  search_keys,
1633
1635
  stability_threshold,
1634
1636
  stability_agg_func,
@@ -1645,17 +1647,34 @@ class FeaturesEnricher(TransformerMixin):
1645
1647
  self,
1646
1648
  X: pd.DataFrame,
1647
1649
  eval_set: list[tuple[pd.DataFrame, pd.Series]],
1650
+ enriched_X: pd.DataFrame,
1651
+ y: pd.Series | None,
1648
1652
  enriched_eval_set: dict[int, tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]],
1649
1653
  eval_set_dates: dict[int, pd.Series],
1654
+ train_dates: pd.Series | None,
1650
1655
  search_keys: dict[str, SearchKey],
1651
1656
  stability_threshold: float,
1652
1657
  stability_agg_func: str | None,
1653
1658
  cat_features: list[str],
1654
1659
  model_task_type: ModelTaskType,
1655
1660
  ) -> list[str]:
1656
- # Find latest eval set or earliest if all eval sets are before train set
1657
1661
  date_column = self._get_date_column(search_keys)
1662
+ if not eval_set:
1663
+ self.logger.info("No eval set. Calculating feature PSI on train intervals")
1664
+ train_df = self._train_interval_psi_frame(enriched_X, y, train_dates, date_column)
1665
+ if train_df is None:
1666
+ return []
1667
+ return self._drop_unstable_by_psi(
1668
+ train_df,
1669
+ None,
1670
+ cat_features,
1671
+ date_column,
1672
+ model_task_type,
1673
+ stability_agg_func,
1674
+ stability_threshold,
1675
+ )
1658
1676
 
1677
+ # Find latest eval set or earliest if all eval sets are before train set
1659
1678
  date_converter = DateTimeConverter(
1660
1679
  date_column, self.date_format, self.logger, self.bundle, generate_cyclical_features=False
1661
1680
  )
@@ -1709,20 +1728,68 @@ class FeaturesEnricher(TransformerMixin):
1709
1728
  selected_eval_set_idx = max(eval_dates, key=lambda x: x[1])[0]
1710
1729
 
1711
1730
  checking_eval_set = enriched_eval_set[selected_eval_set_idx]
1712
-
1713
- checking_eval_set_df = (
1714
- checking_eval_set[2]
1715
- if checking_eval_set[1] is None or checking_eval_set[1].isna().all()
1716
- else pd.concat([checking_eval_set[2], checking_eval_set[1].to_frame(TARGET)], axis=1)
1731
+ checking_eval_set_df = self._with_target(checking_eval_set[2], checking_eval_set[1])
1732
+ reference_df = self._with_target(enriched_X, y)
1733
+ self.logger.info(f"Calculating feature PSI of eval set {selected_eval_set_idx + 1} against train")
1734
+ return self._drop_unstable_by_psi(
1735
+ checking_eval_set_df,
1736
+ reference_df,
1737
+ cat_features,
1738
+ date_column,
1739
+ model_task_type,
1740
+ stability_agg_func,
1741
+ stability_threshold,
1717
1742
  )
1718
- checking_eval_set_df = checking_eval_set_df.copy()
1719
1743
 
1720
- checking_eval_set_df[date_column] = date_converter.to_date_ms(eval_set_dates[selected_eval_set_idx].to_frame())
1744
+ def _train_interval_psi_frame(
1745
+ self,
1746
+ enriched_X: pd.DataFrame,
1747
+ y: pd.Series | None,
1748
+ train_dates: pd.Series | None,
1749
+ date_column: str | None,
1750
+ ) -> pd.DataFrame | None:
1751
+ if train_dates is None or len(train_dates) != len(enriched_X):
1752
+ self.logger.warning("Train dates are missing or not aligned with enriched train for PSI calculation")
1753
+ return None
1754
+ date_converter = DateTimeConverter(
1755
+ date_column, self.date_format, self.logger, self.bundle, generate_cyclical_features=False
1756
+ )
1757
+ dates_ms = date_converter.to_date_ms(train_dates.to_frame(name=date_column))
1758
+ if dates_ms.nunique(dropna=True) <= 1:
1759
+ self.logger.warning("Constant date for train PSI calculation")
1760
+ return None
1761
+ frame = enriched_X.copy()
1762
+ frame[date_column] = dates_ms.to_numpy()
1763
+ if y is not None and not y.isna().all():
1764
+ frame[TARGET] = y.to_numpy()
1765
+ return frame
1766
+
1767
+ def _with_target(self, df: pd.DataFrame, target: pd.Series | None) -> pd.DataFrame:
1768
+ if target is None or target.isna().all():
1769
+ return df
1770
+ with_target = df.copy()
1771
+ with_target[TARGET] = target.to_numpy()
1772
+ return with_target
1721
1773
 
1722
- cat_features = [c for c in cat_features if c in checking_eval_set_df.columns]
1774
+ def _drop_unstable_by_psi(
1775
+ self,
1776
+ current_df: pd.DataFrame,
1777
+ reference_df: pd.DataFrame | None,
1778
+ cat_features: list[str],
1779
+ date_column: str | None,
1780
+ model_task_type: ModelTaskType,
1781
+ stability_agg_func: str | None,
1782
+ stability_threshold: float,
1783
+ ) -> list[str]:
1784
+ cat_features = [column for column in cat_features if column in current_df.columns]
1723
1785
 
1724
1786
  psi_values_sparse = calculate_sparsity_psi(
1725
- checking_eval_set_df, cat_features, date_column, self.logger, model_task_type
1787
+ current_df,
1788
+ cat_features,
1789
+ date_column,
1790
+ self.logger,
1791
+ model_task_type,
1792
+ reference_df=reference_df,
1726
1793
  )
1727
1794
 
1728
1795
  self.logger.info(f"PSI values by sparsity: {psi_values_sparse}")
@@ -1736,7 +1803,13 @@ class FeaturesEnricher(TransformerMixin):
1736
1803
  self.logger.info(f"Unstable by sparsity features ({stability_threshold}): {sorted(unstable_by_sparsity)}")
1737
1804
 
1738
1805
  psi_values = calculate_features_psi(
1739
- checking_eval_set_df, cat_features, date_column, self.logger, model_task_type, stability_agg_func
1806
+ current_df,
1807
+ cat_features,
1808
+ date_column,
1809
+ self.logger,
1810
+ model_task_type,
1811
+ stability_agg_func,
1812
+ reference_df=reference_df,
1740
1813
  )
1741
1814
 
1742
1815
  self.logger.info(f"PSI values by value: {psi_values}")
@@ -3109,6 +3182,8 @@ class FeaturesEnricher(TransformerMixin):
3109
3182
  enriched_eval_y_sorted,
3110
3183
  )
3111
3184
 
3185
+ date_X_sorted = X_sorted[date_column].copy() if date_column is not None and date_column in X_sorted.columns else None
3186
+
3112
3187
  return (
3113
3188
  validated_X,
3114
3189
  fitting_X,
@@ -3121,6 +3196,7 @@ class FeaturesEnricher(TransformerMixin):
3121
3196
  cv,
3122
3197
  columns_renaming,
3123
3198
  eval_set_dates,
3199
+ date_X_sorted,
3124
3200
  )
3125
3201
 
3126
3202
  @dataclass
@@ -310,10 +310,11 @@ class FeaturesMetadataV2(BaseModel):
310
310
  from_online_api: Optional[bool] = None
311
311
  psi_value: Optional[float] = None
312
312
  drift_score: Optional[float] = None
313
- # Calendar month ("2024-01") -> PSI. The earliest month is the reference and is 0.
314
- monthly_psi: Optional[Dict[str, float]] = None
315
- # Calendar month ("2024-01") -> univariate ROC AUC.
316
- monthly_roc_auc: Optional[Dict[str, float]] = None
313
+ # Sample id ("train", "eval_1") -> calendar month ("2024-01") -> PSI.
314
+ # The earliest train month is the reference and is 0.
315
+ monthly_psi: Optional[Dict[str, Dict[str, float]]] = None
316
+ # Sample id ("train", "eval_1") -> calendar month -> univariate ROC AUC.
317
+ monthly_roc_auc: Optional[Dict[str, Dict[str, float]]] = None
317
318
 
318
319
 
319
320
  class HitRateMetrics(BaseModel):
@@ -22,7 +22,7 @@ from upgini.report.data import (
22
22
  SearchResultsSummary,
23
23
  SourceRow,
24
24
  )
25
- from upgini.report.stats import PSI_CRITICAL, PSI_WARNING, compute_report_charts, normalize_month_label
25
+ from upgini.report.stats import PSI_CRITICAL, PSI_WARNING, compute_report_charts
26
26
  from upgini.resource_bundle import ResourceBundle
27
27
  from upgini.utils.feature_info import CLIENT_SOURCE, GENERATED_SOURCE, FeatureInfo
28
28
 
@@ -154,8 +154,8 @@ def build_search_results(
154
154
  feature_monthly_psi: list[FeatureMonthlyPsi] = []
155
155
  feature_monthly_auc: list[FeatureMonthlyAuc] = []
156
156
  for row, meta in paired:
157
- psi = _month_value_map(meta.monthly_psi)
158
- auc = _month_value_map(meta.monthly_roc_auc)
157
+ psi = meta.monthly_psi or {}
158
+ auc = meta.monthly_roc_auc or {}
159
159
  if psi:
160
160
  feature_monthly_psi.append(FeatureMonthlyPsi(feature=row.name, psi=psi))
161
161
  if auc:
@@ -321,16 +321,6 @@ def _psi_status(psi: Optional[float]) -> Optional[str]:
321
321
  return "good"
322
322
 
323
323
 
324
- def _month_value_map(values: Optional[dict]) -> dict[str, float]:
325
- mapped: dict[str, float] = {}
326
- for key, value in (values or {}).items():
327
- label = normalize_month_label(key)
328
- if label is None or value is None or pd.isna(value):
329
- continue
330
- mapped[label] = float(value)
331
- return mapped
332
-
333
-
334
324
  def _has_nonzero_shap_value(shap: Optional[float]) -> bool:
335
325
  return shap is not None and not pd.isna(shap) and shap != 0
336
326
 
@@ -138,15 +138,15 @@ class ScorePsi:
138
138
  @dataclass
139
139
  class FeatureMonthlyPsi:
140
140
  feature: str
141
- # Report month label ("Jan 2024") -> PSI.
142
- psi: dict[str, float] = field(default_factory=dict)
141
+ # Sample id ("train", "eval_1") -> calendar month ("2024-01") -> PSI.
142
+ psi: dict[str, dict[str, float]] = field(default_factory=dict)
143
143
 
144
144
 
145
145
  @dataclass
146
146
  class FeatureMonthlyAuc:
147
147
  feature: str
148
- # Report month label ("Jan 2024") -> ROC AUC.
149
- auc: dict[str, float] = field(default_factory=dict)
148
+ # Sample id ("train", "eval_1") -> calendar month ("2024-01") -> ROC AUC.
149
+ auc: dict[str, dict[str, float]] = field(default_factory=dict)
150
150
 
151
151
 
152
152
  @dataclass
@@ -5,7 +5,7 @@ from pathlib import Path
5
5
  from typing import Optional
6
6
 
7
7
  from upgini.report.data import FeatureRow, ReportCharts, ReportData, SampleStats, SearchResultsSummary, SourceRow
8
- from upgini.report.stats import MEAN_AXIS_PADDING, psi_axis_max, sorted_month_labels
8
+ from upgini.report.stats import MEAN_AXIS_PADDING, psi_axis_max
9
9
  from upgini.utils.feature_info import CLIENT_SOURCE, GENERATED_SOURCE
10
10
 
11
11
  _TEMPLATE_PATH = Path(__file__).with_name("template.html")
@@ -311,21 +311,37 @@ def _score_stability_payload(charts: ReportCharts, samples: list[dict]) -> dict:
311
311
  def _feature_stability_payload(data: ReportData, charts: ReportCharts) -> dict:
312
312
  psi_rows = data.feature_monthly_psi
313
313
  auc_rows = data.feature_monthly_auc
314
- series_months = [month for row in psi_rows for month in row.psi] + [month for row in auc_rows for month in row.auc]
315
- months = sorted_month_labels([*charts.timeline_months, *series_months])
316
- psi_values = [value for row in psi_rows for value in row.psi.values()]
314
+ psi_values = [value for row in psi_rows for months in row.psi.values() for value in months.values()]
315
+ sample_ids: list[str] = []
316
+ for row in psi_rows:
317
+ for sample_id in row.psi:
318
+ if sample_id not in sample_ids:
319
+ sample_ids.append(sample_id)
320
+ for row in auc_rows:
321
+ for sample_id in row.auc:
322
+ if sample_id not in sample_ids:
323
+ sample_ids.append(sample_id)
317
324
  return {
318
- "months": months,
319
325
  "psiAxisMax": psi_axis_max(psi_values, charts.psi_critical),
320
326
  "thresholds": {"warning": charts.psi_warning, "critical": charts.psi_critical},
321
327
  "features": [{"feature": row.feature, "provider": row.provider} for row in data.model_feature_shap],
322
- "psi": [_aligned_feature_series(row.feature, row.psi, months) for row in psi_rows],
323
- "auc": [_aligned_feature_series(row.feature, row.auc, months) for row in auc_rows],
328
+ "bySample": {
329
+ sample_id: {
330
+ "psi": _feature_series(psi_rows, "psi", sample_id),
331
+ "auc": _feature_series(auc_rows, "auc", sample_id),
332
+ }
333
+ for sample_id in sample_ids
334
+ },
324
335
  }
325
336
 
326
337
 
327
- def _aligned_feature_series(feature: str, values: dict[str, float], months: list[str]) -> dict:
328
- return {"feature": feature, "values": [values.get(month) for month in months]}
338
+ def _feature_series(rows, field: str, sample_id: str) -> list[dict]:
339
+ series = []
340
+ for row in rows:
341
+ values = getattr(row, field).get(sample_id)
342
+ if values:
343
+ series.append({"feature": row.feature, "values": values})
344
+ return series
329
345
 
330
346
 
331
347
  def _stat_row(label: str, samples: list[dict], by_id: dict[str, SampleStats], value) -> dict:
@@ -90,9 +90,9 @@
90
90
  </section>
91
91
 
92
92
  <section id="feature-stability" class="section">
93
- <div class="section-head"><div><h2>Feature stability</h2><p>Monthly PSI and univariate ROC AUC for the selected model feature. PSI reference: earliest train month.</p></div><select id="featureStabilitySelect" class="control feature-select" aria-label="Feature"></select></div>
94
- <div class="panel chart-panel"><div class="chart-head"><div><strong>Monthly PSI</strong><div class="source-name">Reference distribution is the earliest train month</div></div><button class="button ghost chart-export" data-chart="featurePsiChart">Save PNG</button></div><div class="threshold-legend" id="featurePsiThresholdLegend"></div><div class="canvas-wrap"><canvas id="featurePsiChart" aria-label="Monthly feature PSI" width="1596" height="560"></canvas><div class="chart-tooltip" id="featurePsiTooltip"></div></div></div>
95
- <div class="panel chart-panel" style="margin-top:14px"><div class="chart-head"><div><strong>Monthly ROC AUC</strong><div class="source-name">Univariate ROC AUC of the feature against the target</div></div><button class="button ghost chart-export" data-chart="featureAucChart">Save PNG</button></div><div class="canvas-wrap"><canvas id="featureAucChart" aria-label="Monthly feature ROC AUC" width="1596" height="560"></canvas><div class="chart-tooltip" id="featureAucTooltip"></div></div></div>
93
+ <div class="section-head"><div><h2>Feature stability</h2><p>Monthly PSI and univariate ROC AUC for the selected model feature, for all samples. PSI reference: earliest train month.</p></div><select id="featureStabilitySelect" class="control feature-select" aria-label="Feature"></select></div>
94
+ <div class="panel chart-panel"><div class="chart-head"><div><strong>Monthly PSI</strong><div class="source-name">Reference distribution is the earliest train month</div></div><button class="button ghost chart-export" data-chart="featurePsiChart">Save PNG</button></div><div class="threshold-legend" id="featurePsiThresholdLegend"></div><div class="legend" id="featurePsiSampleLegend" style="margin-bottom:10px"></div><div class="canvas-wrap"><canvas id="featurePsiChart" aria-label="Monthly feature PSI for all samples" width="1596" height="560"></canvas><div class="chart-tooltip" id="featurePsiTooltip"></div></div></div>
95
+ <div class="panel chart-panel" style="margin-top:14px"><div class="chart-head"><div><strong>Monthly ROC AUC</strong><div class="source-name">Univariate ROC AUC of the feature against the target</div></div><button class="button ghost chart-export" data-chart="featureAucChart">Save PNG</button></div><div class="legend" id="featureAucSampleLegend" style="margin-bottom:10px"></div><div class="canvas-wrap"><canvas id="featureAucChart" aria-label="Monthly feature ROC AUC for all samples" width="1596" height="560"></canvas><div class="chart-tooltip" id="featureAucTooltip"></div></div></div>
96
96
  </section>
97
97
  </main>
98
98
  </div>
@@ -257,6 +257,10 @@ const REPORT_DATA = __REPORT_DATA__;
257
257
  `<span><i style="background:${s.color}"></i>${s.label} target = 1</span>`).join('');
258
258
  const psiSampleLegend = document.getElementById('psiSampleLegend');
259
259
  if (psiSampleLegend) psiSampleLegend.innerHTML = sampleLegend;
260
+ ['featurePsiSampleLegend', 'featureAucSampleLegend'].forEach(id => {
261
+ const el = document.getElementById(id);
262
+ if (el) el.innerHTML = sampleLegend;
263
+ });
260
264
  }
261
265
 
262
266
  /* --------------------------------------------------------------- selects */
@@ -587,9 +591,12 @@ const REPORT_DATA = __REPORT_DATA__;
587
591
  const features = (D.featureStability && D.featureStability.features) || [];
588
592
  el.innerHTML = features.map(f => `<option value="${esc(f.feature)}">${esc(f.feature)}</option>`).join('');
589
593
  }
590
- function featureMonths() {
591
- const cfg = D.featureStability || {};
592
- return cfg.months || [];
594
+ const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
595
+ function monthLabel(key) {
596
+ const match = /^(\d{4})-(\d{2})$/.exec(String(key));
597
+ if (!match) return String(key);
598
+ const name = MONTH_NAMES[Number(match[2]) - 1];
599
+ return name ? `${name} ${match[1]}` : String(key);
593
600
  }
594
601
  function selectedFeature() {
595
602
  const el = document.getElementById('featureStabilitySelect');
@@ -598,31 +605,56 @@ const REPORT_DATA = __REPORT_DATA__;
598
605
  function featureSeries(kind) {
599
606
  const cfg = D.featureStability || {};
600
607
  const name = selectedFeature();
601
- const row = (cfg[kind] || []).find(item => item.feature === name);
602
- return (row && row.values) || [];
608
+ const rows = availableSamples(cfg.bySample).map(sample => {
609
+ const bucket = (cfg.bySample && cfg.bySample[sample.id]) || {};
610
+ const row = (bucket[kind] || []).find(item => item.feature === name);
611
+ return { sample, byMonth: (row && row.values) || {} };
612
+ });
613
+ const months = [...new Set(rows.flatMap(row => Object.keys(row.byMonth)))].sort();
614
+ return {
615
+ months,
616
+ series: rows.map(row => ({
617
+ sample: row.sample,
618
+ values: months.map(month => month in row.byMonth ? row.byMonth[month] : null)
619
+ }))
620
+ };
603
621
  }
604
622
  function featureRecord(name) {
605
623
  return (D.features || []).find(f => f.name === name) || {};
606
624
  }
607
- function featureTooltip(month, name, metric, value) {
625
+ function featureTooltip(month, sample, name, metric, value) {
608
626
  const f = featureRecord(name);
609
- return `<b>${esc(month)} · ${esc(name)}</b><br>${metric}: ${fmt3(value)}` +
627
+ return `<b>${esc(month)} · ${esc(sample.label)} · ${esc(name)}</b><br>${metric}: ${fmt3(value)}` +
610
628
  `<br>Rows: ${f.rows == null ? '—' : num(f.rows)}` +
611
629
  `<br>Labeled: ${f.labeled == null ? '—' : num(f.labeled)}` +
612
630
  `<br>Coverage: ${pct1(f.coverage)}` +
613
631
  `<br>Missing rate: ${pct1(f.missingRate)}`;
614
632
  }
615
- function drawFeatureLine(c, w, h, hitKey, values, color, yFor, dotColor) {
616
- const months = featureMonths();
633
+ function drawFeatureLine(c, w, h, hitKey, months, series, yFor, metric) {
617
634
  hits[hitKey] = [];
618
635
  if (!months.length) return;
619
636
  const count = months.length;
637
+ const name = selectedFeature();
620
638
  const x = i => 48 + (count === 1 ? (w - 70) / 2 : i * (w - 70) / (count - 1));
621
- strokeSeries(c, values.map((val, i) => val == null ? null : { x: x(i), y: yFor(val) }), color, 4, dotColor);
639
+ series.forEach((row, sampleIndex) => {
640
+ const offset = (sampleIndex - (series.length - 1) / 2) * 10;
641
+ strokeSeries(
642
+ c,
643
+ row.values.map((val, i) => val == null ? null : { x: x(i) + offset, y: yFor(val) }),
644
+ row.sample.color,
645
+ 4
646
+ );
647
+ row.values.forEach((val, i) => {
648
+ if (val == null) return;
649
+ hits[hitKey].push({
650
+ x: x(i) + offset, y: yFor(val), r: 12,
651
+ html: featureTooltip(monthLabel(months[i]), row.sample, name, metric, val)
652
+ });
653
+ });
654
+ });
622
655
  c.font = '10px Inter, sans-serif';
623
656
  months.forEach((m, i) => {
624
- if (values[i] != null) hits[hitKey].push({ x: x(i), y: yFor(values[i]), r: 12, index: i });
625
- const parts = String(m).split(' ');
657
+ const parts = monthLabel(m).split(' ');
626
658
  c.fillStyle = '#7d8885';
627
659
  c.fillText(parts[0], x(i) - 8, h - 22);
628
660
  c.fillText(parts[1] || '', x(i) - 12, h - 9);
@@ -630,10 +662,10 @@ const REPORT_DATA = __REPORT_DATA__;
630
662
  }
631
663
  function drawFeaturePsi() {
632
664
  const cfg = D.featureStability || {};
633
- const months = featureMonths();
665
+ const series = featureSeries('psi');
666
+ const months = series.months;
634
667
  const { c, w, h } = setupCanvas('featurePsiChart');
635
668
  if (!months.length) return;
636
- const values = featureSeries('psi');
637
669
  const max = cfg.psiAxisMax || 1;
638
670
  const th = cfg.thresholds || { warning: 0.1, critical: 0.25 };
639
671
  const y = val => 18 + (max - val) / max * (h - 62);
@@ -650,15 +682,14 @@ const REPORT_DATA = __REPORT_DATA__;
650
682
  const yy = 18 + i * (h - 62) / 4;
651
683
  c.fillText((max - i * max / 4).toFixed(2), 4, yy + 3);
652
684
  }
653
- drawFeatureLine(c, w, h, 'featurePsi', values, '#1645ee', y,
654
- i => values[i] > th.critical ? '#d45b5b' : values[i] >= th.warning ? '#e19132' : '#53cc61');
685
+ drawFeatureLine(c, w, h, 'featurePsi', months, series.series, y, 'PSI');
655
686
  }
656
687
  function drawFeatureAuc() {
657
- const months = featureMonths();
688
+ const series = featureSeries('auc');
689
+ const months = series.months;
658
690
  const { c, w, h } = setupCanvas('featureAucChart');
659
691
  if (!months.length) return;
660
- const values = featureSeries('auc');
661
- const present = values.filter(v => v != null && !Number.isNaN(Number(v))).map(Number);
692
+ const present = series.series.flatMap(row => row.values).filter(v => v != null && !Number.isNaN(Number(v))).map(Number);
662
693
  let lo = 0, hi = 1;
663
694
  if (present.length) {
664
695
  const minAuc = Math.min(...present);
@@ -674,7 +705,7 @@ const REPORT_DATA = __REPORT_DATA__;
674
705
  c.beginPath(); c.moveTo(40, yy); c.lineTo(w - 15, yy); c.stroke();
675
706
  c.fillText((hi - i * span / 4).toFixed(2), 4, yy + 3);
676
707
  }
677
- drawFeatureLine(c, w, h, 'featureAuc', values, '#53cc61', y);
708
+ drawFeatureLine(c, w, h, 'featureAuc', months, series.series, y, 'ROC AUC');
678
709
  }
679
710
 
680
711
  /* ------------------------------------------------------------ SHAP list */
@@ -761,16 +792,8 @@ const REPORT_DATA = __REPORT_DATA__;
761
792
  return `<b>${p.month} · ${p.sample.label}</b><br>PSI: ${fmt3(p.psi)}` +
762
793
  `<br>Rows: ${numOrDash(p.rows)}<br>Score coverage: ${pct1(p.scoreCoverage)}<br>Reference: first period (baseline month)`;
763
794
  });
764
- bindTooltip('featurePsiChart', 'featurePsiTooltip', 'featurePsi', i => {
765
- const months = featureMonths();
766
- const values = featureSeries('psi');
767
- return featureTooltip(months[i], selectedFeature(), 'PSI', values[i]);
768
- });
769
- bindTooltip('featureAucChart', 'featureAucTooltip', 'featureAuc', i => {
770
- const months = featureMonths();
771
- const values = featureSeries('auc');
772
- return featureTooltip(months[i], selectedFeature(), 'ROC AUC', values[i]);
773
- });
795
+ bindTooltip('featurePsiChart', 'featurePsiTooltip', 'featurePsi', (_, hit) => hit.html);
796
+ bindTooltip('featureAucChart', 'featureAucTooltip', 'featureAuc', (_, hit) => hit.html);
774
797
  }
775
798
 
776
799
  /* -------------------------------------------------------- sample tooltip */
@@ -48,23 +48,127 @@ def calculate_sparsity_psi(
48
48
  stability_agg_func: str | None = None,
49
49
  psi_features_params: StabilityParams = DEFAULT_FEATURES_PARAMS,
50
50
  psi_target_params: StabilityParams = DEFAULT_TARGET_PARAMS,
51
+ reference_df: pd.DataFrame | None = None,
51
52
  ) -> Dict[str, float]:
52
- sparse_features = df.columns[df.isna().sum() > 0].to_list()
53
- if len(sparse_features) > 0:
54
- logger.info(f"Calculating sparsity stability for {len(sparse_features)} sparse features")
55
- sparse_df = df[sparse_features].notna()
53
+ if reference_df is None:
54
+ sparse_features = df.columns[df.isna().sum() > 0].to_list()
55
+ else:
56
+ sparse_features = [
57
+ column
58
+ for column in df.columns
59
+ if column != date_column
60
+ and column in reference_df.columns
61
+ and (df[column].isna().any() or reference_df[column].isna().any())
62
+ ]
63
+ if len(sparse_features) == 0:
64
+ return {}
65
+ logger.info(f"Calculating sparsity stability for {len(sparse_features)} sparse features")
66
+ sparse_df = df[sparse_features].notna()
67
+ sparse_reference = None
68
+ if reference_df is None:
56
69
  sparse_df[date_column] = df[date_column]
57
- return calculate_features_psi(
58
- sparse_df,
59
- cat_features,
60
- date_column,
61
- logger,
70
+ else:
71
+ sparse_reference = reference_df[sparse_features].notna()
72
+ return calculate_features_psi(
73
+ sparse_df,
74
+ cat_features,
75
+ date_column,
76
+ logger,
77
+ model_task_type,
78
+ stability_agg_func,
79
+ psi_target_params,
80
+ psi_features_params,
81
+ reference_df=sparse_reference,
82
+ )
83
+
84
+
85
+ def _column_psi(
86
+ current_data: list[pd.Series],
87
+ reference_data: pd.Series,
88
+ is_numerical: bool,
89
+ params: StabilityParams,
90
+ agg_func: Callable,
91
+ ) -> float | None:
92
+ return _stability_agg(
93
+ current_data,
94
+ reference_data=reference_data,
95
+ is_numerical=is_numerical,
96
+ min_values_in_bin=params.min_values_in_bin,
97
+ n_bins=params.n_bins,
98
+ cat_top_pct=params.cat_top_pct,
99
+ agg_func=agg_func,
100
+ )
101
+
102
+
103
+ def _target_psi_blocks_features(
104
+ current_targets: list[pd.Series],
105
+ reference_target: pd.Series,
106
+ model_task_type: ModelTaskType,
107
+ stability_agg_func: str | None,
108
+ psi_target_params: StabilityParams,
109
+ logger: logging.Logger,
110
+ ) -> bool:
111
+ target_agg_func = _get_agg_func(stability_agg_func or psi_target_params.agg)
112
+ logger.info(f"Calculating target PSI with agg function {target_agg_func}")
113
+ target_psi = _column_psi(
114
+ current_targets,
115
+ reference_target,
116
+ model_task_type == ModelTaskType.REGRESSION,
117
+ psi_target_params,
118
+ target_agg_func,
119
+ )
120
+ if target_psi is None or np.isnan(target_psi):
121
+ logger.info("Cannot determine target PSI. Skip feature PSI check")
122
+ return True
123
+ if target_psi > psi_target_params.threshold:
124
+ logger.info(
125
+ f"Target PSI {target_psi} is more than threshold {psi_target_params.threshold}. Skip feature PSI check"
126
+ )
127
+ return True
128
+ return False
129
+
130
+
131
+ def _features_psi_against_reference(
132
+ df: pd.DataFrame,
133
+ reference_df: pd.DataFrame,
134
+ cat_features: list[str],
135
+ date_column: str,
136
+ logger: logging.Logger,
137
+ model_task_type: ModelTaskType,
138
+ stability_agg_func: str | None,
139
+ psi_features_params: StabilityParams,
140
+ psi_target_params: StabilityParams,
141
+ ) -> dict[str, float]:
142
+ features = [
143
+ column
144
+ for column in df.columns
145
+ if column not in [TARGET, date_column] and column in reference_df.columns
146
+ ]
147
+ empty_res = {column: 0.0 for column in features}
148
+
149
+ if TARGET in df.columns and TARGET in reference_df.columns:
150
+ if _target_psi_blocks_features(
151
+ [df[TARGET]],
152
+ reference_df[TARGET],
62
153
  model_task_type,
63
154
  stability_agg_func,
64
155
  psi_target_params,
156
+ logger,
157
+ ):
158
+ return empty_res
159
+
160
+ features_agg_func = _get_agg_func(stability_agg_func or psi_features_params.agg)
161
+ logger.info(f"Calculating reference PSI for {len(features)} features with agg function {features_agg_func}")
162
+ psi_values: dict[str, float] = {}
163
+ for feature in features:
164
+ psi_values[feature] = _column_psi(
165
+ [df[feature]],
166
+ reference_df[feature],
167
+ feature not in cat_features,
65
168
  psi_features_params,
169
+ features_agg_func,
66
170
  )
67
- return {}
171
+ return psi_values
68
172
 
69
173
 
70
174
  def calculate_features_psi(
@@ -76,7 +180,26 @@ def calculate_features_psi(
76
180
  stability_agg_func: str | None = None,
77
181
  psi_features_params: StabilityParams = DEFAULT_FEATURES_PARAMS,
78
182
  psi_target_params: StabilityParams = DEFAULT_TARGET_PARAMS,
183
+ reference_df: pd.DataFrame | None = None,
79
184
  ) -> dict[str, float]:
185
+ """PSI for features.
186
+
187
+ Without ``reference_df``, split ``df`` into time intervals and compare later intervals to the first one.
188
+ With ``reference_df``, compare the full reference distribution to the full ``df`` distribution.
189
+ """
190
+ if reference_df is not None:
191
+ return _features_psi_against_reference(
192
+ df,
193
+ reference_df,
194
+ cat_features,
195
+ date_column,
196
+ logger,
197
+ model_task_type,
198
+ stability_agg_func,
199
+ psi_features_params,
200
+ psi_target_params,
201
+ )
202
+
80
203
  empty_res = {col: 0.0 for col in df.columns if col not in [TARGET, date_column]}
81
204
 
82
205
  # Filter out rows with missing dates
@@ -102,25 +225,14 @@ def calculate_features_psi(
102
225
  )
103
226
  return empty_res
104
227
 
105
- target_agg_func = _get_agg_func(stability_agg_func or psi_target_params.agg)
106
- logger.info(f"Calculating target PSI with agg function {target_agg_func}")
107
- target_psi = _stability_agg(
228
+ if _target_psi_blocks_features(
108
229
  [df[TARGET][cur] for cur in current_masks],
109
- reference_data=df[TARGET][reference_mask],
110
- is_numerical=model_task_type == ModelTaskType.REGRESSION,
111
- min_values_in_bin=psi_target_params.min_values_in_bin,
112
- n_bins=psi_target_params.n_bins,
113
- cat_top_pct=psi_target_params.cat_top_pct,
114
- agg_func=target_agg_func,
115
- )
116
- if target_psi is None or np.isnan(target_psi):
117
- logger.info("Cannot determine target PSI. Skip feature PSI check")
118
- return empty_res
119
-
120
- if target_psi > psi_target_params.threshold:
121
- logger.info(
122
- f"Target PSI {target_psi} is more than threshold {psi_target_params.threshold}. Skip feature PSI check"
123
- )
230
+ df[TARGET][reference_mask],
231
+ model_task_type,
232
+ stability_agg_func,
233
+ psi_target_params,
234
+ logger,
235
+ ):
124
236
  return empty_res
125
237
 
126
238
  psi_features_params.n_intervals = min(
@@ -134,14 +246,12 @@ def calculate_features_psi(
134
246
  logger.info(f"Calculating features PSI with agg function {features_agg_func}")
135
247
  features = [feature for feature in df.columns if feature not in [TARGET, date_column]]
136
248
  psi_values = [
137
- _stability_agg(
249
+ _column_psi(
138
250
  [df[feature][cur] for cur in current_masks],
139
- reference_data=df[feature][reference_mask],
140
- is_numerical=feature not in cat_features,
141
- min_values_in_bin=psi_features_params.min_values_in_bin,
142
- n_bins=psi_features_params.n_bins,
143
- cat_top_pct=psi_features_params.cat_top_pct,
144
- agg_func=features_agg_func,
251
+ df[feature][reference_mask],
252
+ feature not in cat_features,
253
+ psi_features_params,
254
+ features_agg_func,
145
255
  )
146
256
  for feature in features
147
257
  ]
@@ -1 +0,0 @@
1
- __version__ = "1.2.171a4287.dev1"