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

Add a knn module #1117

Merged
merged 60 commits into from
May 14, 2024
Merged

Add a knn module #1117

merged 60 commits into from
May 14, 2024

Conversation

elisno
Copy link
Member

@elisno elisno commented May 4, 2024

Summary

This PR prioritizes a refactoring of the two modules

  • cleanlab/outlier.py
  • cleanlab/datalab/internal/issue_manager/duplicate.py

that rely heavily on a knn object (NearestNeighbors) for scoring and flagging different kinds of issues.

MERGE THIS AFTER #1115 !

Included docs

image

More information

The logic for constructing a NearestNeighbor object has been duplicated in several places like so:

# Make sure features exist to fit a knn object
if features is None:
    raise ValueError(
        "Both knn and features arguments cannot be None at the same time. Not enough information to compute outlier scores."
    )

# Select a good value for the number of neighbors
if k is None:
    k = DEFAULT_K  # use default when knn and k are both None
N, M = features.shape
if k > N:  # Ensure number of neighbors less than number of examples
    raise ValueError(
        f"Number of nearest neighbors k={k} cannot exceed the number of examples N={len(features)} passed into the estimator (knn)."
    )

# Select a decent distance metric
if M > 3:  # use euclidean distance for lower dimensional spaces
    metric = "cosine"
elif N > 100:  # Use efficient implementation (numerically unstable in edge cases)
    metric = "euclidean"
else:  # Use scipy implementation for precise results
    metric = euclidean

# Construct the knn object
knn = NearestNeighbors(n_neighbors=k, metric=metric).fit(features)

This PR reduces this headache to a single function call, as this is usually some boilerplate code for creating a knn-object from scratch.

knn: NearestNeighbors = features_to_knn(features, n_neighbors=k)  # Optionally, specify a metric

Additionally, there are some dev docs for module added in the new directory cleanlab/internal/neighbor. Those are not a priority and can be omitted in this PR.

elisno added 27 commits May 3, 2024 15:49
…earch object from an array of numerical features
Copy link

codecov bot commented May 4, 2024

Codecov Report

Attention: Patch coverage is 96.03960% with 4 lines in your changes are missing coverage. Please review.

Project coverage is 96.05%. Comparing base (81af417) to head (402d3fe).
Report is 3 commits behind head on master.

❗ Current head 402d3fe differs from pull request most recent head bda30f2. Consider uploading reports for the commit bda30f2 to get more accurate results

Files Patch % Lines
cleanlab/internal/neighbor/knn_graph.py 93.33% 1 Missing and 1 partial ⚠️
cleanlab/internal/neighbor/search.py 75.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1117      +/-   ##
==========================================
- Coverage   96.13%   96.05%   -0.09%     
==========================================
  Files          76       80       +4     
  Lines        6088     6102      +14     
  Branches     1081     1075       -6     
==========================================
+ Hits         5853     5861       +8     
- Misses        140      143       +3     
- Partials       95       98       +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

)
knn = NearestNeighbors(n_neighbors=self.k, metric=self.metric).fit(features)

if self.metric and self.metric != knn.metric:
Copy link
Member Author

Choose a reason for hiding this comment

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

This condition won't evaluate to True, because even if the metric changed, then the knn object must have been given the same metric in this part of the code.

Removing it is safe.

cleanlab/internal/neighbor/neighbor.py Outdated Show resolved Hide resolved
@jwmueller jwmueller self-requested a review May 7, 2024 01:53
Copy link
Member

@jwmueller jwmueller left a comment

Choose a reason for hiding this comment

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

Looks good to me overall, except the remaining comments I've left.
Leaving final merge to @huiwengoh (I don't want to review this again)

@elisno Before you ping Hui Wen for the final review, please address all of my remaining comments, comment on them how they are addressed, and only then mark them as Resolved.

elisno and others added 6 commits May 7, 2024 14:02
Co-authored-by: Jonas Mueller <1390638+jwmueller@users.noreply.github.com>
Co-authored-by: Jonas Mueller <1390638+jwmueller@users.noreply.github.com>
… knn object

This solves two issues:
- The default metric choice can be extracted from the knn object, so the calling function is no longer responsible for figuring out what metric to pick. Instead, it should assume that the knn object has set a valid metric attribute (knn.metric).
- Removing the dependency on decide_default_metric means that we no longer need to cast features to a numpy array (statically, it was a Union[None, np.ndarray], which is incompatible with that function.
cleanlab/internal/neighbor/metric.py Outdated Show resolved Hide resolved
cleanlab/internal/neighbor/metric.py Outdated Show resolved Hide resolved
@elisno
Copy link
Member Author

elisno commented May 14, 2024

I've addressed the comments made by @jwmueller. @huiwen could you review + merge this?

@elisno elisno requested a review from huiwengoh May 14, 2024 00:29
Copy link
Contributor

@huiwengoh huiwengoh left a comment

Choose a reason for hiding this comment

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

lgtm! nice work

@huiwengoh huiwengoh merged commit 71ba4b3 into cleanlab:master May 14, 2024
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants