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 _get_rescaled_operator(X, X_offset, sample_weight_sqrt):
"""Create LinearOperator for matrix products with implicit centering.
Matrix product `LinearOperator @ coef` returns `(X - X_offset) @ coef`.
"""
def matvec(b):
return X.dot(b) - sample_weight_sqrt * b.dot(X_offset)
def rmatvec(... | Create LinearOperator for matrix products with implicit centering.
Matrix product `LinearOperator @ coef` returns `(X - X_offset) @ coef`.
| _get_rescaled_operator | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _solve_lsqr(
X,
y,
*,
alpha,
fit_intercept=True,
max_iter=None,
tol=1e-4,
X_offset=None,
X_scale=None,
sample_weight_sqrt=None,
):
"""Solve Ridge regression via LSQR.
We expect that y is always mean centered.
If X is dense, we expect it to be mean centered such t... | Solve Ridge regression via LSQR.
We expect that y is always mean centered.
If X is dense, we expect it to be mean centered such that we can solve
||y - Xw||_2^2 + alpha * ||w||_2^2
If X is sparse, we expect X_offset to be given such that we can solve
||y - (X - X_offset)w||_2^2 + alpha * |... | _solve_lsqr | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _solve_lbfgs(
X,
y,
alpha,
positive=True,
max_iter=None,
tol=1e-4,
X_offset=None,
X_scale=None,
sample_weight_sqrt=None,
):
"""Solve ridge regression with LBFGS.
The main purpose is fitting with forcing coefficients to be positive.
For unconstrained ridge regression,... | Solve ridge regression with LBFGS.
The main purpose is fitting with forcing coefficients to be positive.
For unconstrained ridge regression, there are faster dedicated solver methods.
Note that with positive bounds on the coefficients, LBFGS seems faster
than scipy.optimize.lsq_linear.
| _solve_lbfgs | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def ridge_regression(
X,
y,
alpha,
*,
sample_weight=None,
solver="auto",
max_iter=None,
tol=1e-4,
verbose=0,
positive=False,
random_state=None,
return_n_iter=False,
return_intercept=False,
check_input=True,
):
"""Solve the ridge equation by the method of norma... | Solve the ridge equation by the method of normal equations.
Read more in the :ref:`User Guide <ridge_regression>`.
Parameters
----------
X : {array-like, sparse matrix, LinearOperator} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_sampl... | ridge_regression | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None):
"""Fit Ridge regression model.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
Target values.
... | Fit Ridge regression model.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
Target values.
sample_weight : float or ndarray of shape (n_sample... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _prepare_data(self, X, y, sample_weight, solver):
"""Validate `X` and `y` and binarize `y`.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
s... | Validate `X` and `y` and binarize `y`.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
sample_weight : float or ndarray of shape (n_samples,), default=No... | _prepare_data | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def predict(self, X):
"""Predict class labels for samples in `X`.
Parameters
----------
X : {array-like, spare matrix} of shape (n_samples, n_features)
The data matrix for which we want to predict the targets.
Returns
-------
y_pred : ndarray of shap... | Predict class labels for samples in `X`.
Parameters
----------
X : {array-like, spare matrix} of shape (n_samples, n_features)
The data matrix for which we want to predict the targets.
Returns
-------
y_pred : ndarray of shape (n_samples,) or (n_samples, n_o... | predict | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None):
"""Fit Ridge classifier model.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
sample_weight : float or ... | Fit Ridge classifier model.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
sample_weight : float or ndarray of shape (n_samples,), default=None
... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _find_smallest_angle(query, vectors):
"""Find the column of vectors that is most aligned with the query.
Both query and the columns of vectors must have their l2 norm equal to 1.
Parameters
----------
query : ndarray of shape (n_samples,)
Normalized query vector.
vectors : ndarray... | Find the column of vectors that is most aligned with the query.
Both query and the columns of vectors must have their l2 norm equal to 1.
Parameters
----------
query : ndarray of shape (n_samples,)
Normalized query vector.
vectors : ndarray of shape (n_samples, n_features)
Vectors... | _find_smallest_angle | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _compute_gram(self, X, sqrt_sw):
"""Computes the Gram matrix XX^T with possible centering.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The preprocessed design matrix.
sqrt_sw : ndarray of shape (n_samples,)
squ... | Computes the Gram matrix XX^T with possible centering.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The preprocessed design matrix.
sqrt_sw : ndarray of shape (n_samples,)
square roots of sample weights
Returns
... | _compute_gram | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _compute_covariance(self, X, sqrt_sw):
"""Computes covariance matrix X^TX with possible centering.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
The preprocessed design matrix.
sqrt_sw : ndarray of shape (n_samples,)
square... | Computes covariance matrix X^TX with possible centering.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
The preprocessed design matrix.
sqrt_sw : ndarray of shape (n_samples,)
square roots of sample weights
Returns
----... | _compute_covariance | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _sparse_multidot_diag(self, X, A, X_mean, sqrt_sw):
"""Compute the diagonal of (X - X_mean).dot(A).dot((X - X_mean).T)
without explicitly centering X nor computing X.dot(A)
when X is sparse.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
... | Compute the diagonal of (X - X_mean).dot(A).dot((X - X_mean).T)
without explicitly centering X nor computing X.dot(A)
when X is sparse.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
A : ndarray of shape (n_features, n_features)
X_mean... | _sparse_multidot_diag | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _solve_eigen_gram(self, alpha, y, sqrt_sw, X_mean, eigvals, Q, QT_y):
"""Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X.X^T (n_samples <= n_features).
"""
w = 1.0 / (eigvals + alpha)
if self.fit_intercept:
# the vector cont... | Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X.X^T (n_samples <= n_features).
| _solve_eigen_gram | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _eigen_decompose_covariance(self, X, y, sqrt_sw):
"""Eigendecomposition of X^T.X, used when n_samples > n_features
and X is sparse.
"""
n_samples, n_features = X.shape
cov = np.empty((n_features + 1, n_features + 1), dtype=X.dtype)
cov[:-1, :-1], X_mean = self._comput... | Eigendecomposition of X^T.X, used when n_samples > n_features
and X is sparse.
| _eigen_decompose_covariance | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _solve_eigen_covariance_no_intercept(
self, alpha, y, sqrt_sw, X_mean, eigvals, V, X
):
"""Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X^T.X
(n_samples > n_features and X is sparse), and not fitting an intercept.
"""
w = 1... | Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X^T.X
(n_samples > n_features and X is sparse), and not fitting an intercept.
| _solve_eigen_covariance_no_intercept | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _solve_eigen_covariance_intercept(
self, alpha, y, sqrt_sw, X_mean, eigvals, V, X
):
"""Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X^T.X
(n_samples > n_features and X is sparse),
and we are fitting an intercept.
"""
... | Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X^T.X
(n_samples > n_features and X is sparse),
and we are fitting an intercept.
| _solve_eigen_covariance_intercept | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _solve_eigen_covariance(self, alpha, y, sqrt_sw, X_mean, eigvals, V, X):
"""Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X^T.X
(n_samples > n_features and X is sparse).
"""
if self.fit_intercept:
return self._solve_eigen_co... | Compute dual coefficients and diagonal of G^-1.
Used when we have a decomposition of X^T.X
(n_samples > n_features and X is sparse).
| _solve_eigen_covariance | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _solve_svd_design_matrix(self, alpha, y, sqrt_sw, X_mean, singvals_sq, U, UT_y):
"""Compute dual coefficients and diagonal of G^-1.
Used when we have an SVD decomposition of X
(n_samples > n_features and X is dense).
"""
w = ((singvals_sq + alpha) ** -1) - (alpha**-1)
... | Compute dual coefficients and diagonal of G^-1.
Used when we have an SVD decomposition of X
(n_samples > n_features and X is dense).
| _solve_svd_design_matrix | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None, score_params=None):
"""Fit Ridge regression model with gcv.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data. Will be cast to float64 if necessary.
y : ndarray of shape (n_sampl... | Fit Ridge regression model with gcv.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data. Will be cast to float64 if necessary.
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
Target values. Will be cast ... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _score_without_scorer(self, squared_errors):
"""Performs scoring using squared errors when the scorer is None."""
if self.alpha_per_target:
_score = -squared_errors.mean(axis=0)
else:
_score = -squared_errors.mean()
return _score | Performs scoring using squared errors when the scorer is None. | _score_without_scorer | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def _score(self, *, predictions, y, n_y, scorer, score_params):
"""Performs scoring with the specified scorer using the
predictions and the true y values.
"""
if self.is_clf:
identity_estimator = _IdentityClassifier(classes=np.arange(n_y))
_score = scorer(
... | Performs scoring with the specified scorer using the
predictions and the true y values.
| _score | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None, **params):
"""Fit Ridge regression model with cv.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data. If using GCV, will be cast to float64
if necessary.
y : ndarray of shape (n_sample... | Fit Ridge regression model with cv.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data. If using GCV, will be cast to float64
if necessary.
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
Target values. Will ... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.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.5
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.5
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating... | get_metadata_routing | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None, **params):
"""Fit Ridge classifier with cv.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples
and `n_features` is the number of features. When us... | Fit Ridge classifier with cv.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples
and `n_features` is the number of features. When using GCV,
will be cast to float64 if necessary.
... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_ridge.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_ridge.py | BSD-3-Clause |
def get_auto_step_size(
max_squared_sum, alpha_scaled, loss, fit_intercept, n_samples=None, is_saga=False
):
"""Compute automatic step size for SAG solver.
The step size is set to 1 / (alpha_scaled + L + fit_intercept) where L is
the max sum of squares for over all samples.
Parameters
--------... | Compute automatic step size for SAG solver.
The step size is set to 1 / (alpha_scaled + L + fit_intercept) where L is
the max sum of squares for over all samples.
Parameters
----------
max_squared_sum : float
Maximum squared sum of X over samples.
alpha_scaled : float
Constant... | get_auto_step_size | python | scikit-learn/scikit-learn | sklearn/linear_model/_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_sag.py | BSD-3-Clause |
def sag_solver(
X,
y,
sample_weight=None,
loss="log",
alpha=1.0,
beta=0.0,
max_iter=1000,
tol=0.001,
verbose=0,
random_state=None,
check_input=True,
max_squared_sum=None,
warm_start_mem=None,
is_saga=False,
):
"""SAG solver for Ridge and LogisticRegression.
... | SAG solver for Ridge and LogisticRegression.
SAG stands for Stochastic Average Gradient: the gradient of the loss is
estimated each sample at a time and the model is updated along the way with
a constant learning rate.
IMPORTANT NOTE: 'sag' solver converges faster on columns that are on the
same s... | sag_solver | python | scikit-learn/scikit-learn | sklearn/linear_model/_sag.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_sag.py | BSD-3-Clause |
def _get_loss_function(self, loss):
"""Get concrete ``LossFunction`` object for str ``loss``."""
loss_ = self.loss_functions[loss]
loss_class, args = loss_[0], loss_[1:]
if loss in ("huber", "epsilon_insensitive", "squared_epsilon_insensitive"):
args = (self.epsilon,)
... | Get concrete ``LossFunction`` object for str ``loss``. | _get_loss_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 _allocate_parameter_mem(
self,
n_classes,
n_features,
input_dtype,
coef_init=None,
intercept_init=None,
one_class=0,
):
"""Allocate mem for parameters; initialize if provided."""
if n_classes > 2:
# allocate coef_ for multi-clas... | Allocate mem for parameters; initialize if provided. | _allocate_parameter_mem | 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 _make_validation_split(self, y, sample_mask):
"""Split the dataset between training set and validation set.
Parameters
----------
y : ndarray of shape (n_samples, )
Target values.
sample_mask : ndarray of shape (n_samples, )
A boolean array indicatin... | Split the dataset between training set and validation set.
Parameters
----------
y : ndarray of shape (n_samples, )
Target values.
sample_mask : ndarray of shape (n_samples, )
A boolean array indicating whether each sample should be included
for vali... | _make_validation_split | 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_binary(
est,
i,
X,
y,
alpha,
C,
learning_rate,
max_iter,
pos_weight,
neg_weight,
sample_weight,
validation_mask=None,
random_state=None,
):
"""Fit a single binary classifier.
The i'th class is considered the "positive" class.
Parameters
-----... | Fit a single binary classifier.
The i'th class is considered the "positive" class.
Parameters
----------
est : Estimator object
The estimator to fit
i : int
Index of the positive class
X : numpy array or sparse matrix of shape [n_samples,n_features]
Training data
... | fit_binary | 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_multiclass(self, X, y, alpha, C, learning_rate, sample_weight, max_iter):
"""Fit a multi-class classifier by combining binary classifiers
Each binary classifier predicts one class versus all others. This
strategy is called OvA (One versus All) or OvR (One versus Rest).
"""
... | Fit a multi-class classifier by combining binary classifiers
Each binary classifier predicts one class versus all others. This
strategy is called OvA (One versus All) or OvR (One versus Rest).
| _fit_multiclass | 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, 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_classes, n_features),... | 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 partial_fit(self, X, y, sample_weight=None):
"""Perform one epoch of stochastic gradient descent on given samples.
Internally, this method uses ``max_iter = 1``. Therefore, it is not
guaranteed that a minimum of the cost function is reached after calling
it once. Matters such as obj... | Perform one epoch of stochastic gradient descent on given samples.
Internally, this method uses ``max_iter = 1``. Therefore, it is not
guaranteed that a minimum of the cost function is reached after calling
it once. Matters such as objective convergence and early stopping
should be hand... | 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, 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_asymmetric_error(quantile):
"""Test quantile regression for asymmetric distributed targets."""
n_samples = 1000
rng = np.random.RandomState(42)
X = np.concatenate(
(
np.abs(rng.randn(n_samples)[:, None]),
-rng.randint(2, size=(n_samples, 1)),
),
a... | Test quantile regression for asymmetric distributed targets. | test_asymmetric_error | 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_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 |
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.