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 _compute_log_det_cholesky(matrix_chol, covariance_type, n_features):
"""Compute the log-det of the cholesky decomposition of matrices.
Parameters
----------
matrix_chol : array-like
Cholesky decompositions of the matrices.
'full' : shape of (n_components, n_features, n_features)
... | Compute the log-det of the cholesky decomposition of matrices.
Parameters
----------
matrix_chol : array-like
Cholesky decompositions of the matrices.
'full' : shape of (n_components, n_features, n_features)
'tied' : shape of (n_features, n_features)
'diag' : shape of (n_com... | _compute_log_det_cholesky | python | scikit-learn/scikit-learn | sklearn/mixture/_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_gaussian_mixture.py | BSD-3-Clause |
def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type):
"""Estimate the log Gaussian probability.
Parameters
----------
X : array-like of shape (n_samples, n_features)
means : array-like of shape (n_components, n_features)
precisions_chol : array-like
Cholesky dec... | Estimate the log Gaussian probability.
Parameters
----------
X : array-like of shape (n_samples, n_features)
means : array-like of shape (n_components, n_features)
precisions_chol : array-like
Cholesky decompositions of the precision matrices.
'full' : shape of (n_components, n_fe... | _estimate_log_gaussian_prob | python | scikit-learn/scikit-learn | sklearn/mixture/_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_gaussian_mixture.py | BSD-3-Clause |
def _check_parameters(self, X):
"""Check the Gaussian mixture parameters are well defined."""
_, n_features = X.shape
if self.weights_init is not None:
self.weights_init = _check_weights(self.weights_init, self.n_components)
if self.means_init is not None:
self.... | Check the Gaussian mixture parameters are well defined. | _check_parameters | python | scikit-learn/scikit-learn | sklearn/mixture/_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_gaussian_mixture.py | BSD-3-Clause |
def _initialize(self, X, resp):
"""Initialization of the Gaussian mixture parameters.
Parameters
----------
X : array-like of shape (n_samples, n_features)
resp : array-like of shape (n_samples, n_components)
"""
n_samples, _ = X.shape
weights, means, co... | Initialization of the Gaussian mixture parameters.
Parameters
----------
X : array-like of shape (n_samples, n_features)
resp : array-like of shape (n_samples, n_components)
| _initialize | python | scikit-learn/scikit-learn | sklearn/mixture/_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_gaussian_mixture.py | BSD-3-Clause |
def _m_step(self, X, log_resp):
"""M step.
Parameters
----------
X : array-like of shape (n_samples, n_features)
log_resp : array-like of shape (n_samples, n_components)
Logarithm of the posterior probabilities (or responsibilities) of
the point of each ... | M step.
Parameters
----------
X : array-like of shape (n_samples, n_features)
log_resp : array-like of shape (n_samples, n_components)
Logarithm of the posterior probabilities (or responsibilities) of
the point of each sample in X.
| _m_step | python | scikit-learn/scikit-learn | sklearn/mixture/_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_gaussian_mixture.py | BSD-3-Clause |
def _n_parameters(self):
"""Return the number of free parameters in the model."""
_, n_features = self.means_.shape
if self.covariance_type == "full":
cov_params = self.n_components * n_features * (n_features + 1) / 2.0
elif self.covariance_type == "diag":
cov_par... | Return the number of free parameters in the model. | _n_parameters | python | scikit-learn/scikit-learn | sklearn/mixture/_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_gaussian_mixture.py | BSD-3-Clause |
def test_gaussian_mixture_setting_best_params():
"""`GaussianMixture`'s best_parameters, `n_iter_` and `lower_bound_`
must be set appropriately in the case of divergence.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/18216
"""
rnd = np.random.RandomState(0)
n_... | `GaussianMixture`'s best_parameters, `n_iter_` and `lower_bound_`
must be set appropriately in the case of divergence.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/18216
| test_gaussian_mixture_setting_best_params | python | scikit-learn/scikit-learn | sklearn/mixture/tests/test_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/tests/test_gaussian_mixture.py | BSD-3-Clause |
def test_gaussian_mixture_precisions_init_diag(global_dtype):
"""Check that we properly initialize `precision_cholesky_` when we manually
provide the precision matrix.
In this regard, we check the consistency between estimating the precision
matrix and providing the same precision matrix as initializat... | Check that we properly initialize `precision_cholesky_` when we manually
provide the precision matrix.
In this regard, we check the consistency between estimating the precision
matrix and providing the same precision matrix as initialization. It should
lead to the same results with the same number of i... | test_gaussian_mixture_precisions_init_diag | python | scikit-learn/scikit-learn | sklearn/mixture/tests/test_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/tests/test_gaussian_mixture.py | BSD-3-Clause |
def _calculate_precisions(X, resp, covariance_type):
"""Calculate precision matrix of X and its Cholesky decomposition
for the given covariance type.
"""
reg_covar = 1e-6
weights, means, covariances = _estimate_gaussian_parameters(
X, resp, reg_covar, covariance_type
)
precisions_cho... | Calculate precision matrix of X and its Cholesky decomposition
for the given covariance type.
| _calculate_precisions | python | scikit-learn/scikit-learn | sklearn/mixture/tests/test_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/tests/test_gaussian_mixture.py | BSD-3-Clause |
def test_gaussian_mixture_single_component_stable():
"""
Non-regression test for #23032 ensuring 1-component GM works on only a
few samples.
"""
rng = np.random.RandomState(0)
X = rng.multivariate_normal(np.zeros(2), np.identity(2), size=3)
gm = GaussianMixture(n_components=1)
gm.fit(X).... |
Non-regression test for #23032 ensuring 1-component GM works on only a
few samples.
| test_gaussian_mixture_single_component_stable | python | scikit-learn/scikit-learn | sklearn/mixture/tests/test_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/tests/test_gaussian_mixture.py | BSD-3-Clause |
def test_gaussian_mixture_all_init_does_not_estimate_gaussian_parameters(
monkeypatch,
global_random_seed,
):
"""When all init parameters are provided, the Gaussian parameters
are not estimated.
Non-regression test for gh-26015.
"""
mock = Mock(side_effect=_estimate_gaussian_parameters)
... | When all init parameters are provided, the Gaussian parameters
are not estimated.
Non-regression test for gh-26015.
| test_gaussian_mixture_all_init_does_not_estimate_gaussian_parameters | python | scikit-learn/scikit-learn | sklearn/mixture/tests/test_gaussian_mixture.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/tests/test_gaussian_mixture.py | BSD-3-Clause |
def fit(self, X, y, **params):
"""Fit the classifier.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
**params : dict
Parameter... | Fit the classifier.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
**params : dict
Parameters to pass to the `fit` method of the under... | fit | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def predict_proba(self, X):
"""Predict class probabilities for `X` using the fitted estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is ... | Predict class probabilities for `X` using the fitted estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of features.
Return... | predict_proba | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def predict_log_proba(self, X):
"""Predict logarithm class probabilities for `X` using the fitted estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n... | Predict logarithm class probabilities for `X` using the fitted estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of features.
... | predict_log_proba | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def decision_function(self, X):
"""Decision function for samples in `X` using the fitted estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features... | Decision function for samples in `X` using the fitted estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of features.
Retur... | decision_function | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def _fit(self, X, y, **params):
"""Fit the classifier.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
**params : dict
Paramete... | Fit the classifier.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
**params : dict
Parameters to pass to the `fit` method of the under... | _fit | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def predict(self, X):
"""Predict the target of new samples.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The samples, as accepted by `estimator.predict`.
Returns
-------
class_labels : ndarray of shape (n_sam... | Predict the target of new samples.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The samples, as accepted by `estimator.predict`.
Returns
-------
class_labels : ndarray of shape (n_samples,)
The predicted ... | predict | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` e... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
routing informatio... | get_metadata_routing | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def _fit_and_score_over_thresholds(
classifier,
X,
y,
*,
fit_params,
train_idx,
val_idx,
curve_scorer,
score_params,
):
"""Fit a classifier and compute the scores for different decision thresholds.
Parameters
----------
classifier : estimator instance
The cla... | Fit a classifier and compute the scores for different decision thresholds.
Parameters
----------
classifier : estimator instance
The classifier to fit and use for scoring. If `classifier` is already fitted,
it will be used as is.
X : {array-like, sparse matrix} of shape (n_samples, n_f... | _fit_and_score_over_thresholds | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def _mean_interpolated_score(target_thresholds, cv_thresholds, cv_scores):
"""Compute the mean interpolated score across folds by defining common thresholds.
Parameters
----------
target_thresholds : ndarray of shape (thresholds,)
The thresholds to use to compute the mean score.
cv_thresho... | Compute the mean interpolated score across folds by defining common thresholds.
Parameters
----------
target_thresholds : ndarray of shape (thresholds,)
The thresholds to use to compute the mean score.
cv_thresholds : ndarray of shape (n_folds, thresholds_fold)
The thresholds used to c... | _mean_interpolated_score | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def _fit(self, X, y, **params):
"""Fit the classifier and post-tune the decision threshold.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
... | Fit the classifier and post-tune the decision threshold.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
**params : dict
Parameters to ... | _fit | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def predict(self, X):
"""Predict the target of new samples.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The samples, as accepted by `estimator.predict`.
Returns
-------
class_labels : ndarray of shape (n_sam... | Predict the target of new samples.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The samples, as accepted by `estimator.predict`.
Returns
-------
class_labels : ndarray of shape (n_samples,)
The predicted ... | predict | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` e... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
routing informatio... | get_metadata_routing | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def _get_curve_scorer(self):
"""Get the curve scorer based on the objective metric used."""
scoring = check_scoring(self.estimator, scoring=self.scoring)
curve_scorer = _CurveScorer.from_scorer(
scoring, self._get_response_method(), self.thresholds
)
return curve_scor... | Get the curve scorer based on the objective metric used. | _get_curve_scorer | python | scikit-learn/scikit-learn | sklearn/model_selection/_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_classification_threshold.py | BSD-3-Clause |
def plot(
self,
ax=None,
*,
negate_score=False,
score_name=None,
score_type="both",
std_display_style="fill_between",
line_kw=None,
fill_between_kw=None,
errorbar_kw=None,
):
"""Plot visualization.
Parameters
--... | Plot visualization.
Parameters
----------
ax : matplotlib Axes, default=None
Axes object to plot on. If `None`, a new figure and axes is
created.
negate_score : bool, default=False
Whether or not to negate the scores obtained through
:fun... | plot | python | scikit-learn/scikit-learn | sklearn/model_selection/_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_plot.py | BSD-3-Clause |
def from_estimator(
cls,
estimator,
X,
y,
*,
groups=None,
train_sizes=np.linspace(0.1, 1.0, 5),
cv=None,
scoring=None,
exploit_incremental_learning=False,
n_jobs=None,
pre_dispatch="all",
verbose=0,
shuffle=F... | Create a learning curve display from an estimator.
Read more in the :ref:`User Guide <visualizations>` for general
information about the visualization API and :ref:`detailed
documentation <learning_curve>` regarding the learning curve
visualization.
Parameters
---------... | from_estimator | python | scikit-learn/scikit-learn | sklearn/model_selection/_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_plot.py | BSD-3-Clause |
def plot(
self,
ax=None,
*,
negate_score=False,
score_name=None,
score_type="both",
std_display_style="fill_between",
line_kw=None,
fill_between_kw=None,
errorbar_kw=None,
):
"""Plot visualization.
Parameters
--... | Plot visualization.
Parameters
----------
ax : matplotlib Axes, default=None
Axes object to plot on. If `None`, a new figure and axes is
created.
negate_score : bool, default=False
Whether or not to negate the scores obtained through
:fun... | plot | python | scikit-learn/scikit-learn | sklearn/model_selection/_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_plot.py | BSD-3-Clause |
def from_estimator(
cls,
estimator,
X,
y,
*,
param_name,
param_range,
groups=None,
cv=None,
scoring=None,
n_jobs=None,
pre_dispatch="all",
verbose=0,
error_score=np.nan,
fit_params=None,
ax=No... | Create a validation curve display from an estimator.
Read more in the :ref:`User Guide <visualizations>` for general
information about the visualization API and :ref:`detailed
documentation <validation_curve>` regarding the validation curve
visualization.
Parameters
---... | from_estimator | python | scikit-learn/scikit-learn | sklearn/model_selection/_plot.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_plot.py | BSD-3-Clause |
def __iter__(self):
"""Iterate over the points in the grid.
Returns
-------
params : iterator over dict of str to any
Yields dictionaries mapping each estimator parameter to one of its
allowed values.
"""
for p in self.param_grid:
# Al... | Iterate over the points in the grid.
Returns
-------
params : iterator over dict of str to any
Yields dictionaries mapping each estimator parameter to one of its
allowed values.
| __iter__ | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def __len__(self):
"""Number of points on the grid."""
# Product function that can handle iterables (np.prod can't).
product = partial(reduce, operator.mul)
return sum(
product(len(v) for v in p.values()) if p else 1 for p in self.param_grid
) | Number of points on the grid. | __len__ | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def __getitem__(self, ind):
"""Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of str to any
Equal to list(self)[ind]
"""
# This is ... | Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of str to any
Equal to list(self)[ind]
| __getitem__ | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def __len__(self):
"""Number of points that will be sampled."""
if self._is_all_lists():
grid_size = len(ParameterGrid(self.param_distributions))
return min(self.n_iter, grid_size)
else:
return self.n_iter | Number of points that will be sampled. | __len__ | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _search_estimator_has(attr):
"""Check if we can delegate a method to the underlying estimator.
Calling a prediction method will only be available if `refit=True`. In
such case, we check first the fitted best estimator. If it is not
fitted, we check the unfitted estimator.
Checking the unfitted... | Check if we can delegate a method to the underlying estimator.
Calling a prediction method will only be available if `refit=True`. In
such case, we check first the fitted best estimator. If it is not
fitted, we check the unfitted estimator.
Checking the unfitted estimator allows to use `hasattr` on th... | _search_estimator_has | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _yield_masked_array_for_each_param(candidate_params):
"""
Yield a masked array for each candidate param.
`candidate_params` is a sequence of params which were used in
a `GridSearchCV`. We use masked arrays for the results, as not
all params are necessarily present in each element of
`candid... |
Yield a masked array for each candidate param.
`candidate_params` is a sequence of params which were used in
a `GridSearchCV`. We use masked arrays for the results, as not
all params are necessarily present in each element of
`candidate_params`. For example, if using `GridSearchCV` with
a `SVC... | _yield_masked_array_for_each_param | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def score(self, X, y=None, **params):
"""Return the score on the given data, if the estimator has been refit.
This uses the score defined by ``scoring`` where provided, and the
``best_estimator_.score`` method otherwise.
Parameters
----------
X : array-like of shape (n_... | Return the score on the given data, if the estimator has been refit.
This uses the score defined by ``scoring`` where provided, and the
``best_estimator_.score`` method otherwise.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data, wher... | score | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def n_features_in_(self):
"""Number of features seen during :term:`fit`.
Only available when `refit=True`.
"""
# For consistency with other estimators we raise a AttributeError so
# that hasattr() fails if the search estimator isn't fitted.
try:
check_is_fitt... | Number of features seen during :term:`fit`.
Only available when `refit=True`.
| n_features_in_ | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _check_refit_for_multimetric(self, scores):
"""Check `refit` is compatible with `scores` is valid"""
multimetric_refit_msg = (
"For multi-metric scoring, the parameter refit must be set to a "
"scorer key or a callable to refit an estimator with the best "
"parame... | Check `refit` is compatible with `scores` is valid | _check_refit_for_multimetric | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _select_best_index(refit, refit_metric, results):
"""Select index of the best combination of hyperparemeters."""
if callable(refit):
# If callable, refit is expected to return the index of the best
# parameter set.
best_index = refit(results)
if not is... | Select index of the best combination of hyperparemeters. | _select_best_index | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _get_scorers(self):
"""Get the scorer(s) to be used.
This is used in ``fit`` and ``get_metadata_routing``.
Returns
-------
scorers, refit_metric
"""
refit_metric = "score"
if callable(self.scoring):
scorers = self.scoring
elif se... | Get the scorer(s) to be used.
This is used in ``fit`` and ``get_metadata_routing``.
Returns
-------
scorers, refit_metric
| _get_scorers | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _get_routed_params_for_fit(self, params):
"""Get the parameters to be used for routing.
This is a method instead of a snippet in ``fit`` since it's used twice,
here in ``fit``, and in ``HalvingRandomSearchCV.fit``.
"""
if _routing_enabled():
routed_params = proce... | Get the parameters to be used for routing.
This is a method instead of a snippet in ``fit`` since it's used twice,
here in ``fit``, and in ``HalvingRandomSearchCV.fit``.
| _get_routed_params_for_fit | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def fit(self, X, y=None, **params):
"""Run fit with all sets of parameters.
Parameters
----------
X : array-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the numbe... | Run fit with all sets of parameters.
Parameters
----------
X : array-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of features. For precomputed kernel or
... | fit | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _store(key_name, array, weights=None, splits=False, rank=False):
"""A small helper to store the scores/times to the cv_results_"""
# When iterated first by splits, then by parameters
# We want `array` to have `n_candidates` rows and `n_splits` cols.
array = np.array(a... | A small helper to store the scores/times to the cv_results_ | _store | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.4
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.met... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.4
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating... | get_metadata_routing | python | scikit-learn/scikit-learn | sklearn/model_selection/_search.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search.py | BSD-3-Clause |
def _select_best_index(refit, refit_metric, results):
"""Custom refit callable to return the index of the best candidate.
We want the best candidate out of the last iteration. By default
BaseSearchCV would return the best candidate out of all iterations.
Currently, we only support for ... | Custom refit callable to return the index of the best candidate.
We want the best candidate out of the last iteration. By default
BaseSearchCV would return the best candidate out of all iterations.
Currently, we only support for a single metric thus `refit` and
`refit_metric` are not r... | _select_best_index | python | scikit-learn/scikit-learn | sklearn/model_selection/_search_successive_halving.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search_successive_halving.py | BSD-3-Clause |
def fit(self, X, y=None, **params):
"""Run fit with all sets of parameters.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features` is the number of features.
y : a... | Run fit with all sets of parameters.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples and
`n_features` is the number of features.
y : array-like, shape (n_samples,) or (n_samples, n_... | fit | python | scikit-learn/scikit-learn | sklearn/model_selection/_search_successive_halving.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_search_successive_halving.py | BSD-3-Clause |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number o... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : array-like of shape (n_samp... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number o... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : array-like of shape (n_samp... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def _iter_test_masks(self, X=None, y=None, groups=None):
"""Generates boolean masks corresponding to test sets.
By default, delegates to _iter_test_indices(X, y, groups)
"""
for test_index in self._iter_test_indices(X, y, groups):
test_mask = np.zeros(_num_samples(X), dtype=... | Generates boolean masks corresponding to test sets.
By default, delegates to _iter_test_indices(X, y, groups)
| _iter_test_masks | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def get_n_splits(self, X, y=None, groups=None):
"""Returns the number of splitting iterations in the cross-validator.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` ... | Returns the number of splitting iterations in the cross-validator.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : object
... | get_n_splits | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def get_n_splits(self, X, y=None, groups=None):
"""Returns the number of splitting iterations in the cross-validator.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` ... | Returns the number of splitting iterations in the cross-validator.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : object
... | get_n_splits | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number o... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : array-like of shape (n_samp... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of fea... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
Note that providing ``y`` i... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number o... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : array-like of shape (n_samp... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def _split(self, X):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
Yields
------
t... | _split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y=None, groups=None):
"""Generates indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number ... | Generates indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : array-like of shape (n_sam... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def get_n_splits(self, X=None, y=None, groups=None):
"""Returns the number of splitting iterations in the cross-validator.
Parameters
----------
X : object
Always ignored, exists for compatibility.
``np.zeros(n_samples)`` may be used as a placeholder.
y ... | Returns the number of splitting iterations in the cross-validator.
Parameters
----------
X : object
Always ignored, exists for compatibility.
``np.zeros(n_samples)`` may be used as a placeholder.
y : object
Always ignored, exists for compatibility.
... | get_n_splits | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of fea... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
Note that providing ``y`` i... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number o... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : array-like of shape (n_samp... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X, y, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of fea... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
Note that providing ``y`` i... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def _validate_shuffle_split(n_samples, test_size, train_size, default_test_size=None):
"""
Validation helper to check if the train/test sizes are meaningful w.r.t. the
size of the data (n_samples).
"""
if test_size is None and train_size is None:
test_size = default_test_size
test_size_... |
Validation helper to check if the train/test sizes are meaningful w.r.t. the
size of the data (n_samples).
| _validate_shuffle_split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X=None, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
groups : ... | Generate indices to split data into training and test set.
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
groups : object
Always ignored, exists for compatibili... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def _split(self):
"""Generate indices to split data into training and test set.
Yields
------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
ind = np.arange(len(self.tes... | Generate indices to split data into training and test set.
Yields
------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
| _split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def _iter_test_masks(self):
"""Generates boolean masks corresponding to test sets."""
for f in self.unique_folds:
test_index = np.where(self.test_fold == f)[0]
test_mask = np.zeros(len(self.test_fold), dtype=bool)
test_mask[test_index] = True
yield test_ma... | Generates boolean masks corresponding to test sets. | _iter_test_masks | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def split(self, X=None, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
groups : ... | Generate indices to split data into training and test set.
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
groups : object
Always ignored, exists for compatibili... | split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def check_cv(cv=5, y=None, *, classifier=False):
"""Input checker utility for building a cross-validator.
Parameters
----------
cv : int, cross-validation generator, iterable or None, default=5
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- Non... | Input checker utility for building a cross-validator.
Parameters
----------
cv : int, cross-validation generator, iterable or None, default=5
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 5-fold cross validation,
-... | check_cv | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def train_test_split(
*arrays,
test_size=None,
train_size=None,
random_state=None,
shuffle=True,
stratify=None,
):
"""Split arrays or matrices into random train and test subsets.
Quick utility that wraps input validation,
``next(ShuffleSplit().split(X, y))``, and application to inpu... | Split arrays or matrices into random train and test subsets.
Quick utility that wraps input validation,
``next(ShuffleSplit().split(X, y))``, and application to input data
into a single call for splitting (and optionally subsampling) data into a
one-liner.
Read more in the :ref:`User Guide <cross_... | train_test_split | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def _pprint(params, offset=0, printer=repr):
"""Pretty print the dictionary 'params'
Parameters
----------
params : dict
The dictionary to pretty print
offset : int, default=0
The offset in characters to add at the begin of each line.
printer : callable, default=repr
T... | Pretty print the dictionary 'params'
Parameters
----------
params : dict
The dictionary to pretty print
offset : int, default=0
The offset in characters to add at the begin of each line.
printer : callable, default=repr
The function to convert entries to strings, typically... | _pprint | python | scikit-learn/scikit-learn | sklearn/model_selection/_split.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_split.py | BSD-3-Clause |
def _check_params_groups_deprecation(fit_params, params, groups, version):
"""A helper function to check deprecations on `groups` and `fit_params`.
# TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not
# possible.
"""
if params is not None and fit_params is not None:
... | A helper function to check deprecations on `groups` and `fit_params`.
# TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not
# possible.
| _check_params_groups_deprecation | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def cross_validate(
estimator,
X,
y=None,
*,
groups=None,
scoring=None,
cv=None,
n_jobs=None,
verbose=0,
params=None,
pre_dispatch="2*n_jobs",
return_train_score=False,
return_estimator=False,
return_indices=False,
error_score=np.nan,
):
"""Evaluate metric... | Evaluate metric(s) by cross-validation and also record fit/score times.
Read more in the :ref:`User Guide <multimetric_cross_validation>`.
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : {array-like, sparse matrix} of shape (n_s... | cross_validate | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _insert_error_scores(results, error_score):
"""Insert error in `results` by replacing them inplace with `error_score`.
This only applies to multimetric scores because `_fit_and_score` will
handle the single metric case.
"""
successful_score = None
failed_indices = []
for i, result in en... | Insert error in `results` by replacing them inplace with `error_score`.
This only applies to multimetric scores because `_fit_and_score` will
handle the single metric case.
| _insert_error_scores | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _normalize_score_results(scores, scaler_score_key="score"):
"""Creates a scoring dictionary based on the type of `scores`"""
if isinstance(scores[0], dict):
# multimetric scoring
return _aggregate_score_dicts(scores)
# scaler
return {scaler_score_key: scores} | Creates a scoring dictionary based on the type of `scores` | _normalize_score_results | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _fit_and_score(
estimator,
X,
y,
*,
scorer,
train,
test,
verbose,
parameters,
fit_params,
score_params,
return_train_score=False,
return_parameters=False,
return_n_test_samples=False,
return_times=False,
return_estimator=False,
split_progress=None,... | Fit estimator and compute scores for a given dataset split.
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : array-like of shape (n_samples, n_features)
The data to fit.
y : array-like of shape (n_samples,) or (n_samples,... | _fit_and_score | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _score(estimator, X_test, y_test, scorer, score_params, error_score="raise"):
"""Compute the score(s) of an estimator on a given test set.
Will return a dict of floats if `scorer` is a _MultiMetricScorer, otherwise a single
float is returned.
"""
score_params = {} if score_params is None else s... | Compute the score(s) of an estimator on a given test set.
Will return a dict of floats if `scorer` is a _MultiMetricScorer, otherwise a single
float is returned.
| _score | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def cross_val_predict(
estimator,
X,
y=None,
*,
groups=None,
cv=None,
n_jobs=None,
verbose=0,
params=None,
pre_dispatch="2*n_jobs",
method="predict",
):
"""Generate cross-validated estimates for each input data point.
The data is split according to the cv parameter. ... | Generate cross-validated estimates for each input data point.
The data is split according to the cv parameter. Each sample belongs
to exactly one test set, and its prediction is computed with an
estimator fitted on the corresponding training set.
Passing these predictions into an evaluation metric may... | cross_val_predict | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _fit_and_predict(estimator, X, y, train, test, fit_params, method):
"""Fit estimator and predict values for a given dataset split.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
estimator : estimator object implementing 'fit' and 'predict'
The object to us... | Fit estimator and predict values for a given dataset split.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
estimator : estimator object implementing 'fit' and 'predict'
The object to use to fit the data.
X : array-like of shape (n_samples, n_features)
... | _fit_and_predict | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _enforce_prediction_order(classes, predictions, n_classes, method):
"""Ensure that prediction arrays have correct column order
When doing cross-validation, if one or more classes are
not present in the subset of data used for training,
then the output prediction array might not have the same
co... | Ensure that prediction arrays have correct column order
When doing cross-validation, if one or more classes are
not present in the subset of data used for training,
then the output prediction array might not have the same
columns as other folds. Use the list of class names
(assumed to be ints) to e... | _enforce_prediction_order | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _check_is_permutation(indices, n_samples):
"""Check whether indices is a reordering of the array np.arange(n_samples)
Parameters
----------
indices : ndarray
int array to test
n_samples : int
number of expected elements
Returns
-------
is_partition : bool
Tr... | Check whether indices is a reordering of the array np.arange(n_samples)
Parameters
----------
indices : ndarray
int array to test
n_samples : int
number of expected elements
Returns
-------
is_partition : bool
True iff sorted(indices) is np.arange(n)
| _check_is_permutation | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def permutation_test_score(
estimator,
X,
y,
*,
groups=None,
cv=None,
n_permutations=100,
n_jobs=None,
random_state=0,
verbose=0,
scoring=None,
fit_params=None,
params=None,
):
"""Evaluate the significance of a cross-validated score with permutations.
Permute... | Evaluate the significance of a cross-validated score with permutations.
Permutes targets to generate 'randomized data' and compute the empirical
p-value against the null hypothesis that features and targets are
independent.
The p-value represents the fraction of randomized data sets where the
esti... | permutation_test_score | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _shuffle(y, groups, random_state):
"""Return a shuffled copy of y eventually shuffle among same groups."""
if groups is None:
indices = random_state.permutation(len(y))
else:
indices = np.arange(len(groups))
for group in np.unique(groups):
this_mask = groups == group
... | Return a shuffled copy of y eventually shuffle among same groups. | _shuffle | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def learning_curve(
estimator,
X,
y,
*,
groups=None,
train_sizes=np.linspace(0.1, 1.0, 5),
cv=None,
scoring=None,
exploit_incremental_learning=False,
n_jobs=None,
pre_dispatch="all",
verbose=0,
shuffle=False,
random_state=None,
error_score=np.nan,
return_t... | Learning curve.
Determines cross-validated training and test scores for different training
set sizes.
A cross-validation generator splits the whole dataset k times in training
and test data. Subsets of the training set with varying sizes will be used
to train the estimator and a score for each tra... | learning_curve | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _translate_train_sizes(train_sizes, n_max_training_samples):
"""Determine absolute sizes of training subsets and validate 'train_sizes'.
Examples:
_translate_train_sizes([0.5, 1.0], 10) -> [5, 10]
_translate_train_sizes([5, 10], 10) -> [5, 10]
Parameters
----------
train_sizes ... | Determine absolute sizes of training subsets and validate 'train_sizes'.
Examples:
_translate_train_sizes([0.5, 1.0], 10) -> [5, 10]
_translate_train_sizes([5, 10], 10) -> [5, 10]
Parameters
----------
train_sizes : array-like of shape (n_ticks,)
Numbers of training examples th... | _translate_train_sizes | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _incremental_fit_estimator(
estimator,
X,
y,
classes,
train,
test,
train_sizes,
scorer,
return_times,
error_score,
fit_params,
score_params,
):
"""Train estimator on training subsets incrementally and compute scores."""
train_scores, test_scores, fit_times, sc... | Train estimator on training subsets incrementally and compute scores. | _incremental_fit_estimator | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def validation_curve(
estimator,
X,
y,
*,
param_name,
param_range,
groups=None,
cv=None,
scoring=None,
n_jobs=None,
pre_dispatch="all",
verbose=0,
error_score=np.nan,
fit_params=None,
params=None,
):
"""Validation curve.
Determine training and test sc... | Validation curve.
Determine training and test scores for varying parameter values.
Compute scores for an estimator with different values of a specified
parameter. This is similar to grid search with one parameter. However, this
will also compute training scores and is merely a utility for plotting the... | validation_curve | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def _aggregate_score_dicts(scores):
"""Aggregate the list of dict to dict of np ndarray
The aggregated output of _aggregate_score_dicts will be a list of dict
of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...]
Convert it to a dict of array {'prec': np.array([0.1 ...]), ...}
Paramete... | Aggregate the list of dict to dict of np ndarray
The aggregated output of _aggregate_score_dicts will be a list of dict
of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...]
Convert it to a dict of array {'prec': np.array([0.1 ...]), ...}
Parameters
----------
scores : list of dic... | _aggregate_score_dicts | python | scikit-learn/scikit-learn | sklearn/model_selection/_validation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/_validation.py | BSD-3-Clause |
def test_fit_and_score_over_thresholds_curve_scorers():
"""Check that `_fit_and_score_over_thresholds` returns thresholds in ascending order
for the different accepted curve scorers."""
X, y = make_classification(n_samples=100, random_state=0)
train_idx, val_idx = np.arange(50), np.arange(50, 100)
c... | Check that `_fit_and_score_over_thresholds` returns thresholds in ascending order
for the different accepted curve scorers. | test_fit_and_score_over_thresholds_curve_scorers | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fit_and_score_over_thresholds_prefit():
"""Check the behaviour with a prefit classifier."""
X, y = make_classification(n_samples=100, random_state=0)
# `train_idx is None` to indicate that the classifier is prefit
train_idx, val_idx = None, np.arange(50, 100)
classifier = DecisionTreeClass... | Check the behaviour with a prefit classifier. | test_fit_and_score_over_thresholds_prefit | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fit_and_score_over_thresholds_sample_weight():
"""Check that we dispatch the sample-weight to fit and score the classifier."""
X, y = load_iris(return_X_y=True)
X, y = X[:100], y[:100] # only 2 classes
# create a dataset and repeat twice the sample of class #0
X_repeated, y_repeated = np.... | Check that we dispatch the sample-weight to fit and score the classifier. | test_fit_and_score_over_thresholds_sample_weight | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_fit_and_score_over_thresholds_fit_params(fit_params_type):
"""Check that we pass `fit_params` to the classifier when calling `fit`."""
X, y = make_classification(n_samples=100, random_state=0)
fit_params = {
"a": _convert_container(y, fit_params_type),
"b": _convert_container(y, fit... | Check that we pass `fit_params` to the classifier when calling `fit`. | test_fit_and_score_over_thresholds_fit_params | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_no_binary(data):
"""Check that we raise an informative error message for non-binary problem."""
err_msg = "Only binary classification is supported."
with pytest.raises(ValueError, match=err_msg):
TunedThresholdClassifierCV(LogisticRegression()).fit(*data) | Check that we raise an informative error message for non-binary problem. | test_tuned_threshold_classifier_no_binary | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_conflict_cv_refit(params, err_type, err_msg):
"""Check that we raise an informative error message when `cv` and `refit`
cannot be used together.
"""
X, y = make_classification(n_samples=100, random_state=0)
with pytest.raises(err_type, match=err_msg):
Tune... | Check that we raise an informative error message when `cv` and `refit`
cannot be used together.
| test_tuned_threshold_classifier_conflict_cv_refit | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_threshold_classifier_estimator_response_methods(
ThresholdClassifier, estimator, response_method
):
"""Check that `TunedThresholdClassifierCV` exposes the same response methods as the
underlying estimator.
"""
X, y = make_classification(n_samples=100, random_state=0)
model = ThresholdC... | Check that `TunedThresholdClassifierCV` exposes the same response methods as the
underlying estimator.
| test_threshold_classifier_estimator_response_methods | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_without_constraint_value(response_method):
"""Check that `TunedThresholdClassifierCV` is optimizing a given objective
metric."""
X, y = load_breast_cancer(return_X_y=True)
# remove feature to degrade performances
X = X[:, :5]
# make the problem completely imb... | Check that `TunedThresholdClassifierCV` is optimizing a given objective
metric. | test_tuned_threshold_classifier_without_constraint_value | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_metric_with_parameter():
"""Check that we can pass a metric with a parameter in addition check that
`f_beta` with `beta=1` is equivalent to `f1` and different from `f_beta` with
`beta=2`.
"""
X, y = load_breast_cancer(return_X_y=True)
lr = make_pipeline(Standa... | Check that we can pass a metric with a parameter in addition check that
`f_beta` with `beta=1` is equivalent to `f1` and different from `f_beta` with
`beta=2`.
| test_tuned_threshold_classifier_metric_with_parameter | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_with_string_targets(response_method, metric):
"""Check that targets represented by str are properly managed.
Also, check with several metrics to be sure that `pos_label` is properly
dispatched.
"""
X, y = load_breast_cancer(return_X_y=True)
# Encode numeric ta... | Check that targets represented by str are properly managed.
Also, check with several metrics to be sure that `pos_label` is properly
dispatched.
| test_tuned_threshold_classifier_with_string_targets | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_refit(with_sample_weight, global_random_seed):
"""Check the behaviour of the `refit` parameter."""
rng = np.random.RandomState(global_random_seed)
X, y = make_classification(n_samples=100, random_state=0)
if with_sample_weight:
sample_weight = rng.randn(X.shap... | Check the behaviour of the `refit` parameter. | test_tuned_threshold_classifier_refit | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_fit_params(fit_params_type):
"""Check that we pass `fit_params` to the classifier when calling `fit`."""
X, y = make_classification(n_samples=100, random_state=0)
fit_params = {
"a": _convert_container(y, fit_params_type),
"b": _convert_container(y, fit_pa... | Check that we pass `fit_params` to the classifier when calling `fit`. | test_tuned_threshold_classifier_fit_params | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_cv_zeros_sample_weights_equivalence():
"""Check that passing removing some sample from the dataset `X` is
equivalent to passing a `sample_weight` with a factor 0."""
X, y = load_iris(return_X_y=True)
# Scale the data to avoid any convergence issue
X = StandardScal... | Check that passing removing some sample from the dataset `X` is
equivalent to passing a `sample_weight` with a factor 0. | test_tuned_threshold_classifier_cv_zeros_sample_weights_equivalence | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_thresholds_array():
"""Check that we can pass an array to `thresholds` and it is used as candidate
threshold internally."""
X, y = make_classification(random_state=0)
estimator = LogisticRegression()
thresholds = np.linspace(0, 1, 11)
tuned_model = TunedThresh... | Check that we can pass an array to `thresholds` and it is used as candidate
threshold internally. | test_tuned_threshold_classifier_thresholds_array | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_store_cv_results(store_cv_results):
"""Check that if `cv_results_` exists depending on `store_cv_results`."""
X, y = make_classification(random_state=0)
estimator = LogisticRegression()
tuned_model = TunedThresholdClassifierCV(
estimator, store_cv_results=stor... | Check that if `cv_results_` exists depending on `store_cv_results`. | test_tuned_threshold_classifier_store_cv_results | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.py | BSD-3-Clause |
def test_tuned_threshold_classifier_cv_float():
"""Check the behaviour when `cv` is set to a float."""
X, y = make_classification(random_state=0)
# case where `refit=False` and cv is a float: the underlying estimator will be fit
# on the training set given by a ShuffleSplit. We check that we get the sa... | Check the behaviour when `cv` is set to a float. | test_tuned_threshold_classifier_cv_float | python | scikit-learn/scikit-learn | sklearn/model_selection/tests/test_classification_threshold.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/model_selection/tests/test_classification_threshold.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.