Skip to content

Commit a89462b

Browse files
danna-naserNicolasHug
authored andcommitted
FIX ZeroDivisionError in BaseLibSVM._sparse_fit when n_SV == 0 (scikit-learn#14894)
1 parent fdbaa58 commit a89462b

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

doc/whats_new/v0.22.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,9 @@ Changelog
572572
:class:`svm.OneClassSVM` was previously non-initialized, and had size 2. It
573573
has now size 1 with the correct value. :pr:`15099` by `Nicolas Hug`_.
574574

575+
- |Fix| fixed a bug in :class:`BaseLibSVM._sparse_fit` where n_SV=0 raised a
576+
ZeroDivisionError. :pr:`14894` by :user:`Danna Naser <danna-naser>`.
577+
575578
:mod:`sklearn.tree`
576579
...................
577580

sklearn/svm/base.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -287,11 +287,14 @@ def _sparse_fit(self, X, y, sample_weight, solver_type, kernel,
287287
n_SV = self.support_vectors_.shape[0]
288288

289289
dual_coef_indices = np.tile(np.arange(n_SV), n_class)
290-
dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,
291-
dual_coef_indices.size / n_class)
292-
self.dual_coef_ = sp.csr_matrix(
293-
(dual_coef_data, dual_coef_indices, dual_coef_indptr),
294-
(n_class, n_SV))
290+
if not n_SV:
291+
self.dual_coef_ = sp.csr_matrix([])
292+
else:
293+
dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,
294+
dual_coef_indices.size / n_class)
295+
self.dual_coef_ = sp.csr_matrix(
296+
(dual_coef_data, dual_coef_indices, dual_coef_indptr),
297+
(n_class, n_SV))
295298

296299
def predict(self, X):
297300
"""Perform regression on samples in X.

sklearn/svm/tests/test_svm.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,19 @@ def test_sparse_precomputed():
690690
assert "Sparse precomputed" in str(e)
691691

692692

693+
def test_sparse_fit_support_vectors_empty():
694+
# Regression test for #14893
695+
X_train = sparse.csr_matrix([[0, 1, 0, 0],
696+
[0, 0, 0, 1],
697+
[0, 0, 1, 0],
698+
[0, 0, 0, 1]])
699+
y_train = np.array([0.04, 0.04, 0.10, 0.16])
700+
model = svm.SVR(kernel='linear')
701+
model.fit(X_train, y_train)
702+
assert not model.support_vectors_.data.size
703+
assert not model.dual_coef_.data.size
704+
705+
693706
def test_linearsvc_parameters():
694707
# Test possible parameter combinations in LinearSVC
695708
# Generate list of possible parameter combinations

0 commit comments

Comments
 (0)