8000 Fix underflow in nmf._beta_divergence (#10142) · scikit-learn/scikit-learn@2160ea0 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2160ea0

Browse files
TomDLTagramfort
authored andcommitted
Fix underflow in nmf._beta_divergence (#10142)
1 parent c91699d commit 2160ea0

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

sklearn/decomposition/nmf.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,9 @@ def _beta_divergence(X, W, H, beta, square_root=False):
114114
X_data = X.ravel()
115115

116116
# do not affect the zeros: here 0 ** (-1) = 0 and not infinity
117-
WH_data = WH_data[X_data != 0]
118-
X_data = X_data[X_data != 0]
117+
indices = X_data > EPSILON
118+
WH_data = WH_data[indices]
119+
X_data = X_data[indices]
119120

120121
# used to avoid division by zero
121122
WH_data[WH_data == 0] = EPSILON

sklearn/decomposition/tests/test_nmf.py

Lines changed: 15 additions & 0 deletions
3F1E
Original file line numberDiff line numberDiff line change
@@ -479,3 +479,18 @@ def test_nmf_decreasing():
479479
if previous_loss is not None:
480480
assert_greater(previous_loss, loss)
481481
previous_loss = loss
482+
483+
484+
def test_nmf_underflow():
485+
# Regression test for an underflow issue in _beta_divergence
486+
rng = np.random.RandomState(0)
487+
n_samples, n_features, n_components = 10, 2, 2
488+
X = np.abs(rng.randn(n_samples, n_features)) * 10
489+
W = np.abs(rng.randn(n_samples, n_components)) * 10
490+
H = np.abs(rng.randn(n_components, n_features))
491+
492+
X[0, 0] = 0
493+
ref = nmf._beta_divergence(X, W, H, beta=1.0)
494+
X[0, 0] = 1e-323
495+
res = nmf._beta_divergence(X, W, H, beta=1.0)
496+
assert_almost_equal(res, ref)

0 commit comments

Comments
 (0)
0