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 fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
... | Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
coef_init : ndarray of shape (n_features,), default=N... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_stochastic_gradient.py | BSD-3-Clause |
def _decision_function(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
ndarray of shape (n_samples,)
Predicted target values per element in X.
"""... | Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
ndarray of shape (n_samples,)
Predicted target values per element in X.
| _decision_function | python | scikit-learn/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_stochastic_gradient.py | BSD-3-Clause |
def _fit_one_class(self, X, alpha, C, sample_weight, learning_rate, max_iter):
"""Uses SGD implementation with X and y=np.ones(n_samples)."""
# The One-Class SVM uses the SGD implementation with
# y=np.ones(n_samples).
n_samples = X.shape[0]
y = np.ones(n_samples, dtype=X.dtype,... | Uses SGD implementation with X and y=np.ones(n_samples). | _fit_one_class | python | scikit-learn/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_stochastic_gradient.py | BSD-3-Clause |
def partial_fit(self, X, y=None, sample_weight=None):
"""Fit linear One-Class SVM with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Subset of the training data.
y : Ignored
Not used, pre... | Fit linear One-Class SVM with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Subset of the training data.
y : Ignored
Not used, present for API consistency by convention.
sample_weight : ... | partial_fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_stochastic_gradient.py | BSD-3-Clause |
def fit(self, X, y=None, coef_init=None, offset_init=None, sample_weight=None):
"""Fit linear One-Class SVM with Stochastic Gradient Descent.
This solves an equivalent optimization problem of the
One-Class SVM primal optimization problem and returns a weight vector
w and an offset rho s... | Fit linear One-Class SVM with Stochastic Gradient Descent.
This solves an equivalent optimization problem of the
One-Class SVM primal optimization problem and returns a weight vector
w and an offset rho such that the decision function is given by
<w, x> - rho.
Parameters
... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_stochastic_gradient.py | BSD-3-Clause |
def decision_function(self, X):
"""Signed distance to the separating hyperplane.
Signed distance is positive for an inlier and negative for an
outlier.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Testing data.
... | Signed distance to the separating hyperplane.
Signed distance is positive for an inlier and negative for an
outlier.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Testing data.
Returns
-------
dec : arr... | decision_function | python | scikit-learn/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_stochastic_gradient.py | BSD-3-Clause |
def predict(self, X):
"""Return labels (1 inlier, -1 outlier) of the samples.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Testing data.
Returns
-------
y : array, shape (n_samples,)
Labels of the s... | Return labels (1 inlier, -1 outlier) of the samples.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Testing data.
Returns
-------
y : array, shape (n_samples,)
Labels of the samples.
| predict | python | scikit-learn/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_stochastic_gradient.py | BSD-3-Clause |
def _breakdown_point(n_samples, n_subsamples):
"""Approximation of the breakdown point.
Parameters
----------
n_samples : int
Number of samples.
n_subsamples : int
Number of subsamples to consider.
Returns
-------
breakdown_point : float
Approximation of breakd... | Approximation of the breakdown point.
Parameters
----------
n_samples : int
Number of samples.
n_subsamples : int
Number of subsamples to consider.
Returns
-------
breakdown_point : float
Approximation of breakdown point.
| _breakdown_point | python | scikit-learn/scikit-learn | sklearn/linear_model/_theil_sen.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_theil_sen.py | BSD-3-Clause |
def _lstsq(X, y, indices, fit_intercept):
"""Least Squares Estimator for TheilSenRegressor class.
This function calculates the least squares method on a subset of rows of X
and y defined by the indices array. Optionally, an intercept column is
added if intercept is set to true.
Parameters
----... | Least Squares Estimator for TheilSenRegressor class.
This function calculates the least squares method on a subset of rows of X
and y defined by the indices array. Optionally, an intercept column is
added if intercept is set to true.
Parameters
----------
X : array-like of shape (n_samples, n_... | _lstsq | python | scikit-learn/scikit-learn | sklearn/linear_model/_theil_sen.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_theil_sen.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit linear model.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
Returns
-------
self : returns an instance of self.
... | Fit linear model.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
Returns
-------
self : returns an instance of self.
Fitted `TheilSenRegressor... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_theil_sen.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_theil_sen.py | BSD-3-Clause |
def test_linear_regression_sample_weight_consistency(
X_shape, sparse_container, fit_intercept, global_random_seed
):
"""Test that the impact of sample_weight is consistent.
Note that this test is stricter than the common test
check_sample_weight_equivalence alone and also tests sparse X.
It is ver... | Test that the impact of sample_weight is consistent.
Note that this test is stricter than the common test
check_sample_weight_equivalence alone and also tests sparse X.
It is very similar to test_enet_sample_weight_consistency.
| test_linear_regression_sample_weight_consistency | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_base.py | BSD-3-Clause |
def test_bayesian_ridge_score_values():
"""Check value of score on toy example.
Compute log marginal likelihood with equation (36) in Sparse Bayesian
Learning and the Relevance Vector Machine (Tipping, 2001):
- 0.5 * (log |Id/alpha + X.X^T/lambda| +
y^T.(Id/alpha + X.X^T/lambda).y + n * l... | Check value of score on toy example.
Compute log marginal likelihood with equation (36) in Sparse Bayesian
Learning and the Relevance Vector Machine (Tipping, 2001):
- 0.5 * (log |Id/alpha + X.X^T/lambda| +
y^T.(Id/alpha + X.X^T/lambda).y + n * log(2 * pi))
+ lambda_1 * log(lambda) - lamb... | test_bayesian_ridge_score_values | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_bayes.py | BSD-3-Clause |
def test_bayesian_covariance_matrix(n_samples, n_features, global_random_seed):
"""Check the posterior covariance matrix sigma_
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/31093
"""
X, y = datasets.make_regression(
n_samples, n_features, random_state=global_rando... | Check the posterior covariance matrix sigma_
Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/31093
| test_bayesian_covariance_matrix | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_bayes.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_bayes.py | BSD-3-Clause |
def test_linear_model_regressor_coef_shape(Regressor, ndim):
"""Check the consistency of linear models `coef` shape."""
if Regressor is LinearRegression:
pytest.xfail("LinearRegression does not follow `coef_` shape contract!")
X, y = make_regression(random_state=0, n_samples=200, n_features=20)
... | Check the consistency of linear models `coef` shape. | test_linear_model_regressor_coef_shape | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_common.py | BSD-3-Clause |
def test_set_order_dense(order, input_order):
"""Check that _set_order returns arrays with promised order."""
X = np.array([[0], [0], [0]], order=input_order)
y = np.array([0, 0, 0], order=input_order)
X2, y2 = _set_order(X, y, order=order)
if order == "C":
assert X2.flags["C_CONTIGUOUS"]
... | Check that _set_order returns arrays with promised order. | test_set_order_dense | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_set_order_sparse(order, input_order, coo_container):
"""Check that _set_order returns sparse matrices in promised format."""
X = coo_container(np.array([[0], [0], [0]]))
y = coo_container(np.array([0, 0, 0]))
sparse_format = "csc" if input_order == "F" else "csr"
X = X.asformat(sparse_forma... | Check that _set_order returns sparse matrices in promised format. | test_set_order_sparse | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_lasso_dual_gap():
"""
Check that Lasso.dual_gap_ matches its objective formulation, with the
datafit normalized by n_samples
"""
X, y, _, _ = build_dataset(n_samples=10, n_features=30)
n_samples = len(y)
alpha = 0.01 * np.max(np.abs(X.T @ y)) / n_samples
clf = Lasso(alpha=alpha,... |
Check that Lasso.dual_gap_ matches its objective formulation, with the
datafit normalized by n_samples
| test_lasso_dual_gap | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def build_dataset(n_samples=50, n_features=200, n_informative_features=10, n_targets=1):
"""
build an ill-posed linear regression problem with many noisy features and
comparatively few samples
"""
random_state = np.random.RandomState(0)
if n_targets > 1:
w = random_state.randn(n_features... |
build an ill-posed linear regression problem with many noisy features and
comparatively few samples
| build_dataset | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_lassocv_alphas_validation(alphas, err_type, err_msg):
"""Check the `alphas` validation in LassoCV."""
n_samples, n_features = 5, 5
rng = np.random.RandomState(0)
X = rng.randn(n_samples, n_features)
y = rng.randint(0, 2, n_samples)
lassocv = LassoCV(alphas=alphas)
with pytest.raise... | Check the `alphas` validation in LassoCV. | test_lassocv_alphas_validation | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def _scale_alpha_inplace(estimator, n_samples):
"""Rescale the parameter alpha from when the estimator is evoked with
normalize set to True as if it were evoked in a Pipeline with normalize set
to False and with a StandardScaler.
"""
if ("alpha" not in estimator.get_params()) and (
"alphas" ... | Rescale the parameter alpha from when the estimator is evoked with
normalize set to True as if it were evoked in a Pipeline with normalize set
to False and with a StandardScaler.
| _scale_alpha_inplace | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_path_unknown_parameter(path_func):
"""Check that passing parameter not used by the coordinate descent solver
will raise an error."""
X, y, _, _ = build_dataset(n_samples=50, n_features=20)
err_msg = "Unexpected parameters in params"
with pytest.raises(ValueError, match=err_msg):
pat... | Check that passing parameter not used by the coordinate descent solver
will raise an error. | test_path_unknown_parameter | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_enet_coordinate_descent(klass, n_classes, kwargs):
"""Test that a warning is issued if model does not converge"""
clf = klass(max_iter=2, **kwargs)
n_samples = 5
n_features = 2
X = np.ones((n_samples, n_features)) * 1e50
y = np.ones((n_samples, n_classes))
if klass == Lasso:
... | Test that a warning is issued if model does not converge | test_enet_coordinate_descent | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_enet_sample_weight_consistency(
fit_intercept, alpha, precompute, sparse_container, global_random_seed
):
"""Test that the impact of sample_weight is consistent.
Note that this test is stricter than the common test
check_sample_weight_equivalence alone and also tests sparse X.
"""
rng ... | Test that the impact of sample_weight is consistent.
Note that this test is stricter than the common test
check_sample_weight_equivalence alone and also tests sparse X.
| test_enet_sample_weight_consistency | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_enet_cv_sample_weight_correctness(
fit_intercept, sparse_container, global_random_seed
):
"""Test that ElasticNetCV with sample weights gives correct results.
We fit the same model twice, once with weighted training data, once with repeated
data points in the training data and check that both ... | Test that ElasticNetCV with sample weights gives correct results.
We fit the same model twice, once with weighted training data, once with repeated
data points in the training data and check that both models converge to the
same solution.
Since this model uses an internal cross-validation scheme to tu... | test_enet_cv_sample_weight_correctness | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_enet_cv_grid_search(sample_weight):
"""Test that ElasticNetCV gives same result as GridSearchCV."""
n_samples, n_features = 200, 10
cv = 5
X, y = make_regression(
n_samples=n_samples,
n_features=n_features,
effective_rank=10,
n_informative=n_features - 4,
... | Test that ElasticNetCV gives same result as GridSearchCV. | test_enet_cv_grid_search | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_enet_cv_sample_weight_consistency(
fit_intercept, l1_ratio, precompute, sparse_container
):
"""Test that the impact of sample_weight is consistent."""
rng = np.random.RandomState(0)
n_samples, n_features = 10, 5
X = rng.rand(n_samples, n_features)
y = X.sum(axis=1) + rng.rand(n_samples... | Test that the impact of sample_weight is consistent. | test_enet_cv_sample_weight_consistency | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input):
"""Check that ElasticNet does not overwrite sample_weights."""
rng = np.random.RandomState(0)
n_samples, n_features = 10, 5
X = rng.rand(n_samples, n_features)
y = rng.rand(n_samples)
sample_weight_1_25 = 1.25 * np.one... | Check that ElasticNet does not overwrite sample_weights. | test_enet_sample_weight_does_not_overwrite_sample_weight | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_read_only_buffer():
"""Test that sparse coordinate descent works for read-only buffers"""
rng = np.random.RandomState(0)
clf = ElasticNet(alpha=0.1, copy_X=True, random_state=rng)
X = np.asfortranarray(rng.uniform(size=(100, 10)))
X.setflags(write=False)
y = rng.rand(100)
clf.fit(... | Test that sparse coordinate descent works for read-only buffers | test_read_only_buffer | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_cv_estimators_reject_params_with_no_routing_enabled(EstimatorCV):
"""Check that the models inheriting from class:`LinearModelCV` raise an
error when any `params` are passed when routing is not enabled.
"""
X, y = make_regression(random_state=42)
groups = np.array([0, 1] * (len(y) // 2))
... | Check that the models inheriting from class:`LinearModelCV` raise an
error when any `params` are passed when routing is not enabled.
| test_cv_estimators_reject_params_with_no_routing_enabled | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_multitask_cv_estimators_with_sample_weight(MultiTaskEstimatorCV):
"""Check that for :class:`MultiTaskElasticNetCV` and
class:`MultiTaskLassoCV` if `sample_weight` is passed and the
CV splitter does not support `sample_weight` an error is raised.
On the other hand if the splitter does support `s... | Check that for :class:`MultiTaskElasticNetCV` and
class:`MultiTaskLassoCV` if `sample_weight` is passed and the
CV splitter does not support `sample_weight` an error is raised.
On the other hand if the splitter does support `sample_weight`
while `sample_weight` is passed there is no error and process
... | test_multitask_cv_estimators_with_sample_weight | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_linear_model_cv_deprecated_n_alphas(Estimator):
"""Check the deprecation of n_alphas in favor of alphas."""
X, y = make_regression(n_targets=2, random_state=42)
# Asses warning message raised by LinearModelCV when n_alphas is used
with pytest.warns(
FutureWarning,
match="'n_alp... | Check the deprecation of n_alphas in favor of alphas. | test_linear_model_cv_deprecated_n_alphas | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_linear_model_cv_deprecated_alphas_none(Estimator):
"""Check the deprecation of alphas=None."""
X, y = make_regression(n_targets=2, random_state=42)
with pytest.warns(
FutureWarning, match="'alphas=None' is deprecated and will be removed in 1.9"
):
clf = Estimator(alphas=None)
... | Check the deprecation of alphas=None. | test_linear_model_cv_deprecated_alphas_none | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_linear_model_cv_alphas_n_alphas_unset(Estimator):
"""Check that no warning is raised when both n_alphas and alphas are unset."""
X, y = make_regression(n_targets=2, random_state=42)
# Asses no warning message raised when n_alphas is not used
with warnings.catch_warnings():
warnings.sim... | Check that no warning is raised when both n_alphas and alphas are unset. | test_linear_model_cv_alphas_n_alphas_unset | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_linear_model_cv_alphas(Estimator):
"""Check that the behavior of alphas is consistent with n_alphas."""
X, y = make_regression(n_targets=2, random_state=42)
# n_alphas is set, alphas is not => n_alphas is used
clf = Estimator(n_alphas=5)
if clf._is_multitask():
clf.fit(X, y)
el... | Check that the behavior of alphas is consistent with n_alphas. | test_linear_model_cv_alphas | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_coordinate_descent.py | BSD-3-Clause |
def test_lasso_lars_copyX_behaviour(copy_X):
"""
Test that user input regarding copy_X is not being overridden (it was until
at least version 0.21)
"""
lasso_lars = LassoLarsIC(copy_X=copy_X, precompute=False)
rng = np.random.RandomState(0)
X = rng.normal(0, 1, (100, 5))
X_copy = X.copy... |
Test that user input regarding copy_X is not being overridden (it was until
at least version 0.21)
| test_lasso_lars_copyX_behaviour | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_least_angle.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_least_angle.py | BSD-3-Clause |
def test_lasso_lars_fit_copyX_behaviour(copy_X):
"""
Test that user input to .fit for copy_X overrides default __init__ value
"""
lasso_lars = LassoLarsIC(precompute=False)
rng = np.random.RandomState(0)
X = rng.normal(0, 1, (100, 5))
X_copy = X.copy()
y = X[:, 2]
lasso_lars.fit(X, ... |
Test that user input to .fit for copy_X overrides default __init__ value
| test_lasso_lars_fit_copyX_behaviour | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_least_angle.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_least_angle.py | BSD-3-Clause |
def test_lassolarsic_alpha_selection(criterion):
"""Check that we properly compute the AIC and BIC score.
In this test, we reproduce the example of the Fig. 2 of Zou et al.
(reference [1] in LassoLarsIC) In this example, only 7 features should be
selected.
"""
model = make_pipeline(StandardScal... | Check that we properly compute the AIC and BIC score.
In this test, we reproduce the example of the Fig. 2 of Zou et al.
(reference [1] in LassoLarsIC) In this example, only 7 features should be
selected.
| test_lassolarsic_alpha_selection | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_least_angle.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_least_angle.py | BSD-3-Clause |
def test_lassolarsic_noise_variance(fit_intercept):
"""Check the behaviour when `n_samples` < `n_features` and that one needs
to provide the noise variance."""
rng = np.random.RandomState(0)
X, y = datasets.make_regression(
n_samples=10, n_features=11 - fit_intercept, random_state=rng
)
... | Check the behaviour when `n_samples` < `n_features` and that one needs
to provide the noise variance. | test_lassolarsic_noise_variance | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_least_angle.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_least_angle.py | BSD-3-Clause |
def random_X_y_coef(
linear_model_loss, n_samples, n_features, coef_bound=(-2, 2), seed=42
):
"""Random generate y, X and coef in valid range."""
rng = np.random.RandomState(seed)
n_dof = n_features + linear_model_loss.fit_intercept
X = make_low_rank_matrix(
n_samples=n_samples,
n_fe... | Random generate y, X and coef in valid range. | random_X_y_coef | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_linear_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_linear_loss.py | BSD-3-Clause |
def test_loss_grad_hess_are_the_same(
base_loss,
fit_intercept,
sample_weight,
l2_reg_strength,
csr_container,
global_random_seed,
):
"""Test that loss and gradient are the same across different functions."""
loss = LinearModelLoss(base_loss=base_loss(), fit_intercept=fit_intercept)
... | Test that loss and gradient are the same across different functions. | test_loss_grad_hess_are_the_same | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_linear_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_linear_loss.py | BSD-3-Clause |
def test_loss_gradients_hessp_intercept(
base_loss, sample_weight, l2_reg_strength, X_container, global_random_seed
):
"""Test that loss and gradient handle intercept correctly."""
loss = LinearModelLoss(base_loss=base_loss(), fit_intercept=False)
loss_inter = LinearModelLoss(base_loss=base_loss(), fit_... | Test that loss and gradient handle intercept correctly. | test_loss_gradients_hessp_intercept | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_linear_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_linear_loss.py | BSD-3-Clause |
def test_gradients_hessians_numerically(
base_loss, fit_intercept, sample_weight, l2_reg_strength, global_random_seed
):
"""Test gradients and hessians with numerical derivatives.
Gradient should equal the numerical derivatives of the loss function.
Hessians should equal the numerical derivatives of gr... | Test gradients and hessians with numerical derivatives.
Gradient should equal the numerical derivatives of the loss function.
Hessians should equal the numerical derivatives of gradients.
| test_gradients_hessians_numerically | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_linear_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_linear_loss.py | BSD-3-Clause |
def test_multinomial_coef_shape(fit_intercept, global_random_seed):
"""Test that multinomial LinearModelLoss respects shape of coef."""
loss = LinearModelLoss(base_loss=HalfMultinomialLoss(), fit_intercept=fit_intercept)
n_samples, n_features = 10, 5
X, y, coef = random_X_y_coef(
linear_model_lo... | Test that multinomial LinearModelLoss respects shape of coef. | test_multinomial_coef_shape | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_linear_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_linear_loss.py | BSD-3-Clause |
def test_multinomial_hessian_3_classes(sample_weight, global_random_seed):
"""Test multinomial hessian for 3 classes and 2 points.
For n_classes = 3 and n_samples = 2, we have
p0 = [p0_0, p0_1]
p1 = [p1_0, p1_1]
p2 = [p2_0, p2_1]
and with 2 x 2 diagonal subblocks
H = [p0 * (1-p0), ... | Test multinomial hessian for 3 classes and 2 points.
For n_classes = 3 and n_samples = 2, we have
p0 = [p0_0, p0_1]
p1 = [p1_0, p1_1]
p2 = [p2_0, p2_1]
and with 2 x 2 diagonal subblocks
H = [p0 * (1-p0), -p0 * p1, -p0 * p2]
[ -p0 * p1, p1 * (1-p1), -p1 * p2]
... | test_multinomial_hessian_3_classes | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_linear_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_linear_loss.py | BSD-3-Clause |
def test_linear_loss_gradient_hessian_raises_wrong_out_parameters():
"""Test that wrong gradient_out and hessian_out raises errors."""
n_samples, n_features, n_classes = 5, 2, 3
loss = LinearModelLoss(base_loss=HalfBinomialLoss(), fit_intercept=False)
X = np.ones((n_samples, n_features))
y = np.ones... | Test that wrong gradient_out and hessian_out raises errors. | test_linear_loss_gradient_hessian_raises_wrong_out_parameters | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_linear_loss.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_linear_loss.py | BSD-3-Clause |
def check_predictions(clf, X, y):
"""Check that the model is able to fit the classification data"""
n_samples = len(y)
classes = np.unique(y)
n_classes = classes.shape[0]
predicted = clf.fit(X, y).predict(X)
assert_array_equal(clf.classes_, classes)
assert predicted.shape == (n_samples,)
... | Check that the model is able to fit the classification data | check_predictions | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_predict_iris(clf):
"""Test logistic regression with the iris dataset.
Test that both multinomial and OvR solvers handle multiclass data correctly and
give good accuracy score (>0.95) for the training data.
"""
n_samples, n_features = iris.data.shape
target = iris.target_names[iris.targ... | Test logistic regression with the iris dataset.
Test that both multinomial and OvR solvers handle multiclass data correctly and
give good accuracy score (>0.95) for the training data.
| test_predict_iris | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_logistic_regression_solvers():
"""Test solvers converge to the same result."""
X, y = make_classification(n_features=10, n_informative=5, random_state=0)
params = dict(fit_intercept=False, random_state=42)
regressors = {
solver: LogisticRegression(solver=solver, **params).fit(X, y)
... | Test solvers converge to the same result. | test_logistic_regression_solvers | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_logistic_regression_solvers_multiclass(fit_intercept):
"""Test solvers converge to the same result for multiclass problems."""
X, y = make_classification(
n_samples=20, n_features=20, n_informative=10, n_classes=3, random_state=0
)
tol = 1e-8
params = dict(fit_intercept=fit_intercep... | Test solvers converge to the same result for multiclass problems. | test_logistic_regression_solvers_multiclass | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_logistic_regression_solvers_multiclass_unpenalized(
fit_intercept, global_random_seed
):
"""Test and compare solver results for unpenalized multinomial multiclass."""
# We want to avoid perfect separation.
n_samples, n_features, n_classes = 100, 4, 3
rng = np.random.RandomState(global_rando... | Test and compare solver results for unpenalized multinomial multiclass. | test_logistic_regression_solvers_multiclass_unpenalized | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_multinomial_identifiability_on_iris(solver, fit_intercept):
"""Test that the multinomial classification is identifiable.
A multinomial with c classes can be modeled with
probability_k = exp(X@coef_k) / sum(exp(X@coef_l), l=1..c) for k=1..c.
This is not identifiable, unless one chooses a furthe... | Test that the multinomial classification is identifiable.
A multinomial with c classes can be modeled with
probability_k = exp(X@coef_k) / sum(exp(X@coef_l), l=1..c) for k=1..c.
This is not identifiable, unless one chooses a further constraint.
According to [1], the maximum of the L2 penalized likeliho... | test_multinomial_identifiability_on_iris | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_lr_cv_scores_differ_when_sample_weight_is_requested():
"""Test that `sample_weight` is correctly passed to the scorer in
`LogisticRegressionCV.fit` and `LogisticRegressionCV.score` by
checking the difference in scores with the case when `sample_weight`
is not requested.
"""
rng = np.ran... | Test that `sample_weight` is correctly passed to the scorer in
`LogisticRegressionCV.fit` and `LogisticRegressionCV.score` by
checking the difference in scores with the case when `sample_weight`
is not requested.
| test_lr_cv_scores_differ_when_sample_weight_is_requested | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_lr_cv_scores_without_enabling_metadata_routing():
"""Test that `sample_weight` is passed correctly to the scorer in
`LogisticRegressionCV.fit` and `LogisticRegressionCV.score` even
when `enable_metadata_routing=False`
"""
rng = np.random.RandomState(10)
X, y = make_classification(n_samp... | Test that `sample_weight` is passed correctly to the scorer in
`LogisticRegressionCV.fit` and `LogisticRegressionCV.score` even
when `enable_metadata_routing=False`
| test_lr_cv_scores_without_enabling_metadata_routing | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_passing_params_without_enabling_metadata_routing():
"""Test that the right error message is raised when metadata params
are passed while not supported when `enable_metadata_routing=False`."""
X, y = make_classification(n_samples=10, random_state=0)
lr_cv = LogisticRegressionCV()
msg = "is o... | Test that the right error message is raised when metadata params
are passed while not supported when `enable_metadata_routing=False`. | test_passing_params_without_enabling_metadata_routing | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_liblinear_multiclass_warning(Estimator):
"""Check that liblinear warns on multiclass problems."""
msg = (
"Using the 'liblinear' solver for multiclass classification is "
"deprecated. An error will be raised in 1.8. Either use another "
"solver which supports the multinomial los... | Check that liblinear warns on multiclass problems. | test_liblinear_multiclass_warning | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_logistic.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_logistic.py | BSD-3-Clause |
def test_estimator_n_nonzero_coefs():
"""Check `n_nonzero_coefs_` correct when `tol` is and isn't set."""
omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs)
omp.fit(X, y[:, 0])
assert omp.n_nonzero_coefs_ == n_nonzero_coefs
omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coe... | Check `n_nonzero_coefs_` correct when `tol` is and isn't set. | test_estimator_n_nonzero_coefs | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_omp.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_omp.py | BSD-3-Clause |
def test_perceptron_l1_ratio():
"""Check that `l1_ratio` has an impact when `penalty='elasticnet'`"""
clf1 = Perceptron(l1_ratio=0, penalty="elasticnet")
clf1.fit(X, y)
clf2 = Perceptron(l1_ratio=0.15, penalty="elasticnet")
clf2.fit(X, y)
assert clf1.score(X, y) != clf2.score(X, y)
# chec... | Check that `l1_ratio` has an impact when `penalty='elasticnet'` | test_perceptron_l1_ratio | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_perceptron.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_perceptron.py | BSD-3-Clause |
def test_equivariance(quantile):
"""Test equivariace of quantile regression.
See Koenker (2005) Quantile Regression, Chapter 2.2.3.
"""
rng = np.random.RandomState(42)
n_samples, n_features = 100, 5
X, y = make_regression(
n_samples=n_samples,
n_features=n_features,
n_in... | Test equivariace of quantile regression.
See Koenker (2005) Quantile Regression, Chapter 2.2.3.
| test_equivariance | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_quantile.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_quantile.py | BSD-3-Clause |
def test_sparse_input(sparse_container, solver, fit_intercept, global_random_seed):
"""Test that sparse and dense X give same results."""
n_informative = 10
quantile_level = 0.6
X, y = make_regression(
n_samples=300,
n_features=20,
n_informative=10,
random_state=global_ra... | Test that sparse and dense X give same results. | test_sparse_input | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_quantile.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_quantile.py | BSD-3-Clause |
def test_error_interior_point_future(X_y_data, monkeypatch):
"""Check that we will raise a proper error when requesting
`solver='interior-point'` in SciPy >= 1.11.
"""
X, y = X_y_data
import sklearn.linear_model._quantile
with monkeypatch.context() as m:
m.setattr(sklearn.linear_model._... | Check that we will raise a proper error when requesting
`solver='interior-point'` in SciPy >= 1.11.
| test_error_interior_point_future | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_quantile.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_quantile.py | BSD-3-Clause |
def test_perfect_horizontal_line():
"""Check that we can fit a line where all samples are inliers.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19497
"""
X = np.arange(100)[:, None]
y = np.zeros((100,))
estimator = LinearRegression()
ransac_estimator = RA... | Check that we can fit a line where all samples are inliers.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19497
| test_perfect_horizontal_line | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ransac.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ransac.py | BSD-3-Clause |
def ols_ridge_dataset(global_random_seed, request):
"""Dataset with OLS and Ridge solutions, well conditioned X.
The construction is based on the SVD decomposition of X = U S V'.
Parameters
----------
type : {"long", "wide"}
If "long", then n_samples > n_features.
If "wide", then n... | Dataset with OLS and Ridge solutions, well conditioned X.
The construction is based on the SVD decomposition of X = U S V'.
Parameters
----------
type : {"long", "wide"}
If "long", then n_samples > n_features.
If "wide", then n_features > n_samples.
For "wide", we return the minim... | ols_ridge_dataset | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression(solver, fit_intercept, ols_ridge_dataset, global_random_seed):
"""Test that Ridge converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
"""
X, y, _, coef = ols_ridge_dataset
alpha = 1.0 # because ols_ridge_dataset u... | Test that Ridge converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
| test_ridge_regression | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression_hstacked_X(
solver, fit_intercept, ols_ridge_dataset, global_random_seed
):
"""Test that Ridge converges for all solvers to correct solution on hstacked data.
We work with a simple constructed data set with known solution.
Fit on [X] with alpha is the same as fit on [X, X]/2 w... | Test that Ridge converges for all solvers to correct solution on hstacked data.
We work with a simple constructed data set with known solution.
Fit on [X] with alpha is the same as fit on [X, X]/2 with alpha/2.
For long X, [X, X] is a singular matrix.
| test_ridge_regression_hstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression_vstacked_X(
solver, fit_intercept, ols_ridge_dataset, global_random_seed
):
"""Test that Ridge converges for all solvers to correct solution on vstacked data.
We work with a simple constructed data set with known solution.
Fit on [X] with alpha is the same as fit on [X], [y]
... | Test that Ridge converges for all solvers to correct solution on vstacked data.
We work with a simple constructed data set with known solution.
Fit on [X] with alpha is the same as fit on [X], [y]
[X], [y] with 2 * alpha.
For wide X, [X', X'] is a singular ma... | test_ridge_regression_vstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression_unpenalized(
solver, fit_intercept, ols_ridge_dataset, global_random_seed
):
"""Test that unpenalized Ridge = OLS converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
Note: This checks the minimum norm solution for wide... | Test that unpenalized Ridge = OLS converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
Note: This checks the minimum norm solution for wide X, i.e.
n_samples < n_features:
min ||w||_2 subject to X w = y
| test_ridge_regression_unpenalized | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression_unpenalized_hstacked_X(
solver, fit_intercept, ols_ridge_dataset, global_random_seed
):
"""Test that unpenalized Ridge = OLS converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
OLS fit on [X] is the same as fit on [X, ... | Test that unpenalized Ridge = OLS converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
OLS fit on [X] is the same as fit on [X, X]/2.
For long X, [X, X] is a singular matrix and we check against the minimum norm
solution:
min ||w||_2 sub... | test_ridge_regression_unpenalized_hstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression_unpenalized_vstacked_X(
solver, fit_intercept, ols_ridge_dataset, global_random_seed
):
"""Test that unpenalized Ridge = OLS converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
OLS fit on [X] is the same as fit on [X],... | Test that unpenalized Ridge = OLS converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
OLS fit on [X] is the same as fit on [X], [y]
[X], [y].
For wide X, [X', X'] is a singular matrix and we check against th... | test_ridge_regression_unpenalized_vstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression_sample_weights(
solver,
fit_intercept,
sparse_container,
alpha,
ols_ridge_dataset,
global_random_seed,
):
"""Test that Ridge with sample weights gives correct results.
We use the following trick:
||y - Xw||_2 = (z - Aw)' W (z - Aw)
for z=[y, y], A' ... | Test that Ridge with sample weights gives correct results.
We use the following trick:
||y - Xw||_2 = (z - Aw)' W (z - Aw)
for z=[y, y], A' = [X', X'] (vstacked), and W[:n/2] + W[n/2:] = 1, W=diag(W)
| test_ridge_regression_sample_weights | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridgecv_alphas_zero(cv, Estimator):
"""Check alpha=0.0 raises error only when `cv=None`."""
rng = np.random.RandomState(0)
alphas = (0.0, 1.0, 10.0)
n_samples, n_features = 5, 5
if Estimator is RidgeCV:
y = rng.randn(n_samples)
else:
y = rng.randint(0, 2, n_samples)
... | Check alpha=0.0 raises error only when `cv=None`. | test_ridgecv_alphas_zero | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridgecv_alphas_validation(Estimator, params, err_type, err_msg):
"""Check the `alphas` validation in RidgeCV and RidgeClassifierCV."""
n_samples, n_features = 5, 5
X = rng.randn(n_samples, n_features)
y = rng.randint(0, 2, n_samples)
with pytest.raises(err_type, match=err_msg):
Es... | Check the `alphas` validation in RidgeCV and RidgeClassifierCV. | test_ridgecv_alphas_validation | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridgecv_alphas_scalar(Estimator):
"""Check the case when `alphas` is a scalar.
This case was supported in the past when `alphas` where converted
into array in `__init__`.
We add this test to ensure backward compatibility.
"""
n_samples, n_features = 5, 5
X = rng.randn(n_samples, n_... | Check the case when `alphas` is a scalar.
This case was supported in the past when `alphas` where converted
into array in `__init__`.
We add this test to ensure backward compatibility.
| test_ridgecv_alphas_scalar | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_fit_intercept_sparse(
solver, with_sample_weight, global_random_seed, csr_container
):
"""Check that ridge finds the same coefs and intercept on dense and sparse input
in the presence of sample weights.
For now only sparse_cg and lbfgs can correctly fit an intercept
with sparse X wit... | Check that ridge finds the same coefs and intercept on dense and sparse input
in the presence of sample weights.
For now only sparse_cg and lbfgs can correctly fit an intercept
with sparse X with default tol and max_iter.
'sag' is tested separately in test_ridge_fit_intercept_sparse_sag because it
... | test_ridge_fit_intercept_sparse | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_regression_check_arguments_validity(
return_intercept, sample_weight, container, solver
):
"""check if all combinations of arguments give valid estimations"""
# test excludes 'svd' solver because it raises exception for sparse inputs
rng = check_random_state(42)
X = rng.rand(1000, 3... | check if all combinations of arguments give valid estimations | test_ridge_regression_check_arguments_validity | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridgeclassifier_multilabel(Classifier, params):
"""Check that multilabel classification is supported and give meaningful
results."""
X, y = make_multilabel_classification(n_classes=1, random_state=0)
y = y.reshape(-1, 1)
Y = np.concatenate([y, y], axis=1)
clf = Classifier(**params).fit(... | Check that multilabel classification is supported and give meaningful
results. | test_ridgeclassifier_multilabel | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_positive_regression_test(solver, fit_intercept, alpha):
"""Test that positive Ridge finds true positive coefficients."""
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
coef = np.array([1, -10])
if fit_intercept:
intercept = 20
y = X.dot(coef) + intercept
else:
... | Test that positive Ridge finds true positive coefficients. | test_ridge_positive_regression_test | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_ground_truth_positive_test(fit_intercept, alpha):
"""Test that Ridge w/wo positive converges to the same solution.
Ridge with positive=True and positive=False must give the same
when the ground truth coefs are all positive.
"""
rng = np.random.RandomState(42)
X = rng.randn(300, 1... | Test that Ridge w/wo positive converges to the same solution.
Ridge with positive=True and positive=False must give the same
when the ground truth coefs are all positive.
| test_ridge_ground_truth_positive_test | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_positive_error_test(solver):
"""Test input validation for positive argument in Ridge."""
alpha = 0.1
X = np.array([[1, 2], [3, 4]])
coef = np.array([1, -1])
y = X @ coef
model = Ridge(alpha=alpha, positive=True, solver=solver, fit_intercept=False)
with pytest.raises(ValueErro... | Test input validation for positive argument in Ridge. | test_ridge_positive_error_test | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_positive_ridge_loss(alpha):
"""Check ridge loss consistency when positive argument is enabled."""
X, y = make_regression(n_samples=300, n_features=300, random_state=42)
alpha = 0.10
n_checks = 100
def ridge_loss(model, random_state=None, noise_scale=1e-8):
intercept = model.interce... | Check ridge loss consistency when positive argument is enabled. | test_positive_ridge_loss | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_lbfgs_solver_consistency(alpha):
"""Test that LBGFS gets almost the same coef of svd when positive=False."""
X, y = make_regression(n_samples=300, n_features=300, random_state=42)
y = np.expand_dims(y, 1)
alpha = np.asarray([alpha])
config = {
"positive": False,
"tol": 1e-16... | Test that LBGFS gets almost the same coef of svd when positive=False. | test_lbfgs_solver_consistency | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_lbfgs_solver_error():
"""Test that LBFGS solver raises ConvergenceWarning."""
X = np.array([[1, -1], [1, 1]])
y = np.array([-1e10, 1e10])
model = Ridge(
alpha=0.01,
solver="lbfgs",
fit_intercept=False,
tol=1e-12,
positive=True,
max_iter=1,
)
... | Test that LBFGS solver raises ConvergenceWarning. | test_lbfgs_solver_error | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_sample_weight_consistency(
fit_intercept, sparse_container, data, solver, global_random_seed
):
"""Test that the impact of sample_weight is consistent.
Note that this test is stricter than the common test
check_sample_weight_equivalence alone.
"""
# filter out solver that do not ... | Test that the impact of sample_weight is consistent.
Note that this test is stricter than the common test
check_sample_weight_equivalence alone.
| test_ridge_sample_weight_consistency | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_cv_results_predictions(with_sample_weight, fit_intercept, n_targets):
"""Check that the predictions stored in `cv_results_` are on the original scale.
The GCV approach works on scaled data: centered by an offset and scaled by the
square root of the sample weights. Thus, prior to computing sc... | Check that the predictions stored in `cv_results_` are on the original scale.
The GCV approach works on scaled data: centered by an offset and scaled by the
square root of the sample weights. Thus, prior to computing scores, the
predictions need to be scaled back to the original scale. These predictions ar... | test_ridge_cv_results_predictions | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_cv_multioutput_sample_weight(global_random_seed):
"""Check that `RidgeCV` works properly with multioutput and sample_weight
when `scoring != None`.
We check the error reported by the RidgeCV is close to a naive LOO-CV using a
Ridge estimator.
"""
X, y = make_regression(n_targets=... | Check that `RidgeCV` works properly with multioutput and sample_weight
when `scoring != None`.
We check the error reported by the RidgeCV is close to a naive LOO-CV using a
Ridge estimator.
| test_ridge_cv_multioutput_sample_weight | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_ridge_cv_custom_multioutput_scorer():
"""Check that `RidgeCV` works properly with a custom multioutput scorer."""
X, y = make_regression(n_targets=2, random_state=0)
def custom_error(y_true, y_pred):
errors = (y_true - y_pred) ** 2
mean_errors = np.mean(errors, axis=0)
if m... | Check that `RidgeCV` works properly with a custom multioutput scorer. | test_ridge_cv_custom_multioutput_scorer | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_set_score_request_with_default_scoring(metaestimator, make_dataset):
"""Test that `set_score_request` is set within `RidgeCV.fit()` and
`RidgeClassifierCV.fit()` when using the default scoring and no
UnsetMetadataPassedError is raised. Regression test for the fix in PR #29634."""
X, y = make_da... | Test that `set_score_request` is set within `RidgeCV.fit()` and
`RidgeClassifierCV.fit()` when using the default scoring and no
UnsetMetadataPassedError is raised. Regression test for the fix in PR #29634. | test_set_score_request_with_default_scoring | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_ridge.py | BSD-3-Clause |
def test_sag_pobj_matches_logistic_regression(csr_container):
"""tests if the sag pobj matches log reg"""
n_samples = 100
alpha = 1.0
max_iter = 20
X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1)
clf1 = LogisticRegression(
solver="sag",
fit_int... | tests if the sag pobj matches log reg | test_sag_pobj_matches_logistic_regression | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_sag_pobj_matches_ridge_regression(csr_container):
"""tests if the sag pobj matches ridge reg"""
n_samples = 100
n_features = 10
alpha = 1.0
n_iter = 100
fit_intercept = False
rng = np.random.RandomState(10)
X = rng.normal(size=(n_samples, n_features))
true_w = rng.normal(siz... | tests if the sag pobj matches ridge reg | test_sag_pobj_matches_ridge_regression | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_sag_regressor_computed_correctly(csr_container):
"""tests if the sag regressor is computed correctly"""
alpha = 0.1
n_features = 10
n_samples = 40
max_iter = 100
tol = 0.000001
fit_intercept = True
rng = np.random.RandomState(0)
X = rng.normal(size=(n_samples, n_features))
... | tests if the sag regressor is computed correctly | test_sag_regressor_computed_correctly | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_sag_regressor(seed, csr_container):
"""tests if the sag regressor performs well"""
xmin, xmax = -5, 5
n_samples = 300
tol = 0.001
max_iter = 100
alpha = 0.1
rng = np.random.RandomState(seed)
X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1)
# simple linear functi... | tests if the sag regressor performs well | test_sag_regressor | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_sag_classifier_computed_correctly(csr_container):
"""tests if the binary classifier is computed correctly"""
alpha = 0.1
n_samples = 50
n_iter = 50
tol = 0.00001
fit_intercept = True
X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1)
step_size = g... | tests if the binary classifier is computed correctly | test_sag_classifier_computed_correctly | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_sag_multiclass_computed_correctly(csr_container):
"""tests if the multiclass classifier is computed correctly"""
alpha = 0.1
n_samples = 20
tol = 1e-5
max_iter = 70
fit_intercept = True
X, y = make_blobs(n_samples=n_samples, centers=3, random_state=0, cluster_std=0.1)
step_size ... | tests if the multiclass classifier is computed correctly | test_sag_multiclass_computed_correctly | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_classifier_results(csr_container):
"""tests if classifier results match target"""
alpha = 0.1
n_features = 20
n_samples = 10
tol = 0.01
max_iter = 200
rng = np.random.RandomState(0)
X = rng.normal(size=(n_samples, n_features))
w = rng.normal(size=n_features)
y = np.dot(X... | tests if classifier results match target | test_classifier_results | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_binary_classifier_class_weight(csr_container):
"""tests binary classifier with classweights for each class"""
alpha = 0.1
n_samples = 50
n_iter = 20
tol = 0.00001
fit_intercept = True
X, y = make_blobs(n_samples=n_samples, centers=2, random_state=10, cluster_std=0.1)
step_size =... | tests binary classifier with classweights for each class | test_binary_classifier_class_weight | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_classifier_single_class():
"""tests if ValueError is thrown with only one class"""
X = [[1, 2], [3, 4]]
y = [1, 1]
msg = "This solver needs samples of at least 2 classes in the data"
with pytest.raises(ValueError, match=msg):
LogisticRegression(solver="sag").fit(X, y) | tests if ValueError is thrown with only one class | test_classifier_single_class | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sag.py | BSD-3-Clause |
def test_sgd_l1_ratio_not_used(Estimator, l1_ratio):
"""Check that l1_ratio is not used when penalty is not 'elasticnet'"""
clf1 = Estimator(penalty="l1", l1_ratio=None, random_state=0).fit(X, Y)
clf2 = Estimator(penalty="l1", l1_ratio=l1_ratio, random_state=0).fit(X, Y)
assert_allclose(clf1.coef_, clf... | Check that l1_ratio is not used when penalty is not 'elasticnet' | test_sgd_l1_ratio_not_used | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sgd.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sgd.py | BSD-3-Clause |
def test_power_t_limits(klass):
"""Check that a warning is raised when `power_t` is negative."""
# Check that negative values of `power_t` raise a warning
clf = klass(power_t=-1.0)
with pytest.warns(
FutureWarning, match="Negative values for `power_t` are deprecated"
):
clf.fit(X, Y... | Check that a warning is raised when `power_t` is negative. | test_power_t_limits | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sgd.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sgd.py | BSD-3-Clause |
def test_provide_coef(klass):
"""Check that the shape of `coef_init` is validated."""
with pytest.raises(ValueError, match="Provided coef_init does not match dataset"):
klass().fit(X, Y, coef_init=np.zeros((3,))) | Check that the shape of `coef_init` is validated. | test_provide_coef | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sgd.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sgd.py | BSD-3-Clause |
def test_sgd_early_stopping_with_partial_fit(klass):
"""Check that we raise an error for `early_stopping` used with
`partial_fit`.
"""
err_msg = "early_stopping should be False with partial_fit"
with pytest.raises(ValueError, match=err_msg):
klass(early_stopping=True).partial_fit(X, Y) | Check that we raise an error for `early_stopping` used with
`partial_fit`.
| test_sgd_early_stopping_with_partial_fit | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sgd.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sgd.py | BSD-3-Clause |
def test_validation_mask_correctly_subsets(monkeypatch):
"""Test that data passed to validation callback correctly subsets.
Non-regression test for #23255.
"""
X, Y = iris.data, iris.target
n_samples = X.shape[0]
validation_fraction = 0.2
clf = linear_model.SGDClassifier(
early_stop... | Test that data passed to validation callback correctly subsets.
Non-regression test for #23255.
| test_validation_mask_correctly_subsets | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sgd.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sgd.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.