← Back to Pull requests

[API] Exposing fitted samplers + their scores in CFI #829

Merged
GrituX merged 10 files (766 lines) on Oct 27, 2026 14:22 UTC
View on GitHub
GrituX GrituX commented on Oct 15, 2026 13:32 UTC
Author

Here is the list of changes, with some explanations:

  • _list_imputation_models becomes fitted_samplers_

  • Added an attribute conditional_scores_: this is computed during importance(), as the score to predict $X_j$ from $X_{-j}$. The metrics used here are $R^2$ and balanced accuracy depending on data type. I chose balanced accuracy in this version of the code as an easy solution for multiclass situations, but if AUC is preferred, then we need to choose between OVR or OVO strategy. The computation is done sequentially after everything all importance score computation because these scores are computed inside joblib workers. This would mean overriding all importance sub-methods, and change everything just for CFI, which can make things harder to maintain. It's doable, but it's more of a question of preference between code maintenance or compute upgrade.

  • Added an attribute conditional_score_types_: similar to data_types but for conditional_scores_, it gives the score type for each feature group

  • Made a few fixes here and there to improve code.
  • For the moment, there are no new tests. I think it's better to discuss things first, and once everything is validated, I'll add tests to finalize and settle the code, and fix current ones according to changes.

    Diff: 766 lines (+671 / -95) across 10 files Reviewer: bthirion Review duration: 17329m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.56) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 766 lines diff across 10 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.85 · 5 substantive comment(s)
    0.85
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.397
    Real PR Conversation Timeline
    27 items
    bthirion bthirion commented on Oct 16, 2026 06:44 UTC
    Contributor

    * I chose balanced accuracy in this version of the code as an easy solution for multiclass situations, but if AUC is preferred, then we need to choose between OVR or OVO strategy.

    I think I'd rather take OVR AUC.

    jpaillard jpaillard commented on code on Oct 16, 2026 07:37 UTC
    Code Review
    src/hidimstat/samplers/conditional_sampling.py:1
    @@ -188,3 +224,43 @@ def sample(
                         )
                     )
                 return np.stack(y_pred_cond, axis=-1)
    +
    +    def score(self, X: np.ndarray, y: np.ndarray) -> float:

    We need to find a different name than score.
    In a case where features are independent, a perfect conditional sampler would have a score of 0. This would be misleading, especially for users familiar with sklearn's API.

    jpaillard jpaillard commented on code on Oct 16, 2026 07:40 UTC
    Code Review
    src/hidimstat/conditional_feature_importance.py:1
    @@ -210,13 +243,64 @@ def _permutation(self, X, features_group_id, random_state=None):
             X_minus_j = _get_array_cols(
                 X, self._feature_groups_ids[features_group_id], drop=True
             )
    -        return self._list_imputation_models[features_group_id].sample(
    +        return self.fitted_samplers_[features_group_id].sample(
                 X_minus_j,
                 X_j,
                 n_samples=self.n_permutations,
                 random_state=random_state,
             )
     
    +    def _joblib_score_one_conditional_sampler(
    +        self, conditional_sampler, X, features_group_ids
    +    ):
    +        """
    +        Score a single fitted conditional sampler on X.
    +        """
    +        X_j = _get_array_cols(X, features_group_ids)
    +        X_minus_j = _get_array_cols(X, features_group_ids, drop=True)
    +        return conditional_sampler.score(X_minus_j, X_j)
    +
    +    def importance(self, X, y):
    +        """
    +        Compute the importance scores for each group of covariates, and the
    +        predictability of each group from the others.
    +
    +        Parameters
    +        ----------
    +        X : array-like of shape (n_samples, n_features)
    +            The input samples to compute importance scores for.
    +        y : array-like of shape (n_samples,)
    +            The target values.
    +
    +        Returns
    +        -------
    +        importances_ : ndarray of shape (n_groups,)
    +            The importance scores for each feature group.
    +
    +        Notes
    +        -----
    +        The predictability scores are stored separately in conditional_scores_.
    +        """
    +        importances = super().importance(X, y)
    +
    +        self.conditional_scores_ = np.asarray(

    Maybe we could even make this optional. In a scenario where this stage is costly and the user is not interested in the conditional_scores_ it could be convenient to skip this step.

    jpaillard jpaillard commented on Oct 16, 2026 07:46 UTC
    Reviewer

  • Isn't conditional_score_types_ redundant with data_types?

  • - regarding the naming I have some concerns about conditional_scores_. First it's semantically close to conditional_importance which can be misleading. And second, a conditional sampler can be very good while the value of conditional_scores_ is very low (in the case of independent variables for instance). What about shared_variance_ or conditional_predictability_ or feature_predictability_
    - How will this deal with groups of featurs?

    GrituX GrituX commented on Oct 16, 2026 14:09 UTC
    Author

    Isn't conditional_score_types_ redundant with data_types?

    Indeed, I deleted it.

    regarding the naming I have some concerns about conditional_scores_. First it's semantically close to conditional_importance which can be misleading. And second, a conditional sampler can be very good while the value of conditional_scores_ is very low (in the case of independent variables for instance). What about shared_variance_ or conditional_predictability_ or feature_predictability_

    I renamed it feature_predictability_ following your suggestion

    * How will this deal with groups of featurs?

    It averages over the scores of individual features for the moment, but there's probably a better way to do it.

    Also, I'm thinking that it could be nice to have a plot_feature_predictability() method similar to plot_importance().
    I also modified the plot_cfi.py example to showcase changes, but since I haven't edited tests for the moment, it's not readable.

    GrituX GrituX commented on Oct 16, 2026 14:11 UTC
    Author

    Also, for the moment, there is the issue that the entire feature_group has a single data_type ...

    bthirion bthirion commented on Oct 17, 2026 14:26 UTC
    Contributor

    Also, for the moment, there is the issue that the entire feature_group has a single data_type ...

    Indeed, but we can address that later. It's something to discuss first.

    GrituX GrituX commented on Oct 19, 2026 11:33 UTC
    Author

    Ok, then I'll write some tests to settle the code.

    codecov[bot] codecov[bot] commented on Oct 19, 2026 14:58 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 96.07843% with 4 lines in your changes missing coverage. Please review.
    :white_check_mark: Project coverage is 97.53%. Comparing base (f99afab) to head (ffde59d).

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | src/hidimstat/conditional\_feature\_importance.py | 95.23% | 2 Missing :warning: |
    | src/hidimstat/base\_variable\_importance.py | 94.11% | 1 Missing :warning: |
    | src/hidimstat/samplers/conditional\_sampling.py | 97.56% | 1 Missing :warning: |

    <details><summary>Additional details and impacted files</summary>

    @@            Coverage Diff             @@
    ##             main     #829      +/-   ##
    ==========================================
    - Coverage   97.62%   97.53%   -0.10%     
    ==========================================
      Files          37       37              
      Lines        2523     2592      +69     
    ==========================================
    + Hits         2463     2528      +65     
    - Misses         60       64       +4     
    

    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    bthirion bthirion commented on code on Oct 19, 2026 21:18 UTC
    Code Review
    examples/plot_cfi.py:1
    @@ -89,21 +93,52 @@
     
     import matplotlib.pyplot as plt
     
    -_, ax = plt.subplots(figsize=(6, 3))
    -ax = cfi.plot_importance(ax=ax)
    +_, axes = plt.subplots(1, 2, figsize=(6, 3))
    +ax = cfi.plot_importance(ax=axes[0])
     ax.set_xlabel("Feature Importance")
    +ax = cfi.plot_feature_predictability(ax=axes[1])
    +ax.set_xlabel("Feature predictability")

    the title does not render well.
    Besides, a vertical line at 1 would be useful.

    bthirion bthirion commented on code on Oct 19, 2026 21:20 UTC
    Code Review
    src/hidimstat/samplers/conditional_sampling.py:1
    @@ -188,3 +223,54 @@ def sample(
                         )
                     )
                 return np.stack(y_pred_cond, axis=-1)
    +
    +    def feature_predictability(self, X: np.ndarray, y: np.ndarray) -> float:
    +        """
    +        Scores how well $X^j$ is predicted from $X^{-j}$.
    +
    +        For continuous data, the coefficient of determination $R^2$ is used.
    +        For a group of variables, columns are averaged weighted by their variance.

    WDYM ?

    bthirion bthirion commented on code on Oct 19, 2026 21:21 UTC
    Code Review
    src/hidimstat/samplers/conditional_sampling.py:1
    @@ -188,3 +223,54 @@ def sample(
                         )
                     )
                 return np.stack(y_pred_cond, axis=-1)
    +
    +    def feature_predictability(self, X: np.ndarray, y: np.ndarray) -> float:
    +        """
    +        Scores how well $X^j$ is predicted from $X^{-j}$.
    +
    +        For continuous data, the coefficient of determination $R^2$ is used.
    +        For a group of variables, columns are averaged weighted by their variance.

    the R^2 score is averaged, right ?

    bthirion bthirion commented on code on Oct 19, 2026 21:23 UTC
    Code Review
    src/hidimstat/conditional_feature_importance.py:1
    @@ -107,7 +135,7 @@ def __init__(
             ), "Categorial imputation model invalid"
     
             self.feature_types = feature_types
    -        self._list_imputation_models = []
    +        self._conditionnal_samplers = []

    What was the motivation for this renaming ? Maybe it's a good idea, but I'm not completely sure.

    bthirion bthirion commented on Oct 19, 2026 21:25 UTC
    Reviewer

    LGTM overall, thx.

    jpaillard jpaillard commented on code on Oct 20, 2026 07:28 UTC
    Code Review
    src/hidimstat/samplers/conditional_sampling.py:1
    @@ -188,3 +223,54 @@ def sample(
                         )
                     )
                 return np.stack(y_pred_cond, axis=-1)
    +
    +    def feature_predictability(self, X: np.ndarray, y: np.ndarray) -> float:
    +        """
    +        Scores how well $X^j$ is predicted from $X^{-j}$.
    +
    +        For continuous data, the coefficient of determination $R^2$ is used.
    +        For a group of variables, columns are averaged weighted by their variance.
    +
    +        For categorical data, the balanced accuracy is computed.
    +        For a group of variables, the balanced accuracy is averaged uniformly
    +        over the columns.

            For categorical data, the ROC AUC is computed.
            For a group of variables, the ROC AUC is averaged uniformly
            over the columns.
    

    jpaillard jpaillard commented on code on Oct 20, 2026 07:30 UTC
    Code Review
    src/hidimstat/samplers/conditional_sampling.py:1
    @@ -188,3 +223,54 @@ def sample(
                         )
                     )
                 return np.stack(y_pred_cond, axis=-1)
    +
    +    def feature_predictability(self, X: np.ndarray, y: np.ndarray) -> float:
    +        """
    +        Scores how well $X^j$ is predicted from $X^{-j}$.
    +
    +        For continuous data, the coefficient of determination $R^2$ is used.
    +        For a group of variables, columns are averaged weighted by their variance.
    +
    +        For categorical data, the balanced accuracy is computed.
    +        For a group of variables, the balanced accuracy is averaged uniformly
    +        over the columns.
    +
    +        Parameters
    +        ----------
    +        X : ndarray
    +            The complementary of the considered set of variables, $X^{-j}$.
    +        y : ndarray
    +            The group of variables to predict, $X^j$.
    +
    +        Returns
    +        -------
    +        score : float
    +            The $R^2$ (continuous) or AUC (categorical) with OVR strategy for multiclass.

    Another possibility would be to return $2\times$ AUC $-1$ for categorical variables so that it is in a comparable [0, 1] range to that of regression, with a similar chance level at 0.

    jpaillard jpaillard commented on code on Oct 20, 2026 07:34 UTC
    Code Review
    src/hidimstat/conditional_feature_importance.py:1
    @@ -210,13 +242,126 @@ def _permutation(self, X, features_group_id, random_state=None):
             X_minus_j = _get_array_cols(
                 X, self._feature_groups_ids[features_group_id], drop=True
             )
    -        return self._list_imputation_models[features_group_id].sample(
    +        return self.fitted_samplers_[features_group_id].sample(
                 X_minus_j,
                 X_j,
                 n_samples=self.n_permutations,
                 random_state=random_state,
             )
     
    +    def _joblib_score_one_conditional_sampler(
    +        self, conditional_sampler, X, features_group_ids
    +    ):
    +        """
    +        Score a single fitted conditional sampler on X.
    +        """
    +        X_j = _get_array_cols(X, features_group_ids)
    +        X_minus_j = _get_array_cols(X, features_group_ids, drop=True)
    +        return conditional_sampler.feature_predictability(X_minus_j, X_j)
    +
    +    def importance(self, X, y):
    +        """
    +        Compute the importance scores for each group of covariates, and the
    +        predictability of each group from the others.
    +
    +        Parameters
    +        ----------
    +        X : array-like of shape (n_samples, n_features)
    +            The input samples to compute importance scores for.
    +        y : array-like of shape (n_samples,)
    +            The target values.
    +
    +        Returns
    +        -------
    +        importances_ : ndarray of shape (n_groups,)
    +            The importance scores for each feature group.
    +        """
    +        importances = super().importance(X, y)
    +
    +        self.feature_predictability_ = np.asarray(

    Should we allow this to be skipped?

    jpaillard jpaillard commented on code on Oct 20, 2026 07:35 UTC
    Code Review
    src/hidimstat/conditional_feature_importance.py:1
    @@ -210,13 +242,126 @@ def _permutation(self, X, features_group_id, random_state=None):
             X_minus_j = _get_array_cols(
                 X, self._feature_groups_ids[features_group_id], drop=True
             )
    -        return self._list_imputation_models[features_group_id].sample(
    +        return self.fitted_samplers_[features_group_id].sample(
                 X_minus_j,
                 X_j,
                 n_samples=self.n_permutations,
                 random_state=random_state,
             )
     
    +    def _joblib_score_one_conditional_sampler(

    To avoid using "score" I would suggest _joblib_feature_predictability

    jpaillard jpaillard commented on code on Oct 20, 2026 07:37 UTC
    Code Review
    test/samplers/test_conditional_sampling.py:1

    Could we have a test in a setting where features are either very easy to predict or completely independent, and check that feature_predictability_ matches what we would expect?

    GrituX GrituX commented on code on Oct 20, 2026 09:55 UTC
    Code Review
    src/hidimstat/samplers/conditional_sampling.py:1
    @@ -188,3 +223,54 @@ def sample(
                         )
                     )
                 return np.stack(y_pred_cond, axis=-1)
    +
    +    def feature_predictability(self, X: np.ndarray, y: np.ndarray) -> float:
    +        """
    +        Scores how well $X^j$ is predicted from $X^{-j}$.
    +
    +        For continuous data, the coefficient of determination $R^2$ is used.
    +        For a group of variables, columns are averaged weighted by their variance.

    The R2 score is averaged indeed. Sklearn r2_score method has the possibility to perform weighting during this computation by the variance of each column, but I honestly can't remember why I picked this option. I think it's better to use a uniform average since it's what we're doing for the categorical data. I switch back to this and update the doc.

    GrituX GrituX commented on code on Oct 20, 2026 09:58 UTC
    Code Review
    src/hidimstat/conditional_feature_importance.py:1
    @@ -107,7 +135,7 @@ def __init__(
             ), "Categorial imputation model invalid"
     
             self.feature_types = feature_types
    -        self._list_imputation_models = []
    +        self._conditionnal_samplers = []

    The idea was to have a more explicit naming that was also closer to our API.

    GrituX GrituX commented on code on Oct 20, 2026 12:54 UTC
    Code Review
    src/hidimstat/conditional_feature_importance.py:1
    @@ -210,13 +242,126 @@ def _permutation(self, X, features_group_id, random_state=None):
             X_minus_j = _get_array_cols(
                 X, self._feature_groups_ids[features_group_id], drop=True
             )
    -        return self._list_imputation_models[features_group_id].sample(
    +        return self.fitted_samplers_[features_group_id].sample(
                 X_minus_j,
                 X_j,
                 n_samples=self.n_permutations,
                 random_state=random_state,
             )
     
    +    def _joblib_score_one_conditional_sampler(
    +        self, conditional_sampler, X, features_group_ids
    +    ):
    +        """
    +        Score a single fitted conditional sampler on X.
    +        """
    +        X_j = _get_array_cols(X, features_group_ids)
    +        X_minus_j = _get_array_cols(X, features_group_ids, drop=True)
    +        return conditional_sampler.feature_predictability(X_minus_j, X_j)
    +
    +    def importance(self, X, y):
    +        """
    +        Compute the importance scores for each group of covariates, and the
    +        predictability of each group from the others.
    +
    +        Parameters
    +        ----------
    +        X : array-like of shape (n_samples, n_features)
    +            The input samples to compute importance scores for.
    +        y : array-like of shape (n_samples,)
    +            The target values.
    +
    +        Returns
    +        -------
    +        importances_ : ndarray of shape (n_groups,)
    +            The importance scores for each feature group.
    +        """
    +        importances = super().importance(X, y)
    +
    +        self.feature_predictability_ = np.asarray(

    Yes, it can be a good thing to skip this. I'm making this computed by default, with a simple boolean as argument.

    GrituX GrituX commented on code on Oct 20, 2026 12:59 UTC
    Code Review
    src/hidimstat/samplers/conditional_sampling.py:1
    @@ -188,3 +223,54 @@ def sample(
                         )
                     )
                 return np.stack(y_pred_cond, axis=-1)
    +
    +    def feature_predictability(self, X: np.ndarray, y: np.ndarray) -> float:
    +        """
    +        Scores how well $X^j$ is predicted from $X^{-j}$.
    +
    +        For continuous data, the coefficient of determination $R^2$ is used.
    +        For a group of variables, columns are averaged weighted by their variance.
    +
    +        For categorical data, the balanced accuracy is computed.
    +        For a group of variables, the balanced accuracy is averaged uniformly
    +        over the columns.
    +
    +        Parameters
    +        ----------
    +        X : ndarray
    +            The complementary of the considered set of variables, $X^{-j}$.
    +        y : ndarray
    +            The group of variables to predict, $X^j$.
    +
    +        Returns
    +        -------
    +        score : float
    +            The $R^2$ (continuous) or AUC (categorical) with OVR strategy for multiclass.

    Indeed, I think it's a good idea. What do you think @bthirion ?

    GrituX GrituX commented on code on Oct 20, 2026 14:26 UTC
    Code Review
    test/samplers/test_conditional_sampling.py:1

    I've added tests for easy to predict features and independent ones, for both continuous and categorical outputs in single and multi output settings.

    bthirion bthirion approved these changes on Oct 20, 2026 21:04 UTC
    Approved Reviewer

    LGTM, thx.

    jpaillard jpaillard approved these changes on Oct 21, 2026 07:57 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    GrituX GrituX
    Labels
    risk: low confidence: 88.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 55.9% (MEDIUM) · Higher = larger blast radius
    55.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.7% · Lower = rushed or shallow review
    88.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.3% · Safe to merge
    6.3%