Skip to content

fix: preserve neighbor order in stability explanations - #794

Merged
milton-minervino merged 4 commits into
MAIF:developfrom
aminemanai2003:fix/777-shap-neighbor-order
Oct 8, 2026
Merged

milton-minervino merged 4 commits into
MAIF:developfrom
aminemanai2003:fix/777-shap-neighbor-order

Conversation

@aminemanai2003

@aminemanai2003 aminemanai2003 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Description

I fixed the row mix-up in feature stability calculations. find_neighbors now carries each selected row's position through the prediction and distance filters, and compute_features_stability passes those positions to shap_neighbors. This keeps the requested instance first, preserves distance order, and avoids multiplying rows when two observations have identical features.

Direct calls to shap_neighbors without positions still work for unique feature rows. They now follow the supplied neighbourhood order; for duplicate feature rows, they raise a clear error instead of returning ambiguous results.

Fixes: #777

Type of change

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

  • uv run --no-sync python -m pytest tests/unit_tests/utils/test_explanation_metrics.py tests/unit_tests/explainer/test_smart_explainer.py -q — 86 passed
  • uv run --no-sync python -m pytest tests/unit_tests/explainer/test_smart_plotter.py -k stability -q — 5 passed
  • uvx ruff check shapash/utils/explanation_metrics.py and git diff --check — passed

Test configuration: Windows, Python 3.11.9, Shapash source branch based on upstream develop.

The regression tests cover an instance later in the dataset than a neighbour, duplicate feature rows, distance ties that would otherwise push the selected row out of the initial slice, classification filtering with returned row positions, and both stability output branches.

@milton-minervino milton-minervino left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for this PR, this fixes real bugs: SHAP rows now follow the neighbourhood order (instance first, then by distance), tied distances can no longer push the selected row out of the top N, and duplicate feature rows no longer multiply rows.

Two small requests before merging:

  • Can you please document the new ValueError in the shap_neighbors docstring by adding a Raises section? With neighbor_positions=None and duplicate feature rows it now raises ValueError, where it used to silently return too many rows. Please also note that rows now follow the neighborhood order (instance first).
  • Can you add tests for the paths the new tests don't cover?
    • find_neighbors in classification mode with return_positions=True. Assert that positions[i][0] is the selected row and that len(positions[i]) == len(neighbors[i]) after the filters.
    • Explainer.compute_features_stability end to end, for both the len(selection) == 1 branch (local_neighbors) and the multi-row branch (features_stability). Check that amplitude matches the selected row's SHAP values.

Comment thread shapash/utils/explanation_metrics.py Resolved
@aminemanai2003

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I added the Raises section and clarified the row order in the docstring. I also added the classification test for return_positions=True and changed the stability tests so they check the selected row's actual normalized SHAP values in both the single- and multi-row branches, including a duplicate feature row.

The two affected test files pass (73 tests), and the six stability plotting tests pass too. Ruff on the production file and git diff --check also pass.

@guillaume-vignal
guillaume-vignal changed the base branch from develop to master October 6, 2026 18:53
@guillaume-vignal
guillaume-vignal changed the base branch from master to develop October 6, 2026 18:54

@milton-minervino milton-minervino left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the changes!

@codecov

codecov Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.13%. Comparing base (7d2eb69) to head (7011d62).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #794      +/-   ##
===========================================
+ Coverage    79.03%   79.13%   +0.10%     
===========================================
  Files           59       59              
  Lines         7287     7305      +18     
  Branches      1534     1538       +4     
===========================================
+ Hits          5759     5781      +22     
+ Misses         951      947       -4     
  Partials       577      577              
Files with missing lines Coverage Δ
shapash/explainer/explainer.py 82.47% <100.00%> (ø)
shapash/utils/explanation_metrics.py 76.74% <100.00%> (+8.27%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@milton-minervino
milton-minervino merged commit e8cda61 into MAIF:develop Oct 8, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

shap_neighbors returns a neighbour's contributions as "the instance": the inner merge puts rows back in x_encoded order

2 participants