code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_learning_curve_exploit_incremental_learning_routing():
"""Test that learning_curve routes metadata to the estimator correctly while
partial_fitting it with `exploit_incremental_learning=True`."""
n_samples = _num_samples(X)
rng = np.random.RandomState(0)
fit_sample_weight = rng.rand(n_samp... | Test that learning_curve routes metadata to the estimator correctly while
partial_fitting it with `exploit_incremental_learning=True`. | test_learning_curve_exploit_incremental_learning_routing | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_validation.py | BSD-3-Clause |
def _get_weights(dist, weights):
"""Get the weights from an array of distances and a parameter ``weights``.
Assume weights have already been validated.
Parameters
----------
dist : ndarray
The input distances.
weights : {'uniform', 'distance'}, callable or None
The kind of wei... | Get the weights from an array of distances and a parameter ``weights``.
Assume weights have already been validated.
Parameters
----------
dist : ndarray
The input distances.
weights : {'uniform', 'distance'}, callable or None
The kind of weighting used.
Returns
-------
... | _get_weights | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _is_sorted_by_data(graph):
"""Return whether the graph's non-zero entries are sorted by data.
The non-zero entries are stored in graph.data and graph.indices.
For each row (or sample), the non-zero entries can be either:
- sorted by indices, as after graph.sort_indices();
- sorted by da... | Return whether the graph's non-zero entries are sorted by data.
The non-zero entries are stored in graph.data and graph.indices.
For each row (or sample), the non-zero entries can be either:
- sorted by indices, as after graph.sort_indices();
- sorted by data, as after _check_precomputed(graph)... | _is_sorted_by_data | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _check_precomputed(X):
"""Check precomputed distance matrix.
If the precomputed distance matrix is sparse, it checks that the non-zero
entries are sorted by distances. If not, the matrix is copied and sorted.
Parameters
----------
X : {sparse matrix, array-like}, (n_samples, n_samples)
... | Check precomputed distance matrix.
If the precomputed distance matrix is sparse, it checks that the non-zero
entries are sorted by distances. If not, the matrix is copied and sorted.
Parameters
----------
X : {sparse matrix, array-like}, (n_samples, n_samples)
Distance matrix to other samp... | _check_precomputed | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def sort_graph_by_row_values(graph, copy=False, warn_when_not_sorted=True):
"""Sort a sparse graph such that each row is stored with increasing values.
.. versionadded:: 1.2
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Distance matrix to other samples, where ... | Sort a sparse graph such that each row is stored with increasing values.
.. versionadded:: 1.2
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Distance matrix to other samples, where only non-zero elements are
considered neighbors. Matrix is converted to CSR... | sort_graph_by_row_values | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _kneighbors_from_graph(graph, n_neighbors, return_distance):
"""Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_grap... | Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_graph`. Matrix should be of format CSR format.
n_neighbors : int
... | _kneighbors_from_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _radius_neighbors_from_graph(graph, radius, return_distance):
"""Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_gra... | Decompose a nearest neighbors sparse graph into distances and indices.
Parameters
----------
graph : sparse matrix of shape (n_samples, n_samples)
Neighbors graph as given by `kneighbors_graph` or
`radius_neighbors_graph`. Matrix should be of format CSR format.
radius : float
R... | _radius_neighbors_from_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _kneighbors_reduce_func(self, dist, start, n_neighbors, return_distance):
"""Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_sampl... | Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_samples)
The distance matrix.
start : int
The index in X whic... | _kneighbors_reduce_func | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def kneighbors(self, X=None, n_neighbors=None, return_distance=True):
"""Find the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_queries, n_features), \
or (n_q... | Find the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', default=None
The query p... | kneighbors | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def kneighbors_graph(self, X=None, n_neighbors=None, mode="connectivity"):
"""Compute the (weighted) graph of k-Neighbors for points in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precom... | Compute the (weighted) graph of k-Neighbors for points in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', default=None
The query point or points.
If not provided,... | kneighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def _radius_neighbors_reduce_func(self, dist, start, radius, return_distance):
"""Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_samp... | Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
----------
dist : ndarray of shape (n_samples_chunk, n_samples)
The distance matrix.
start : int
The index in X whic... | _radius_neighbors_reduce_func | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def radius_neighbors_graph(
self, X=None, radius=None, mode="connectivity", sort_results=False
):
"""Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Parameters
----------
X :... | Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query point or points.
... | radius_neighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_base.py | BSD-3-Clause |
def predict(self, X):
"""Predict the class labels for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictio... | Predict the class labels for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def predict_proba(self, X):
"""Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, p... | Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict_proba | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit the radius neighbors classifier from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y : {arra... | Fit the radius neighbors classifier from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : {array-like, sparse matrix} of shape (n... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def predict_proba(self, X):
"""Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, p... | Return probability estimates for the test data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict_proba | python | scikit-learn/scikit-learn | sklearn/neighbors/_classification.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_classification.py | BSD-3-Clause |
def _check_params(X, metric, p, metric_params):
"""Check the validity of the input parameters"""
params = zip(["metric", "p", "metric_params"], [metric, p, metric_params])
est_params = X.get_params()
for param_name, func_param in params:
if func_param != est_params[param_name]:
raise... | Check the validity of the input parameters | _check_params | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def _query_include_self(X, include_self, mode):
"""Return the query based on include_self param"""
if include_self == "auto":
include_self = mode == "connectivity"
# it does not include each sample as its own neighbors
if not include_self:
X = None
return X | Return the query based on include_self param | _query_include_self | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def kneighbors_graph(
X,
n_neighbors,
*,
mode="connectivity",
metric="minkowski",
p=2,
metric_params=None,
include_self=False,
n_jobs=None,
):
"""Compute the (weighted) graph of k-Neighbors for points in X.
Read more in the :ref:`User Guide <unsupervised_neighbors>`.
Pa... | Compute the (weighted) graph of k-Neighbors for points in X.
Read more in the :ref:`User Guide <unsupervised_neighbors>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Sample data.
n_neighbors : int
Number of neighbors for each sample.
... | kneighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def radius_neighbors_graph(
X,
radius,
*,
mode="connectivity",
metric="minkowski",
p=2,
metric_params=None,
include_self=False,
n_jobs=None,
):
"""Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
... | Compute the (weighted) graph of Neighbors for points in X.
Neighborhoods are restricted the points at a distance lower than
radius.
Read more in the :ref:`User Guide <unsupervised_neighbors>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Sampl... | radius_neighbors_graph | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the k-nearest neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y... | Fit the k-nearest neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : Ignored
Not used, presen... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def transform(self, X):
"""Compute the (weighted) graph of Neighbors for points in X.
Parameters
----------
X : array-like of shape (n_samples_transform, n_features)
Sample data.
Returns
-------
Xt : sparse matrix of shape (n_samples_transform, n_sam... | Compute the (weighted) graph of Neighbors for points in X.
Parameters
----------
X : array-like of shape (n_samples_transform, n_features)
Sample data.
Returns
-------
Xt : sparse matrix of shape (n_samples_transform, n_samples_fit)
Xt[i, j] is a... | transform | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the radius neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y :... | Fit the radius neighbors transformer from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : Ignored
Not used, present ... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_graph.py | BSD-3-Clause |
def fit(self, X, y=None, sample_weight=None):
"""Fit the Kernel Density model on the data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
y :... | Fit the Kernel Density model on the data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
y : None
Ignored. This parameter exists only for... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_kde.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_kde.py | BSD-3-Clause |
def score_samples(self, X):
"""Compute the log-likelihood of each sample under the model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
An array of points to query. Last dimension should match dimension
of training data (n_features).
... | Compute the log-likelihood of each sample under the model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
An array of points to query. Last dimension should match dimension
of training data (n_features).
Returns
-------
de... | score_samples | python | scikit-learn/scikit-learn | sklearn/neighbors/_kde.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_kde.py | BSD-3-Clause |
def sample(self, n_samples=1, random_state=None):
"""Generate random samples from the model.
Currently, this is implemented only for gaussian and tophat kernels.
Parameters
----------
n_samples : int, default=1
Number of samples to generate.
random_state : ... | Generate random samples from the model.
Currently, this is implemented only for gaussian and tophat kernels.
Parameters
----------
n_samples : int, default=1
Number of samples to generate.
random_state : int, RandomState instance or None, default=None
D... | sample | python | scikit-learn/scikit-learn | sklearn/neighbors/_kde.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_kde.py | BSD-3-Clause |
def fit_predict(self, X, y=None):
"""Fit the model to the training set X and return the labels.
**Not available for novelty detection (when novelty is set to True).**
Label is 1 for an inlier and -1 for an outlier according to the LOF
score and the contamination parameter.
Para... | Fit the model to the training set X and return the labels.
**Not available for novelty detection (when novelty is set to True).**
Label is 1 for an inlier and -1 for an outlier according to the LOF
score and the contamination parameter.
Parameters
----------
X : {array-... | fit_predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the local outlier factor detector from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples) if metric='precomputed'
Training data.
y ... | Fit the local outlier factor detector from the training dataset.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric='precomputed'
Training data.
y : Ignored
Not used, present... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def _predict(self, X=None):
"""Predict the labels (1 inlier, -1 outlier) of X according to LOF.
If X is None, returns the same as fit_predict(X_train).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query sam... | Predict the labels (1 inlier, -1 outlier) of X according to LOF.
If X is None, returns the same as fit_predict(X_train).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
The query sample or samples to compute the Local Out... | _predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def score_samples(self, X):
"""Opposite of the Local Outlier Factor of X.
It is the opposite as bigger is better, i.e. large values correspond
to inliers.
**Only available for novelty detection (when novelty is set to True).**
The argument X is supposed to contain *new data*: i... | Opposite of the Local Outlier Factor of X.
It is the opposite as bigger is better, i.e. large values correspond
to inliers.
**Only available for novelty detection (when novelty is set to True).**
The argument X is supposed to contain *new data*: if X contains a
point from train... | score_samples | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def _local_reachability_density(self, distances_X, neighbors_indices):
"""The local reachability density (LRD)
The LRD of a sample is the inverse of the average reachability
distance of its k-nearest neighbors.
Parameters
----------
distances_X : ndarray of shape (n_que... | The local reachability density (LRD)
The LRD of a sample is the inverse of the average reachability
distance of its k-nearest neighbors.
Parameters
----------
distances_X : ndarray of shape (n_queries, self.n_neighbors)
Distances to the neighbors (in the training sa... | _local_reachability_density | python | scikit-learn/scikit-learn | sklearn/neighbors/_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_lof.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit the model according to the given training data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The corresponding training labels.
Retur... | Fit the model according to the given training data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The corresponding training labels.
Returns
-------
self ... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def transform(self, X):
"""Apply the learned transformation to the given data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data samples.
Returns
-------
X_embedded: ndarray of shape (n_samples, n_components)
The ... | Apply the learned transformation to the given data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data samples.
Returns
-------
X_embedded: ndarray of shape (n_samples, n_components)
The data samples transformed.
... | transform | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def _initialize(self, X, y, init):
"""Initialize the transformation.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The training labels.
init : str or ndarray of s... | Initialize the transformation.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training samples.
y : array-like of shape (n_samples,)
The training labels.
init : str or ndarray of shape (n_features_a, n_features_b)
... | _initialize | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def _callback(self, transformation):
"""Called after each iteration of the optimizer.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The solution computed by the optimizer in this iteration.
"""
if self.callback is not No... | Called after each iteration of the optimizer.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The solution computed by the optimizer in this iteration.
| _callback | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def _loss_grad_lbfgs(self, transformation, X, same_class_mask, sign=1.0):
"""Compute the loss and the loss gradient w.r.t. `transformation`.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The raveled linear transformation on which to com... | Compute the loss and the loss gradient w.r.t. `transformation`.
Parameters
----------
transformation : ndarray of shape (n_components * n_features,)
The raveled linear transformation on which to compute loss and
evaluate gradient.
X : ndarray of shape (n_samples... | _loss_grad_lbfgs | python | scikit-learn/scikit-learn | sklearn/neighbors/_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nca.py | BSD-3-Clause |
def fit(self, X, y):
"""
Fit the NearestCentroid model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features... |
Fit the NearestCentroid model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features` is the number of features.
... | fit | python | scikit-learn/scikit-learn | sklearn/neighbors/_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nearest_centroid.py | BSD-3-Clause |
def predict(self, X):
"""Perform classification on an array of test vectors `X`.
The predicted class `C` for each sample in `X` is returned.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input data.
Returns
-... | Perform classification on an array of test vectors `X`.
The predicted class `C` for each sample in `X` is returned.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input data.
Returns
-------
y_pred : ndarray o... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_nearest_centroid.py | BSD-3-Clause |
def predict(self, X):
"""Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for... | Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_regression.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_regression.py | BSD-3-Clause |
def predict(self, X):
"""Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), \
or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for... | Predict the target for the provided data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed', or None
Test samples. If `None`, predictions for all indexed points are
... | predict | python | scikit-learn/scikit-learn | sklearn/neighbors/_regression.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/_regression.py | BSD-3-Clause |
def test_array_object_type(BallTreeImplementation):
"""Check that we do not accept object dtype array."""
X = np.array([(1, 2, 3), (2, 5), (5, 5, 1, 2)], dtype=object)
with pytest.raises(ValueError, match="setting an array element with a sequence"):
BallTreeImplementation(X) | Check that we do not accept object dtype array. | test_array_object_type | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_ball_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_ball_tree.py | BSD-3-Clause |
def _has_explicit_diagonal(X):
"""Return True if the diagonal is explicitly stored"""
X = X.tocoo()
explicit = X.row[X.row == X.col]
return len(explicit) == X.shape[0] | Return True if the diagonal is explicitly stored | _has_explicit_diagonal | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_graph.py | BSD-3-Clause |
def test_graph_feature_names_out(Klass):
"""Check `get_feature_names_out` for transformers defined in `_graph.py`."""
n_samples_fit = 20
n_features = 10
rng = np.random.RandomState(42)
X = rng.randn(n_samples_fit, n_features)
est = Klass().fit(X)
names_out = est.get_feature_names_out()
... | Check `get_feature_names_out` for transformers defined in `_graph.py`. | test_graph_feature_names_out | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_graph.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_graph.py | BSD-3-Clause |
def test_kdtree_picklable_with_joblib(BinarySearchTree):
"""Make sure that KDTree queries work when joblib memmaps.
Non-regression test for #21685 and #21228."""
rng = np.random.RandomState(0)
X = rng.random_sample((10, 3))
tree = BinarySearchTree(X, leaf_size=2)
# Call Parallel with max_nbyte... | Make sure that KDTree queries work when joblib memmaps.
Non-regression test for #21685 and #21228. | test_kdtree_picklable_with_joblib | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_kd_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_kd_tree.py | BSD-3-Clause |
def test_lof_error_n_neighbors_too_large():
"""Check that we raise a proper error message when n_neighbors == n_samples.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/17207
"""
X = np.ones((7, 7))
msg = (
"Expected n_neighbors < n_samples_fit, but n_neigh... | Check that we raise a proper error message when n_neighbors == n_samples.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/17207
| test_lof_error_n_neighbors_too_large | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_lof.py | BSD-3-Clause |
def test_lof_input_dtype_preservation(global_dtype, algorithm, contamination, novelty):
"""Check that the fitted attributes are stored using the data type of X."""
X = iris.data.astype(global_dtype, copy=False)
iso = neighbors.LocalOutlierFactor(
n_neighbors=5, algorithm=algorithm, contamination=co... | Check that the fitted attributes are stored using the data type of X. | test_lof_input_dtype_preservation | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_lof.py | BSD-3-Clause |
def test_lof_duplicate_samples():
"""
Check that LocalOutlierFactor raises a warning when duplicate values
in the training data cause inaccurate results.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27839
"""
rng = np.random.default_rng(0)
x = rng.permu... |
Check that LocalOutlierFactor raises a warning when duplicate values
in the training data cause inaccurate results.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27839
| test_lof_duplicate_samples | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_lof.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_lof.py | BSD-3-Clause |
def test_simple_example():
"""Test on a simple example.
Puts four points in the input space where the opposite labels points are
next to each other. After transform the samples from the same class
should be next to each other.
"""
X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])
y = np.array... | Test on a simple example.
Puts four points in the input space where the opposite labels points are
next to each other. After transform the samples from the same class
should be next to each other.
| test_simple_example | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nca.py | BSD-3-Clause |
def test_toy_example_collapse_points():
"""Test on a toy example of three points that should collapse
We build a simple example: two points from the same class and a point from
a different class in the middle of them. On this simple example, the new
(transformed) points should all collapse into one sin... | Test on a toy example of three points that should collapse
We build a simple example: two points from the same class and a point from
a different class in the middle of them. On this simple example, the new
(transformed) points should all collapse into one single point. Indeed, the
objective is 2/(1 + ... | test_toy_example_collapse_points | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nca.py | BSD-3-Clause |
def callback(self, transformation, n_iter):
"""Stores the last value of the loss function"""
self.loss, _ = self.fake_nca._loss_grad_lbfgs(
transformation, self.X, self.same_class_mask, -1.0
) | Stores the last value of the loss function | callback | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nca.py | BSD-3-Clause |
def test_finite_differences(global_random_seed):
"""Test gradient of loss function
Assert that the gradient is almost equal to its finite differences
approximation.
"""
# Initialize the transformation `M`, as well as `X` and `y` and `NCA`
rng = np.random.RandomState(global_random_seed)
X, y... | Test gradient of loss function
Assert that the gradient is almost equal to its finite differences
approximation.
| test_finite_differences | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nca.py | BSD-3-Clause |
def test_expected_transformation_shape():
"""Test that the transformation has the expected shape."""
X = iris_data
y = iris_target
class TransformationStorer:
def __init__(self, X, y):
# Initialize a fake NCA and variables needed to call the loss
# function:
... | Test that the transformation has the expected shape. | test_expected_transformation_shape | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nca.py | BSD-3-Clause |
def test_nca_feature_names_out(n_components):
"""Check `get_feature_names_out` for `NeighborhoodComponentsAnalysis`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28293
"""
X = iris_data
y = iris_target
est = NeighborhoodComponentsAnalysis(n_components=n_com... | Check `get_feature_names_out` for `NeighborhoodComponentsAnalysis`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28293
| test_nca_feature_names_out | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nca.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nca.py | BSD-3-Clause |
def test_negative_priors_error():
"""Check that we raise an error when the user-defined priors are negative."""
clf = NearestCentroid(priors=[-2, 4])
with pytest.raises(ValueError, match="priors must be non-negative"):
clf.fit(X, y) | Check that we raise an error when the user-defined priors are negative. | test_negative_priors_error | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nearest_centroid.py | BSD-3-Clause |
def test_warn_non_normalized_priors():
"""Check that we raise a warning and normalize the user-defined priors when they
don't sum to 1.
"""
priors = [2, 4]
clf = NearestCentroid(priors=priors)
with pytest.warns(
UserWarning,
match="The priors do not sum to 1. Normalizing such tha... | Check that we raise a warning and normalize the user-defined priors when they
don't sum to 1.
| test_warn_non_normalized_priors | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nearest_centroid.py | BSD-3-Clause |
def test_method_not_available_with_manhattan(response_method):
"""Check that we raise an AttributeError with Manhattan metric when trying
to call a non-thresholded response method.
"""
clf = NearestCentroid(metric="manhattan").fit(X, y)
with pytest.raises(AttributeError):
getattr(clf, respon... | Check that we raise an AttributeError with Manhattan metric when trying
to call a non-thresholded response method.
| test_method_not_available_with_manhattan | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nearest_centroid.py | BSD-3-Clause |
def test_error_zero_variances(array_constructor):
"""Check that we raise an error when the variance for all features is zero."""
X = np.ones((len(y), 2))
X[:, 1] *= 2
X = array_constructor(X)
clf = NearestCentroid()
with pytest.raises(ValueError, match="All features have zero variance"):
... | Check that we raise an error when the variance for all features is zero. | test_error_zero_variances | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_nearest_centroid.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_nearest_centroid.py | BSD-3-Clause |
def _parse_metric(metric: str, dtype=None):
"""
Helper function for properly building a type-specialized DistanceMetric instances.
Constructs a type-specialized DistanceMetric instance from a string
beginning with "DM_" while allowing a pass-through for other metric-specifying
strings. This is nece... |
Helper function for properly building a type-specialized DistanceMetric instances.
Constructs a type-specialized DistanceMetric instance from a string
beginning with "DM_" while allowing a pass-through for other metric-specifying
strings. This is necessary since we wish to parameterize dtype independe... | _parse_metric | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def _generate_test_params_for(metric: str, n_features: int):
"""Return list of DistanceMetric kwargs for tests."""
# Distinguishing on cases not to compute unneeded datastructures.
rng = np.random.RandomState(1)
if metric == "minkowski":
return [
dict(p=1.5),
dict(p=2),... | Return list of DistanceMetric kwargs for tests. | _generate_test_params_for | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def _weight_func(dist):
"""Weight function to replace lambda d: d ** -2.
The lambda function is not valid because:
if d==0 then 0^-2 is not valid."""
# Dist could be multidimensional, flatten it so all values
# can be looped
with np.errstate(divide="ignore"):
retval = 1.0 / dist
ret... | Weight function to replace lambda d: d ** -2.
The lambda function is not valid because:
if d==0 then 0^-2 is not valid. | _weight_func | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def check_precomputed(make_train_test, estimators):
"""Tests unsupervised NearestNeighbors with a distance matrix."""
# Note: smaller samples may result in spurious test success
rng = np.random.RandomState(42)
X = rng.random_sample((10, 4))
Y = rng.random_sample((3, 4))
DXX, DYX = make_train_tes... | Tests unsupervised NearestNeighbors with a distance matrix. | check_precomputed | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_radius_neighbors_boundary_handling():
"""Test whether points lying on boundary are handled consistently
Also ensures that even with only one query point, an object array
is returned rather than a 2d array.
"""
X = np.array([[1.5], [3.0], [3.01]])
radius = 3.0
for algorithm in ALG... | Test whether points lying on boundary are handled consistently
Also ensures that even with only one query point, an object array
is returned rather than a 2d array.
| test_radius_neighbors_boundary_handling | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_neighbors_validate_parameters(Estimator, csr_container):
"""Additional parameter validation for *Neighbors* estimators not covered by common
validation."""
X = rng.random_sample((10, 2))
Xsparse = csr_container(X)
X3 = rng.random_sample((10, 3))
y = np.ones(10)
nbrs = Estimator(alg... | Additional parameter validation for *Neighbors* estimators not covered by common
validation. | test_neighbors_validate_parameters | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_neighbors_minkowski_semimetric_algo_warn(Estimator, n_features, algorithm):
"""
Validation of all classes extending NeighborsBase with
Minkowski semi-metrics (i.e. when 0 < p < 1). That proper
Warning is raised for `algorithm="auto"` and "brute".
"""
X = rng.random_sample((10, n_feature... |
Validation of all classes extending NeighborsBase with
Minkowski semi-metrics (i.e. when 0 < p < 1). That proper
Warning is raised for `algorithm="auto"` and "brute".
| test_neighbors_minkowski_semimetric_algo_warn | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_neighbors_minkowski_semimetric_algo_error(Estimator, n_features, algorithm):
"""Check that we raise a proper error if `algorithm!='brute'` and `p<1`."""
X = rng.random_sample((10, 2))
y = np.ones(10)
model = Estimator(algorithm=algorithm, p=0.1)
msg = (
f'algorithm="{algorithm}" do... | Check that we raise a proper error if `algorithm!='brute'` and `p<1`. | test_neighbors_minkowski_semimetric_algo_error | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_regressor_predict_on_arraylikes():
"""Ensures that `predict` works for array-likes when `weights` is a callable.
Non-regression test for #22687.
"""
X = [[5, 1], [3, 1], [4, 3], [0, 3]]
y = [2, 3, 5, 6]
def _weights(dist):
return np.ones_like(dist)
est = KNeighborsRegress... | Ensures that `predict` works for array-likes when `weights` is a callable.
Non-regression test for #22687.
| test_regressor_predict_on_arraylikes | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_nan_euclidean_support(Estimator, params):
"""Check that the different neighbor estimators are lenient towards `nan`
values if using `metric="nan_euclidean"`.
"""
X = [[0, 1], [1, np.nan], [2, 3], [3, 5]]
y = [0, 0, 1, 1]
params.update({"metric": "nan_euclidean"})
estimator = Estim... | Check that the different neighbor estimators are lenient towards `nan`
values if using `metric="nan_euclidean"`.
| test_nan_euclidean_support | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_predict_dataframe():
"""Check that KNN predict works with dataframes
non-regression test for issue #26768
"""
pd = pytest.importorskip("pandas")
X = pd.DataFrame(np.array([[1, 2], [3, 4], [5, 6], [7, 8]]), columns=["a", "b"])
y = np.array([1, 2, 3, 4])
knn = neighbors.KNeighborsC... | Check that KNN predict works with dataframes
non-regression test for issue #26768
| test_predict_dataframe | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_nearest_neighbours_works_with_p_less_than_1():
"""Check that NearestNeighbors works with :math:`p \\in (0,1)` when `algorithm`
is `"auto"` or `"brute"` regardless of the dtype of X.
Non-regression test for issue #26548
"""
X = np.array([[1.0, 0.0], [0.0, 0.0], [0.0, 1.0]])
neigh = neig... | Check that NearestNeighbors works with :math:`p \in (0,1)` when `algorithm`
is `"auto"` or `"brute"` regardless of the dtype of X.
Non-regression test for issue #26548
| test_nearest_neighbours_works_with_p_less_than_1 | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_KNeighborsClassifier_raise_on_all_zero_weights():
"""Check that `predict` and `predict_proba` raises on sample of all zeros weights.
Related to Issue #25854.
"""
X = [[0, 1], [1, 2], [2, 3], [3, 4]]
y = [0, 0, 1, 1]
def _weights(dist):
return np.vectorize(lambda x: 0 if x > 0.... | Check that `predict` and `predict_proba` raises on sample of all zeros weights.
Related to Issue #25854.
| test_KNeighborsClassifier_raise_on_all_zero_weights | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_neighbor_classifiers_loocv(nn_model, algorithm):
"""Check that `predict` and related functions work fine with X=None
Calling predict with X=None computes a prediction for each training point
from the labels of its neighbors (without the label of the data point being
predicted upon). This is th... | Check that `predict` and related functions work fine with X=None
Calling predict with X=None computes a prediction for each training point
from the labels of its neighbors (without the label of the data point being
predicted upon). This is therefore mathematically equivalent to
leave-one-out cross-vali... | test_neighbor_classifiers_loocv | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def test_neighbor_regressors_loocv(nn_model, algorithm):
"""Check that `predict` and related functions work fine with X=None"""
X, y = datasets.make_regression(n_samples=15, n_features=2, random_state=0)
# Only checking cross_val_predict and not cross_val_score because
# cross_val_score does not work w... | Check that `predict` and related functions work fine with X=None | test_neighbor_regressors_loocv | python | scikit-learn/scikit-learn | sklearn/neighbors/tests/test_neighbors.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/tests/test_neighbors.py | BSD-3-Clause |
def inplace_softmax(X):
"""Compute the K-way softmax function inplace.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data.
"""
tmp = X - X.max(axis=1)[:, np.newaxis]
np.exp(tmp, out=X)
X /= X.sum(axis=1)[:, np.newaxis] | Compute the K-way softmax function inplace.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data.
| inplace_softmax | python | scikit-learn/scikit-learn | sklearn/neural_network/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_base.py | BSD-3-Clause |
def inplace_logistic_derivative(Z, delta):
"""Apply the derivative of the logistic sigmoid function.
It exploits the fact that the derivative is a simple function of the output
value from logistic function.
Parameters
----------
Z : {array-like, sparse matrix}, shape (n_samples, n_features)
... | Apply the derivative of the logistic sigmoid function.
It exploits the fact that the derivative is a simple function of the output
value from logistic function.
Parameters
----------
Z : {array-like, sparse matrix}, shape (n_samples, n_features)
The data which was output from the logistic ... | inplace_logistic_derivative | python | scikit-learn/scikit-learn | sklearn/neural_network/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_base.py | BSD-3-Clause |
def squared_loss(y_true, y_pred, sample_weight=None):
"""Compute the squared loss for regression.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) values.
y_pred : array-like or label indicator matrix
Predicted values, as returned by a regr... | Compute the squared loss for regression.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) values.
y_pred : array-like or label indicator matrix
Predicted values, as returned by a regression estimator.
sample_weight : array-like of shape (n... | squared_loss | python | scikit-learn/scikit-learn | sklearn/neural_network/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_base.py | BSD-3-Clause |
def poisson_loss(y_true, y_pred, sample_weight=None):
"""Compute (half of the) Poisson deviance loss for regression.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted values, as... | Compute (half of the) Poisson deviance loss for regression.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or label indicator matrix
Predicted values, as returned by a regression estimator.
sample_weight : arr... | poisson_loss | python | scikit-learn/scikit-learn | sklearn/neural_network/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_base.py | BSD-3-Clause |
def log_loss(y_true, y_prob, sample_weight=None):
"""Compute Logistic loss for classification.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_prob : array-like of float, shape = (n_samples, n_classes)
Predicted probabilities, as... | Compute Logistic loss for classification.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_prob : array-like of float, shape = (n_samples, n_classes)
Predicted probabilities, as returned by a classifier's
predict_proba method.... | log_loss | python | scikit-learn/scikit-learn | sklearn/neural_network/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_base.py | BSD-3-Clause |
def binary_log_loss(y_true, y_prob, sample_weight=None):
"""Compute binary logistic loss for classification.
This is identical to log_loss in binary classification case,
but is kept for its use in multilabel case.
Parameters
----------
y_true : array-like or label indicator matrix
Grou... | Compute binary logistic loss for classification.
This is identical to log_loss in binary classification case,
but is kept for its use in multilabel case.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_prob : array-like of float, sh... | binary_log_loss | python | scikit-learn/scikit-learn | sklearn/neural_network/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_base.py | BSD-3-Clause |
def _unpack(self, packed_parameters):
"""Extract the coefficients and intercepts from packed_parameters."""
for i in range(self.n_layers_ - 1):
start, end, shape = self._coef_indptr[i]
self.coefs_[i] = np.reshape(packed_parameters[start:end], shape)
start, end = self... | Extract the coefficients and intercepts from packed_parameters. | _unpack | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def _forward_pass(self, activations):
"""Perform a forward pass on the network by computing the values
of the neurons in the hidden layers and the output layer.
Parameters
----------
activations : list, length = n_layers - 1
The ith element of the list holds the valu... | Perform a forward pass on the network by computing the values
of the neurons in the hidden layers and the output layer.
Parameters
----------
activations : list, length = n_layers - 1
The ith element of the list holds the values of the ith layer.
| _forward_pass | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def _forward_pass_fast(self, X, check_input=True):
"""Predict using the trained model
This is the same as _forward_pass but does not record the activations
of all layers and only returns the last layer's activation.
Parameters
----------
X : {array-like, sparse matrix} ... | Predict using the trained model
This is the same as _forward_pass but does not record the activations
of all layers and only returns the last layer's activation.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data.
... | _forward_pass_fast | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def _compute_loss_grad(
self, layer, sw_sum, activations, deltas, coef_grads, intercept_grads
):
"""Compute the gradient of loss with respect to coefs and intercept for
specified layer.
This function does backpropagation for the specified one layer.
"""
coef_grads[la... | Compute the gradient of loss with respect to coefs and intercept for
specified layer.
This function does backpropagation for the specified one layer.
| _compute_loss_grad | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def _loss_grad_lbfgs(
self,
packed_coef_inter,
X,
y,
sample_weight,
activations,
deltas,
coef_grads,
intercept_grads,
):
"""Compute the MLP loss function and its corresponding derivatives
with respect to the different parameters... | Compute the MLP loss function and its corresponding derivatives
with respect to the different parameters given in the initialization.
Returned gradients are packed in a single vector so it can be used
in lbfgs
Parameters
----------
packed_coef_inter : ndarray
... | _loss_grad_lbfgs | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def _backprop(
self, X, y, sample_weight, activations, deltas, coef_grads, intercept_grads
):
"""Compute the MLP loss function and its corresponding derivatives
with respect to each parameter: weights and bias vectors.
Parameters
----------
X : {array-like, sparse ma... | Compute the MLP loss function and its corresponding derivatives
with respect to each parameter: weights and bias vectors.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data.
y : ndarray of shape (n_samples,)
... | _backprop | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def _score_with_function(self, X, y, sample_weight, score_function):
"""Private score method without input validation."""
# Input validation would remove feature names, so we disable it
y_pred = self._predict(X, check_input=False)
if np.isnan(y_pred).any() or np.isinf(y_pred).any():
... | Private score method without input validation. | _score_with_function | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def _predict(self, X, check_input=True):
"""Private predict method with optional input validation"""
y_pred = self._forward_pass_fast(X, check_input=check_input)
if self.n_outputs_ == 1:
y_pred = y_pred.ravel()
return self._label_binarizer.inverse_transform(y_pred) | Private predict method with optional input validation | _predict | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def predict_log_proba(self, X):
"""Return the log of probability estimates.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input data.
Returns
-------
log_y_prob : ndarray of shape (n_samples, n_classes)
The predic... | Return the log of probability estimates.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input data.
Returns
-------
log_y_prob : ndarray of shape (n_samples, n_classes)
The predicted log-probability of the sample for each ... | predict_log_proba | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def predict_proba(self, X):
"""Probability estimates.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data.
Returns
-------
y_prob : ndarray of shape (n_samples, n_classes)
The predicted pr... | Probability estimates.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data.
Returns
-------
y_prob : ndarray of shape (n_samples, n_classes)
The predicted probability of the sample for each class ... | predict_proba | python | scikit-learn/scikit-learn | sklearn/neural_network/_multilayer_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_multilayer_perceptron.py | BSD-3-Clause |
def transform(self, X):
"""Compute the hidden layer activation probabilities, P(h=1|v=X).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to be transformed.
Returns
-------
h : ndarray of shape (n_sampl... | Compute the hidden layer activation probabilities, P(h=1|v=X).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to be transformed.
Returns
-------
h : ndarray of shape (n_samples, n_components)
Laten... | transform | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def _mean_hiddens(self, v):
"""Computes the probabilities P(h=1|v).
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
h : ndarray of shape (n_samples, n_components)
Correspondi... | Computes the probabilities P(h=1|v).
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
h : ndarray of shape (n_samples, n_components)
Corresponding mean field values for the hidden lay... | _mean_hiddens | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def _sample_hiddens(self, v, rng):
"""Sample from the distribution P(h|v).
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer to sample from.
rng : RandomState instance
Random number generator to use.
... | Sample from the distribution P(h|v).
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer to sample from.
rng : RandomState instance
Random number generator to use.
Returns
-------
h : ndarray of... | _sample_hiddens | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def _sample_visibles(self, h, rng):
"""Sample from the distribution P(v|h).
Parameters
----------
h : ndarray of shape (n_samples, n_components)
Values of the hidden layer to sample from.
rng : RandomState instance
Random number generator to use.
... | Sample from the distribution P(v|h).
Parameters
----------
h : ndarray of shape (n_samples, n_components)
Values of the hidden layer to sample from.
rng : RandomState instance
Random number generator to use.
Returns
-------
v : ndarray o... | _sample_visibles | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def _free_energy(self, v):
"""Computes the free energy F(v) = - log sum_h exp(-E(v,h)).
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
free_energy : ndarray of shape (n_samples,)
... | Computes the free energy F(v) = - log sum_h exp(-E(v,h)).
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
free_energy : ndarray of shape (n_samples,)
The value of the free energy.
... | _free_energy | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def gibbs(self, v):
"""Perform one Gibbs sampling step.
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer to start from.
Returns
-------
v_new : ndarray of shape (n_samples, n_features)
Values ... | Perform one Gibbs sampling step.
Parameters
----------
v : ndarray of shape (n_samples, n_features)
Values of the visible layer to start from.
Returns
-------
v_new : ndarray of shape (n_samples, n_features)
Values of the visible layer after one ... | gibbs | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def partial_fit(self, X, y=None):
"""Fit the model to the partial segment of the data X.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target... | Fit the model to the partial segment of the data X.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformation... | partial_fit | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def _fit(self, v_pos, rng):
"""Inner fit for one mini-batch.
Adjust the parameters to maximize the likelihood of v using
Stochastic Maximum Likelihood (SML).
Parameters
----------
v_pos : ndarray of shape (n_samples, n_features)
The data to use for training.... | Inner fit for one mini-batch.
Adjust the parameters to maximize the likelihood of v using
Stochastic Maximum Likelihood (SML).
Parameters
----------
v_pos : ndarray of shape (n_samples, n_features)
The data to use for training.
rng : RandomState instance
... | _fit | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def score_samples(self, X):
"""Compute the pseudo-likelihood of X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Values of the visible layer. Must be all-boolean (not checked).
Returns
-------
pseudo_likelihoo... | Compute the pseudo-likelihood of X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Values of the visible layer. Must be all-boolean (not checked).
Returns
-------
pseudo_likelihood : ndarray of shape (n_samples,)
... | score_samples | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the model to the data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (No... | Fit the model to the data X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).... | fit | python | scikit-learn/scikit-learn | sklearn/neural_network/_rbm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_rbm.py | BSD-3-Clause |
def update_params(self, params, grads):
"""Update parameters with given gradients
Parameters
----------
params : list of length = len(coefs_) + len(intercepts_)
The concatenated list containing coefs_ and intercepts_ in MLP
model. Used for initializing velocities... | Update parameters with given gradients
Parameters
----------
params : list of length = len(coefs_) + len(intercepts_)
The concatenated list containing coefs_ and intercepts_ in MLP
model. Used for initializing velocities and updating params
grads : list of lengt... | update_params | python | scikit-learn/scikit-learn | sklearn/neural_network/_stochastic_optimizers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_stochastic_optimizers.py | BSD-3-Clause |
def trigger_stopping(self, msg, verbose):
"""Decides whether it is time to stop training
Parameters
----------
msg : str
Message passed in for verbose output
verbose : bool
Print message to stdin if True
Returns
-------
is_stoppi... | Decides whether it is time to stop training
Parameters
----------
msg : str
Message passed in for verbose output
verbose : bool
Print message to stdin if True
Returns
-------
is_stopping : bool
True if training needs to stop
... | trigger_stopping | python | scikit-learn/scikit-learn | sklearn/neural_network/_stochastic_optimizers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/_stochastic_optimizers.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.