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

Make kNN more resilient to nominal data #1566

Closed
wants to merge 1 commit into from
Closed
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
19 changes: 18 additions & 1 deletion river/utils/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import functools
import itertools
import math
import numbers
import operator

import numpy as np
Expand Down Expand Up @@ -162,7 +163,23 @@ def minkowski_distance(a: dict, b: dict, p: int):
Manhattan distance. When `p=2`, this is equivalent to using the Euclidean distance.

"""
return sum((abs(a.get(k, 0.0) - b.get(k, 0.0))) ** p for k in {*a.keys(), *b.keys()}) ** (1 / p)

def abs_diff(a, b) -> float:
"""Naïve absolute difference of two objects.

If a and b are both numbers, this is the regular absolute difference.

Otherwise, the difference is 0 is the objects are the same and 1 if they are different.
"""
if isinstance(a, numbers.Real) and isinstance(b, numbers.Real):
return float(abs(a - b))
elif a == b:
return 0.0
return 1.0

return sum((abs_diff(a.get(k, 0.0), b.get(k, 0.0))) ** p for k in {*a.keys(), *b.keys()}) ** (
1 / p
)


def softmax(y_pred: dict):
Expand Down
Loading