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

[ENH] Bhatthacharayya distance #4111

Merged
merged 5 commits into from
Nov 1, 2019
Merged
Changes from 1 commit
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
24 changes: 11 additions & 13 deletions Orange/distance/distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,33 +645,31 @@ class PearsonRAbsolute(CorrelationDistance):
def fit(self, _):
return PearsonModel(True, self.axis, self.impute)


def _prob_dist(a):
# Makes the vector sum to one, as to mimic probability distribution.
return a / np.sum(a)

def non_negative(a):
#Raise an exception for infinities, nans and negative values
try:
check_array(a, accept_sparse=True, accept_large_sparse=True, ensure_2d=False)
except:
raise ValueError("Bhattcharyya distance requires non-negative values")
if sp.issparse(a):
if a.min() < 0:
raise ValueError("Bhattcharyya distance requires non-negative values")
return
if min(a) < 0:

def check_non_negative(a):
# Raise an exception for infinities, nans and negative values
check_array(a,
accept_sparse=True, accept_large_sparse=True, ensure_2d=False)
if a.min() < 0:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AndrejaKovacic, would this be OK, too?

Dense arrays also have a method min, so there's no need for if. Also, I think it is better to not change the exception message raised by check_array so the caller is informed that, for instance, there are nan values in the data.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's more informative this way.

raise ValueError("Bhattcharyya distance requires non-negative values")


def _bhattacharyya(a, b):
# not a real metric, does not obey triangle inequality
non_negative(a)
non_negative(b)
check_non_negative(a)
check_non_negative(b)
a = _prob_dist(a)
b = _prob_dist(b)
if sp.issparse(a):
return -np.log(np.sum(np.sqrt(a.multiply(b))))
return -np.log(np.sum(np.sqrt(a * b)))


class Bhattacharyya(Distance):
supports_discrete = False
supports_sparse = True
Expand Down