Skip to content
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

[FIX] Classification models output correct shapes #4602

Merged
merged 1 commit into from
Apr 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 38 additions & 16 deletions Orange/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,39 @@ def backmap_probs(self, probs, n_values, backmappers):
new_probs = new_probs / tots[:, None]
return new_probs

def data_to_model_domain(self, data: Table) -> Table:
"""
Transforms data to the model domain if possible.

Parameters
----------
data
Data to be transformed to the model domain

Returns
-------
Transformed data table

Raises
------
DomainTransformationError
Error indicates that transformation is not possible since domains
are not compatible
"""
if data.domain == self.domain:
return data

if self.original_domain.attributes != data.domain.attributes \
and data.X.size \
and not all_nan(data.X):
new_data = data.transform(self.original_domain)
if all_nan(new_data.X):
raise DomainTransformationError(
"domain transformation produced no defined values")
return new_data.transform(self.domain)

return data.transform(self.domain)

def __call__(self, data, ret=Value):
multitarget = len(self.domain.class_vars) > 1

Expand All @@ -336,21 +369,6 @@ def one_hot_probs(value):
def fix_dim(x):
return x[0] if one_d else x

def data_to_model_domain():
if data.domain == self.domain:
return data

if self.original_domain.attributes != data.domain.attributes \
and data.X.size \
and not all_nan(data.X):
new_data = data.transform(self.original_domain)
if all_nan(new_data.X):
raise DomainTransformationError(
"domain transformation produced no defined values")
return new_data.transform(self.domain)

return data.transform(self.domain)

if not 0 <= ret <= 2:
raise ValueError("invalid value of argument 'ret'")
if ret > 0 and any(v.is_continuous for v in self.domain.class_vars):
Expand All @@ -368,14 +386,18 @@ def data_to_model_domain():
else:
one_d = False

# if sparse convert to csr_matrix
if scipy.sparse.issparse(data):
data = data.tocsr()

# Call the predictor
backmappers = None
n_values = []
if isinstance(data, (np.ndarray, scipy.sparse.csr.csr_matrix)):
prediction = self.predict(data)
elif isinstance(data, Table):
backmappers, n_values = self.get_backmappers(data)
data = data_to_model_domain()
data = self.data_to_model_domain(data)
prediction = self.predict_storage(data)
elif isinstance(data, (list, tuple)):
data = Table.from_list(self.original_domain, data)
Expand Down
5 changes: 0 additions & 5 deletions Orange/classification/svm.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,8 @@
svm_pps = SklLearner.preprocessors + [AdaptiveNormalize()]


class SVMClassifier(SklModel):
pass


class SVMLearner(SklLearner):
__wraps__ = skl_svm.SVC
__returns__ = SVMClassifier
preprocessors = svm_pps

def __init__(self, C=1.0, kernel='rbf', degree=3, gamma="auto",
Expand Down
11 changes: 11 additions & 0 deletions Orange/classification/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,17 @@ def test_no_common_values(self):
self.assertTrue(np.all(val <= 2))
np.testing.assert_array_equal(prob, 1 / 3)

def test_sparse_matrix(self):
iris_sparse = self.iris.to_sparse()
for lrn in [LogisticRegressionLearner, TreeLearner]: # skl and non-skl
model = lrn()(iris_sparse)
pred = model(iris_sparse.X.tocsc())
self.assertTupleEqual((len(self.iris),), pred.shape)
pred = model(iris_sparse.X.tolil())
self.assertTupleEqual((len(self.iris),), pred.shape)
pred = model(iris_sparse.X.tocoo())
self.assertTupleEqual((len(self.iris),), pred.shape)


if __name__ == '__main__':
unittest.main()
2 changes: 1 addition & 1 deletion Orange/tests/test_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
SimpleRandomForestLearner, EllipticEnvelopeLearner)
from Orange.classification.rules import _RuleLearner
from Orange.data import (ContinuousVariable, DiscreteVariable,
Domain, Table, Variable)
Domain, Table)
from Orange.data.table import DomainTransformationError
from Orange.evaluation import CrossValidation
from Orange.tests.dummy_learners import DummyLearner, DummyMulticlassLearner
Expand Down