-
-
Notifications
You must be signed in to change notification settings - Fork 25.8k
ENH: use Bayesian priors in Nearest Neighbors classifier (Issue 399) #970
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
Closed
cricketsong
wants to merge
8
commits into
scikit-learn:main
from
cricketsong:issue399_prior_neighbor
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
c6bafed
ENH: use Bayesian priors in Nearest Neighbors classifier (Issue 399)
cricketsong 3005a60
use `unique` to get integers from labels
cricketsong 884e7e2
replace 3 loops by calls to `np.bincount`
cricketsong 902dcb6
replace loop by call to `np.bincount`
cricketsong 3680fc5
parameter `class_prior` is processed by constructor
cricketsong e83c711
implement `predict` in terms of `predict_proba`
cricketsong 089dece
integrate `class_prior` parameter to narrative doc
cricketsong 4dec520
correct minor mistakes in documentation
cricketsong File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,6 +15,7 @@ | |
from ..base import BaseEstimator | ||
from ..metrics import pairwise_distances | ||
from ..utils import safe_asarray, atleast2d_or_csr | ||
from ..utils.fixes import unique | ||
|
||
|
||
class NeighborsWarning(UserWarning): | ||
|
@@ -45,14 +46,14 @@ def _get_weights(dist, weights): | |
"""Get the weights from an array of distances and a parameter ``weights`` | ||
|
||
Parameters | ||
=========== | ||
---------- | ||
dist: ndarray | ||
The input distances | ||
weights: {'uniform', 'distance' or a callable} | ||
The kind of weighting used | ||
|
||
Returns | ||
======== | ||
------- | ||
weights_arr: array of the same shape as ``dist`` | ||
if ``weights == 'uniform'``, then returns None | ||
""" | ||
|
@@ -68,6 +69,39 @@ def _get_weights(dist, weights): | |
raise ValueError("weights not recognized: should be 'uniform', " | ||
"'distance', or a callable function") | ||
|
||
def _check_class_prior(class_prior): | ||
"""Check to make sure class prior is valid.""" | ||
if class_prior in (None, 'default', 'flat'): | ||
return class_prior | ||
elif isinstance(class_prior, (list, np.ndarray)): | ||
return class_prior | ||
else: | ||
raise ValueError("class prior not recognized: should be 'default', " | ||
"'flat', or a list or ndarray") | ||
|
||
def _get_class_prior(y, class_prior): | ||
"""Get class prior from targets ``y`` and parameter ``class_prior`` | ||
|
||
Parameters | ||
---------- | ||
y : ndarray | ||
The target labels, from 0 to ``n-1`` (thus ``n`` classes) | ||
class_prior: {'default', 'flat' or a dict} | ||
The class prior probabilities to use | ||
|
||
Returns | ||
------- | ||
class_prior_arr: array of the same shape as ``np.unique(y)`` | ||
""" | ||
if class_prior in (None, 'default'): | ||
return np.bincount(y).astype(float) / len(y) | ||
elif class_prior == 'flat': | ||
return np.ones((len(np.unique(y)),)) / len(np.unique(y)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since we normalise later, we can just return 1 here. |
||
elif isinstance(class_prior, (list, np.ndarray)): | ||
return class_prior | ||
else: | ||
raise ValueError("class prior not recognized: should be 'default', " | ||
"'flat', or a list or ndarray") | ||
|
||
class NeighborsBase(BaseEstimator): | ||
"""Base class for nearest neighbors estimators.""" | ||
|
@@ -567,8 +601,7 @@ def fit(self, X, y): | |
y : {array-like, sparse matrix}, shape = [n_samples] | ||
Target values, array of integer values. | ||
""" | ||
self._y = np.asarray(y) | ||
self._classes = np.sort(np.unique(y)) | ||
self._classes, self._y = unique(y, return_inverse=True) | ||
return self._fit(X) | ||
|
||
|
||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
since we normalize later, we can ignore the
/ len(y)