Skip to content

Commit e4206e2

Browse files
Statistics.tests: Inject explicit zeros into dense_sparse decorator
1 parent e515f30 commit e4206e2

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

Orange/statistics/util.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,11 @@ def bincount(x, weights=None, max_val=None, minlength=None):
131131
bc = np.bincount(
132132
x.astype(np.int32, copy=False), weights=weights, minlength=minlength
133133
).astype(float)
134-
# Since `csr_matrix.values` only contain non-zero values, we must count
135-
# those separately and set the appropriate bin
134+
# Since `csr_matrix.values` only contain non-zero values or explicit
135+
# zeros, we must count implicit zeros separately and add them to the
136+
# explicit ones found before
136137
if sp.issparse(x_original):
137-
bc[0] = zero_weights
138+
bc[0] += zero_weights
138139

139140
return bc, nans
140141

Orange/tests/test_statistics.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import unittest
22
import warnings
3-
from functools import wraps
3+
from functools import wraps, partial
44
from itertools import chain
55

66
import numpy as np
@@ -16,9 +16,21 @@ def dense_sparse(test_case):
1616
"""Run a single test case on both dense and sparse data."""
1717
@wraps(test_case)
1818
def _wrapper(self):
19+
20+
def sparse_with_explicit_zero(x, array):
21+
"""Inject one explicit zero into a sparse array."""
22+
np_array, sp_array = np.atleast_2d(x), array(x)
23+
assert issparse(sp_array), 'Can not inject explicit zero into non-sparse matrix'
24+
25+
zero_indices = np.argwhere(np_array == 0)
26+
if zero_indices.size:
27+
sp_array[tuple(zero_indices[0])] = 0
28+
29+
return sp_array
30+
1931
test_case(self, lambda x: np.array(x))
20-
test_case(self, lambda x: csr_matrix(x))
21-
test_case(self, lambda x: csc_matrix(x))
32+
test_case(self, partial(sparse_with_explicit_zero, array=csr_matrix))
33+
test_case(self, partial(sparse_with_explicit_zero, array=csc_matrix))
2234

2335
return _wrapper
2436

0 commit comments

Comments
 (0)