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_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_dtype_equivalence(algorithm, novelty, contamination):
"""Check the equivalence of the results with 32 and 64 bits input."""
inliers = iris.data[:50] # setosa iris are really distinct from others
outliers = iris.data[-5:] # virginica will be considered as outliers
# lower the precision of... | Check the equivalence of the results with 32 and 64 bits input. | test_lof_dtype_equivalence | 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 _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 y_pred.shape[1] == 1:
return y_pred.ravel()
return 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 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 |
def iteration_ends(self, time_step):
"""Perform updates to learning rate and potential other states at the
end of an iteration
Parameters
----------
time_step : int
number of training samples trained on so far, used to update
learning rate for 'invscaling... | Perform updates to learning rate and potential other states at the
end of an iteration
Parameters
----------
time_step : int
number of training samples trained on so far, used to update
learning rate for 'invscaling'
| iteration_ends | 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 _get_updates(self, grads):
"""Get the values used to update params with given gradients
Parameters
----------
grads : list, length = len(coefs_) + len(intercepts_)
Containing gradients with respect to coefs_ and intercepts_ in MLP
model. So length should be a... | Get the values used to update params with given gradients
Parameters
----------
grads : list, length = len(coefs_) + len(intercepts_)
Containing gradients with respect to coefs_ and intercepts_ in MLP
model. So length should be aligned with params
Returns
... | _get_updates | 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 _get_updates(self, grads):
"""Get the values used to update params with given gradients
Parameters
----------
grads : list, length = len(coefs_) + len(intercepts_)
Containing gradients with respect to coefs_ and intercepts_ in MLP
model. So length should be a... | Get the values used to update params with given gradients
Parameters
----------
grads : list, length = len(coefs_) + len(intercepts_)
Containing gradients with respect to coefs_ and intercepts_ in MLP
model. So length should be aligned with params
Returns
... | _get_updates | 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 test_poisson_loss(global_random_seed):
"""Test Poisson loss against well tested HalfPoissonLoss."""
n = 1000
rng = np.random.default_rng(global_random_seed)
y_true = rng.integers(low=0, high=10, size=n).astype(float)
y_raw = rng.standard_normal(n)
y_pred = np.exp(y_raw)
sw = rng.uniform(... | Test Poisson loss against well tested HalfPoissonLoss. | test_poisson_loss | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_base.py | BSD-3-Clause |
def test_mlp_loading_from_joblib_partial_fit(tmp_path):
"""Loading from MLP and partial fitting updates weights. Non-regression
test for #19626."""
pre_trained_estimator = MLPRegressor(
hidden_layer_sizes=(42,), random_state=42, learning_rate_init=0.01, max_iter=200
)
features, target = [[2]... | Loading from MLP and partial fitting updates weights. Non-regression
test for #19626. | test_mlp_loading_from_joblib_partial_fit | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def test_preserve_feature_names(Estimator):
"""Check that feature names are preserved when early stopping is enabled.
Feature names are required for consistency checks during scoring.
Non-regression test for gh-24846
"""
pd = pytest.importorskip("pandas")
rng = np.random.RandomState(0)
X ... | Check that feature names are preserved when early stopping is enabled.
Feature names are required for consistency checks during scoring.
Non-regression test for gh-24846
| test_preserve_feature_names | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def test_mlp_warm_start_with_early_stopping(MLPEstimator):
"""Check that early stopping works with warm start."""
mlp = MLPEstimator(
max_iter=10, random_state=0, warm_start=True, early_stopping=True
)
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning)
... | Check that early stopping works with warm start. | test_mlp_warm_start_with_early_stopping | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def test_mlp_warm_start_no_convergence(MLPEstimator, solver):
"""Check that we stop the number of iteration at `max_iter` when warm starting.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/24764
"""
model = MLPEstimator(
solver=solver,
warm_start=True,
... | Check that we stop the number of iteration at `max_iter` when warm starting.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/24764
| test_mlp_warm_start_no_convergence | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def test_mlp_partial_fit_after_fit(MLPEstimator):
"""Check partial fit does not fail after fit when early_stopping=True.
Non-regression test for gh-25693.
"""
mlp = MLPEstimator(early_stopping=True, random_state=0).fit(X_iris, y_iris)
msg = "partial_fit does not support early_stopping=True"
wi... | Check partial fit does not fail after fit when early_stopping=True.
Non-regression test for gh-25693.
| test_mlp_partial_fit_after_fit | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def test_mlp_diverging_loss():
"""Test that a diverging model does not raise errors when early stopping is enabled.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/29504
"""
mlp = MLPRegressor(
hidden_layer_sizes=100,
activation="identity",
solve... | Test that a diverging model does not raise errors when early stopping is enabled.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/29504
| test_mlp_diverging_loss | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def test_mlp_vs_poisson_glm_equivalent(global_random_seed):
"""Test MLP with Poisson loss and no hidden layer equals GLM."""
n = 100
rng = np.random.default_rng(global_random_seed)
X = np.linspace(0, 1, n)
y = rng.poisson(np.exp(X + 1))
X = X.reshape(n, -1)
glm = PoissonRegressor(alpha=0, to... | Test MLP with Poisson loss and no hidden layer equals GLM. | test_mlp_vs_poisson_glm_equivalent | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def test_minimum_input_sample_size():
"""Check error message when the validation set is too small."""
X, y = make_regression(n_samples=2, n_features=5, random_state=0)
model = MLPRegressor(early_stopping=True, random_state=0)
with pytest.raises(ValueError, match="The validation set is too small"):
... | Check error message when the validation set is too small. | test_minimum_input_sample_size | python | scikit-learn/scikit-learn | sklearn/neural_network/tests/test_mlp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neural_network/tests/test_mlp.py | BSD-3-Clause |
def _is_constant_feature(var, mean, n_samples):
"""Detect if a feature is indistinguishable from a constant feature.
The detection is based on its computed variance and on the theoretical
error bounds of the '2 pass algorithm' for variance computation.
See "Algorithms for computing the sample variance... | Detect if a feature is indistinguishable from a constant feature.
The detection is based on its computed variance and on the theoretical
error bounds of the '2 pass algorithm' for variance computation.
See "Algorithms for computing the sample variance: analysis and
recommendations", by Chan, Golub, an... | _is_constant_feature | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def _handle_zeros_in_scale(scale, copy=True, constant_mask=None):
"""Set scales of near constant features to 1.
The goal is to avoid division by very small or zero values.
Near constant features are detected automatically by identifying
scales close to machine precision unless they are precomputed by
... | Set scales of near constant features to 1.
The goal is to avoid division by very small or zero values.
Near constant features are detected automatically by identifying
scales close to machine precision unless they are precomputed by
the caller and passed with the `constant_mask` kwarg.
Typically ... | _handle_zeros_in_scale | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def scale(X, *, axis=0, with_mean=True, with_std=True, copy=True):
"""Standardize a dataset along any axis.
Center to the mean and component wise scale to unit variance.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (... | Standardize a dataset along any axis.
Center to the mean and component wise scale to unit variance.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to center and scale.
axis : {... | scale | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def _reset(self):
"""Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
"""
# Checking one attribute is enough, because they are all set together
# in partial_fit
if hasattr(self, "scale_"):
del self.scale_
... | Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
| _reset | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Compute the minimum and maximum to be used for later scaling.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data used to compute the per-feature minimum and maximum
used for later scaling along the features... | Compute the minimum and maximum to be used for later scaling.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data used to compute the per-feature minimum and maximum
used for later scaling along the features axis.
y : None
... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def partial_fit(self, X, y=None):
"""Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a continuous stream.
... | Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a continuous stream.
Parameters
----------
X ... | partial_fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def transform(self, X):
"""Scale features of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed.
Returns
-------
Xt : ndarray of shape (n_samples, n_features)
... | Scale features of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed.
Returns
-------
Xt : ndarray of shape (n_samples, n_features)
Transformed data.
| transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def inverse_transform(self, X):
"""Undo the scaling of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed. It cannot be sparse.
Returns
-------
X_original : ndarray ... | Undo the scaling of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed. It cannot be sparse.
Returns
-------
X_original : ndarray of shape (n_samples, n_features)
... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def minmax_scale(X, feature_range=(0, 1), *, axis=0, copy=True):
"""Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such
that it is in the given range on the training set, i.e. between
zero and one.
The transformation is g... | Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such
that it is in the given range on the training set, i.e. between
zero and one.
The transformation is given by (when ``axis=0``)::
X_std = (X - X.min(axis=0)) / (X.ma... | minmax_scale | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def _reset(self):
"""Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
"""
# Checking one attribute is enough, because they are all set together
# in partial_fit
if hasattr(self, "scale_"):
del self.scale_
... | Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
| _reset | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def fit(self, X, y=None, sample_weight=None):
"""Compute the mean and std to be used for later scaling.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to compute the mean and standard deviation
used for later ... | Compute the mean and std to be used for later scaling.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
y : None
... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def partial_fit(self, X, y=None, sample_weight=None):
"""Online computation of mean and std on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a co... | Online computation of mean and std on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a continuous stream.
The algorithm for incremental mean and ... | partial_fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def transform(self, X, copy=None):
"""Perform standardization by centering and scaling.
Parameters
----------
X : {array-like, sparse matrix of shape (n_samples, n_features)
The data used to scale along the features axis.
copy : bool, default=None
Copy th... | Perform standardization by centering and scaling.
Parameters
----------
X : {array-like, sparse matrix of shape (n_samples, n_features)
The data used to scale along the features axis.
copy : bool, default=None
Copy the input X or not.
Returns
---... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def inverse_transform(self, X, copy=None):
"""Scale back the data to the original representation.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to scale along the features axis.
copy : bool, default=None
... | Scale back the data to the original representation.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to scale along the features axis.
copy : bool, default=None
Copy the input `X` or not.
Returns
... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def _reset(self):
"""Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
"""
# Checking one attribute is enough, because they are all set together
# in partial_fit
if hasattr(self, "scale_"):
del self.scale_
... | Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
| _reset | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Compute the maximum absolute value to be used for later scaling.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to compute the per-feature minimum and maximum
used for later scalin... | Compute the maximum absolute value to be used for later scaling.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to compute the per-feature minimum and maximum
used for later scaling along the features axis.
y... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def partial_fit(self, X, y=None):
"""Online computation of max absolute value of X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a continuous strea... | Online computation of max absolute value of X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a continuous stream.
Parameters
----------
... | partial_fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def transform(self, X):
"""Scale the data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data that should be scaled.
Returns
-------
X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features)
... | Scale the data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data that should be scaled.
Returns
-------
X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features)
Transformed array.
| transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def inverse_transform(self, X):
"""Scale back the data to the original representation.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data that should be transformed back.
Returns
-------
X_original : {ndar... | Scale back the data to the original representation.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data that should be transformed back.
Returns
-------
X_original : {ndarray, sparse matrix} of shape (n_samples, n_... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def maxabs_scale(X, *, axis=0, copy=True):
"""Scale each feature to the [-1, 1] range without breaking the sparsity.
This estimator scales each feature individually such
that the maximal absolute value of each feature in the
training set will be 1.0.
This scaler can also be applied to sparse CSR o... | Scale each feature to the [-1, 1] range without breaking the sparsity.
This estimator scales each feature individually such
that the maximal absolute value of each feature in the
training set will be 1.0.
This scaler can also be applied to sparse CSR or CSC matrices.
Parameters
----------
... | maxabs_scale | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Compute the median and quantiles to be used for scaling.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to compute the median and quantiles
used for later scaling along the feature... | Compute the median and quantiles to be used for scaling.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to compute the median and quantiles
used for later scaling along the features axis.
y : Ignored
... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def transform(self, X):
"""Center and scale the data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to scale along the specified axis.
Returns
-------
X_tr : {ndarray, sparse matrix} of shape (n_... | Center and scale the data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data used to scale along the specified axis.
Returns
-------
X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features)
Tr... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def inverse_transform(self, X):
"""Scale back the data to the original representation.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The rescaled data to be transformed back.
Returns
-------
X_original : {ndar... | Scale back the data to the original representation.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The rescaled data to be transformed back.
Returns
-------
X_original : {ndarray, sparse matrix} of shape (n_samples, n_... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def robust_scale(
X,
*,
axis=0,
with_centering=True,
with_scaling=True,
quantile_range=(25.0, 75.0),
copy=True,
unit_variance=False,
):
"""Standardize a dataset along any axis.
Center to the median and component wise scale
according to the interquartile range.
Read more... | Standardize a dataset along any axis.
Center to the median and component wise scale
according to the interquartile range.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_sample, n_features)
The data to center... | robust_scale | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def normalize(X, norm="l2", *, axis=1, copy=True, return_norm=False):
"""Scale input vectors individually to unit norm (vector length).
Read more in the :ref:`User Guide <preprocessing_normalization>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
T... | Scale input vectors individually to unit norm (vector length).
Read more in the :ref:`User Guide <preprocessing_normalization>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to normalize, element by element.
scipy.sparse matrices shoul... | normalize | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def transform(self, X, copy=None):
"""Scale each non zero row of X to unit norm.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to normalize, row by row. scipy.sparse matrices should be
in CSR format to avoid an un... | Scale each non zero row of X to unit norm.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to normalize, row by row. scipy.sparse matrices should be
in CSR format to avoid an un-necessary copy.
copy : bool, default... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def binarize(X, *, threshold=0.0, copy=True):
"""Boolean thresholding of array-like or scipy.sparse matrix.
Read more in the :ref:`User Guide <preprocessing_binarization>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to binarize, element ... | Boolean thresholding of array-like or scipy.sparse matrix.
Read more in the :ref:`User Guide <preprocessing_binarization>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to binarize, element by element.
scipy.sparse matrices should be i... | binarize | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def transform(self, X, copy=None):
"""Binarize each element of X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to binarize, element by element.
scipy.sparse matrices should be in CSR format to avoid an
... | Binarize each element of X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to binarize, element by element.
scipy.sparse matrices should be in CSR format to avoid an
un-necessary copy.
copy : bool
... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def fit(self, K, y=None):
"""Fit KernelCenterer.
Parameters
----------
K : ndarray of shape (n_samples, n_samples)
Kernel matrix.
y : None
Ignored.
Returns
-------
self : object
Returns the instance itself.
""... | Fit KernelCenterer.
Parameters
----------
K : ndarray of shape (n_samples, n_samples)
Kernel matrix.
y : None
Ignored.
Returns
-------
self : object
Returns the instance itself.
| fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def transform(self, K, copy=True):
"""Center kernel matrix.
Parameters
----------
K : ndarray of shape (n_samples1, n_samples2)
Kernel matrix.
copy : bool, default=True
Set to False to perform inplace computation.
Returns
-------
... | Center kernel matrix.
Parameters
----------
K : ndarray of shape (n_samples1, n_samples2)
Kernel matrix.
copy : bool, default=True
Set to False to perform inplace computation.
Returns
-------
K_new : ndarray of shape (n_samples1, n_sampl... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.