FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Add K-Nearest Neighbors classifier by poorva0405 · Pull Request #7563 · TheAlgorithms/Java · GitHub

Add K-Nearest Neighbors classifier - #7563

Open
poorva0405 wants to merge 4 commits into
TheAlgorithms:masterfrom
poorva0405:feat-knearestneighbors
Open

Add K-Nearest Neighbors classifier#7563
poorva0405 wants to merge 4 commits into
TheAlgorithms:masterfrom
poorva0405:feat-knearestneighbors

Conversation

poorva0405 commented Aug 6, 2026
edited
Loading

Copy link
Copy Markdown

Description

This PR adds a K-Nearest Neighbors (KNN) classifier implementation to the machinelearning package.

Features

  • Implements KNN classification using Euclidean distance.
  • Supports training through fit().
  • Supports prediction for single and batch samples.
  • Uses deterministic tie-breaking when multiple classes receive the same number of votes.
  • Includes comprehensive input validation.
  • Includes JUnit 5 tests covering normal and edge cases.
  • Includes Javadocs for all public APIs.

Closes #7562

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized it.
  • All filenames are in PascalCase.
  • All functions and variable names follow Java naming conventions.
  • All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
  • All new algorithms include a corresponding test class that validates their functionality.
  • All new code is formatted with clang-format -i --style=file path/to/your/file.java

codecov-commenter commented Aug 6, 2026
edited
Loading

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.58824% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.48%. Comparing base (7c934ad) to head (37d77ef).
⚠️ Report is 10 commits behind head on master.

Files with missing lines Patch % Lines
...ealgorithms/machinelearning/KNearestNeighbors.java 95.58% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #7563      +/-   ##
============================================
+ Coverage     80.42%   80.48%   +0.05%     
- Complexity     7457     7491      +34     
============================================
  Files           815      816       +1     
  Lines         24055    24124      +69     
  Branches       4732     4751      +19     
============================================
+ Hits          19346    19415      +69     
- Misses         3945     3946       +1     
+ Partials        764      763       -1     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

AKASH02-byte left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Left an inline comment regarding exception checking in KNearestNeighbors.java. Overall, the implementation and tests look clean!


Map<Integer, Integer> votes = new HashMap<>();

if (k > trainingFeatures.length) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

The check if (k > trainingFeatures.length) currently happens inside predict(). Consider moving this validation check into fit() so that invalid $k$ values are caught early during dataset initialization rather than failing later during inference.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

+1 to moving this into fit(). A few additional points in favor:

  1. As written, the check fires only after the full distance pass and the O(n log n) sort, so all that work is wasted before the exception is thrown.
  2. From predict() an IllegalArgumentException is semantically off — the test point itself is already validated at that point; the real problem is the classifier's configuration vs. the fitted data, which would be an IllegalStateException. In fit() IAE becomes correct.
  3. throwsExceptionWhenKIsGreaterThanNumberOfTrainingSamples will need to expect the throw from fit() instead:
KNearestNeighbors knn = new KNearestNeighbors(7);
assertThrows(IllegalArgumentException.class, () -> knn.fit(features, labels));

alxkm left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Solid PR - clean implementation, good tests.

One change requested: move the k > trainingFeatures.length check into fit(), per the thread on line 168.

Improvements (non-blocking):

  • fields are declared mid-class, move them to the top next to k
  • fit() stores the caller's arrays directly — a defensive copy would be safer
  • the two "not fitted" null checks in predict() can be collapsed into one
  • Neighbor could be a record

Nice tests coverage.


Map<Integer, Integer> votes = new HashMap<>();

if (k > trainingFeatures.length) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

+1 to moving this into fit(). A few additional points in favor:

  1. As written, the check fires only after the full distance pass and the O(n log n) sort, so all that work is wasted before the exception is thrown.
  2. From predict() an IllegalArgumentException is semantically off — the test point itself is already validated at that point; the real problem is the classifier's configuration vs. the fitted data, which would be an IllegalStateException. In fit() IAE becomes correct.
  3. throwsExceptionWhenKIsGreaterThanNumberOfTrainingSamples will need to expect the throw from fit() instead:
KNearestNeighbors knn = new KNearestNeighbors(7);
assertThrows(IllegalArgumentException.class, () -> knn.fit(features, labels));

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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.

[FEATURE REQUEST] <title> Add K-Nearest Neighbors (KNN) Classification Algorithm

4 participants


Back | FazBrowse Home | New Git URL