From bb893a29d5bc42ae860e362fd06ef200ab008a5d Mon Sep 17 00:00:00 2001 From: Andreas Mueller Date: Wed, 7 Dec 2016 18:51:13 -0500 Subject: [PATCH] raise AttributeError in SVC.coef_ for proper duck-typing --- sklearn/svm/base.py | 4 ++-- sklearn/svm/tests/test_svm.py | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/sklearn/svm/base.py b/sklearn/svm/base.py index d24bfefce4f6d..b00130127f0b0 100644 --- a/sklearn/svm/base.py +++ b/sklearn/svm/base.py @@ -482,8 +482,8 @@ def _validate_for_predict(self, X): @property def coef_(self): if self.kernel != 'linear': - raise ValueError('coef_ is only available when using a ' - 'linear kernel') + raise AttributeError('coef_ is only available when using a ' + 'linear kernel') coef = self._get_coef() diff --git a/sklearn/svm/tests/test_svm.py b/sklearn/svm/tests/test_svm.py index e49b956682020..88c4b04dfca8b 100644 --- a/sklearn/svm/tests/test_svm.py +++ b/sklearn/svm/tests/test_svm.py @@ -57,6 +57,7 @@ def test_libsvm_iris(): for k in ('linear', 'rbf'): clf = svm.SVC(kernel=k).fit(iris.data, iris.target) assert_greater(np.mean(clf.predict(iris.data) == iris.target), 0.9) + assert_true(hasattr(clf, "coef_") == (k == 'linear')) assert_array_equal(clf.classes_, np.sort(clf.classes_)) @@ -257,7 +258,7 @@ def test_oneclass(): assert_array_almost_equal(clf.dual_coef_, [[0.632, 0.233, 0.633, 0.234, 0.632, 0.633]], decimal=3) - assert_raises(ValueError, lambda: clf.coef_) + assert_false(hasattr(clf, "coef_")) def test_oneclass_decision_function(): @@ -641,7 +642,8 @@ def test_linearsvc(): assert_array_almost_equal(clf.intercept_, [0], decimal=3) # the same with l1 penalty - clf = svm.LinearSVC(penalty='l1', loss='squared_hinge', dual=False, random_state=0).fit(X, Y) + clf = svm.LinearSVC(penalty='l1', loss='squared_hinge', dual=False, + random_state=0).fit(X, Y) assert_array_equal(clf.predict(T), true_result) # l2 penalty with dual formulation