-
-
Notifications
You must be signed in to change notification settings - Fork 428
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add KDE bandwidth selectors using biased or unbiased cross-validation #2384
Closed
+203
−25
Closed
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
69dfc83
Add cross-validation-based bandwidth selection
sethaxen 2831780
Pass bin width to bandwidth functions
sethaxen b7b1df0
Make function more modular
sethaxen d2eae90
Document cv bandwidth methods
sethaxen 2ea80f1
Add example using UCV bandwidth
sethaxen 276479d
Document that ucv and bcv are acceptable values for bw
sethaxen 0207f14
Fix bugs in cv score computation
sethaxen ca30ec7
Use histogram utility function
sethaxen c2515da
Add tests for density utils
sethaxen d26eb17
Reorganizing existing histogram test with other density utils tests
sethaxen 76ac63c
Make corrections to docstrings
sethaxen 1332338
Add missing test import
sethaxen 3588378
Fix pylint error
sethaxen 485b38a
Remove unused imports
sethaxen 51626c0
Disable pylint checks
sethaxen 8947d60
Update CHANGELOG.md
sethaxen c85b86d
Simplify code by using correlate
sethaxen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
import pytest | ||
|
||
import numpy as np | ||
from ...data import load_arviz_data | ||
from ...stats.density_utils import ( | ||
_prepare_cv_score_inputs, | ||
_compute_cv_score, | ||
_bw_cv, | ||
_bw_oversmoothed, | ||
_bw_scott, | ||
histogram, | ||
) | ||
|
||
|
||
def compute_cv_score_explicit(bw, x, unbiased): | ||
"""Explicit computation of the CV score for a 1D dataset.""" | ||
n = len(x) | ||
score = 0.0 | ||
for i in range(n): | ||
for j in range(i + 1, n): | ||
delta = (x[i] - x[j]) / bw | ||
if unbiased: | ||
score += np.exp(-0.25 * delta**2) - np.sqrt(8) * np.exp(-0.5 * delta**2) | ||
else: | ||
score += (delta**4 - 12 * delta**2 + 12) * np.exp(-0.25 * delta**2) | ||
if not unbiased: | ||
score /= 64 | ||
score = 0.5 / n / bw / np.sqrt(np.pi) + score / n**2 / bw / np.sqrt(np.pi) | ||
return score | ||
|
||
|
||
def test_histogram(): | ||
school = load_arviz_data("non_centered_eight").posterior["mu"].values | ||
k_count_az, k_dens_az, _ = histogram(school, bins=np.asarray([-np.inf, 0.5, 0.7, 1, np.inf])) | ||
k_dens_np, *_ = np.histogram(school, bins=[-np.inf, 0.5, 0.7, 1, np.inf], density=True) | ||
k_count_np, *_ = np.histogram(school, bins=[-np.inf, 0.5, 0.7, 1, np.inf], density=False) | ||
assert np.allclose(k_count_az, k_count_np) | ||
assert np.allclose(k_dens_az, k_dens_np) | ||
|
||
|
||
@pytest.mark.parametrize("unbiased", [True, False]) | ||
@pytest.mark.parametrize("bw", [0.1, 0.5, 2.0]) | ||
@pytest.mark.parametrize("n", [100, 1_000]) | ||
def test_compute_cv_score(bw, unbiased, n, seed=42): | ||
"""Test that the histogram-based CV score matches the explicit CV score.""" | ||
rng = np.random.default_rng(seed) | ||
x = rng.normal(size=n) | ||
x_std = x.std() | ||
grid_counts, grid_edges = np.histogram( | ||
x, bins=100, range=(x.min() - 0.5 * x_std, x.max() + 0.5 * x_std) | ||
) | ||
bin_width = grid_edges[1] - grid_edges[0] | ||
grid = grid_edges[:-1] + 0.5 * bin_width | ||
|
||
# if data is discretized to regularly-spaced bins, then explicit CV score should match | ||
# the histogram-based CV score | ||
x_discrete = np.repeat(grid, grid_counts) | ||
rng.shuffle(x_discrete) | ||
score_inputs = _prepare_cv_score_inputs(grid_counts, n) | ||
score = _compute_cv_score(bw, n, bin_width, unbiased, *score_inputs) | ||
score_explicit = compute_cv_score_explicit(bw, x_discrete, unbiased) | ||
assert np.isclose(score, score_explicit) | ||
|
||
|
||
@pytest.mark.parametrize("unbiased", [True, False]) | ||
def test_bw_cv_normal(unbiased, seed=42, bins=512, n=100_000): | ||
"""Test that for normal target, selected CV bandwidth converges to known optimum.""" | ||
rng = np.random.default_rng(seed) | ||
x = rng.normal(size=n) | ||
x_std = x.std() | ||
grid_counts, grid_edges = np.histogram( | ||
x, bins=bins, range=(x.min() - 0.5 * x_std, x.max() + 0.5 * x_std) | ||
) | ||
bin_width = grid_edges[1] - grid_edges[0] | ||
bw = _bw_cv(x, unbiased=unbiased, bin_width=bin_width, grid_counts=grid_counts) | ||
assert bw > bin_width / (2 * np.pi) | ||
assert bw < _bw_oversmoothed(x) | ||
assert np.isclose(bw, _bw_scott(x), rtol=0.2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maybe we can disable "too-many..." globally. It's popping up in many places.