code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_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 |
def test_sgd_one_class_svm_estimator_type():
"""Check that SGDOneClassSVM has the correct estimator type.
Non-regression test for if the mixin was not on the left.
"""
sgd_ocsvm = SGDOneClassSVM()
assert get_tags(sgd_ocsvm).estimator_type == "outlier_detector" | Check that SGDOneClassSVM has the correct estimator type.
Non-regression test for if the mixin was not on the left.
| test_sgd_one_class_svm_estimator_type | 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_sparse_enet_coordinate_descent(csc_container):
"""Test that a warning is issued if model does not converge"""
clf = Lasso(max_iter=2)
n_samples = 5
n_features = 2
X = csc_container((n_samples, n_features)) * 1e50
y = np.ones(n_samples)
warning_message = (
"Objective did not ... | Test that a warning is issued if model does not converge | test_sparse_enet_coordinate_descent | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sparse_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sparse_coordinate_descent.py | BSD-3-Clause |
def test_sparse_read_only_buffer(copy_X):
"""Test that sparse coordinate descent works for read-only buffers"""
rng = np.random.RandomState(0)
clf = ElasticNet(alpha=0.1, copy_X=copy_X, random_state=rng)
X = sp.random(100, 20, format="csc", random_state=rng)
# Make X.data read-only
X.data = cr... | Test that sparse coordinate descent works for read-only buffers | test_sparse_read_only_buffer | python | scikit-learn/scikit-learn | sklearn/linear_model/tests/test_sparse_coordinate_descent.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/tests/test_sparse_coordinate_descent.py | BSD-3-Clause |
def fit(self, X, y, sample_weight=None):
"""Fit a Generalized Linear Model.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
sample_weight :... | Fit a Generalized Linear Model.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
sample_weight : array-like of shape (n_samples,), default=None
... | fit | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/glm.py | BSD-3-Clause |
def _linear_predictor(self, X):
"""Compute the linear_predictor = `X @ coef_ + intercept_`.
Note that we often use the term raw_prediction instead of linear predictor.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
... | Compute the linear_predictor = `X @ coef_ + intercept_`.
Note that we often use the term raw_prediction instead of linear predictor.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
Returns
-------
y_pr... | _linear_predictor | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/glm.py | BSD-3-Clause |
def predict(self, X):
"""Predict using GLM with feature matrix X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
Returns
-------
y_pred : array of shape (n_samples,)
Returns predicted value... | Predict using GLM with feature matrix X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
Returns
-------
y_pred : array of shape (n_samples,)
Returns predicted values.
| predict | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/glm.py | BSD-3-Clause |
def score(self, X, y, sample_weight=None):
"""Compute D^2, the percentage of deviance explained.
D^2 is a generalization of the coefficient of determination R^2.
R^2 uses squared error and D^2 uses the deviance of this GLM, see the
:ref:`User Guide <regression_metrics>`.
D^2 is... | Compute D^2, the percentage of deviance explained.
D^2 is a generalization of the coefficient of determination R^2.
R^2 uses squared error and D^2 uses the deviance of this GLM, see the
:ref:`User Guide <regression_metrics>`.
D^2 is defined as
:math:`D^2 = 1-\frac{D(y_{true},y_... | score | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/glm.py | BSD-3-Clause |
def setup(self, X, y, sample_weight):
"""Precomputations
If None, initializes:
- self.coef
Sets:
- self.raw_prediction
- self.loss_value
"""
_, _, self.raw_prediction = self.linear_loss.weight_intercept_raw(self.coef, X)
self.loss_valu... | Precomputations
If None, initializes:
- self.coef
Sets:
- self.raw_prediction
- self.loss_value
| setup | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/_newton_solver.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/_newton_solver.py | BSD-3-Clause |
def inner_solve(self, X, y, sample_weight):
"""Compute Newton step.
Sets:
- self.coef_newton
- self.gradient_times_newton
""" | Compute Newton step.
Sets:
- self.coef_newton
- self.gradient_times_newton
| inner_solve | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/_newton_solver.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/_newton_solver.py | BSD-3-Clause |
def fallback_lbfgs_solve(self, X, y, sample_weight):
"""Fallback solver in case of emergency.
If a solver detects convergence problems, it may fall back to this methods in
the hope to exit with success instead of raising an error.
Sets:
- self.coef
- self.conver... | Fallback solver in case of emergency.
If a solver detects convergence problems, it may fall back to this methods in
the hope to exit with success instead of raising an error.
Sets:
- self.coef
- self.converged
| fallback_lbfgs_solve | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/_newton_solver.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/_newton_solver.py | BSD-3-Clause |
def line_search(self, X, y, sample_weight):
"""Backtracking line search.
Sets:
- self.coef_old
- self.coef
- self.loss_value_old
- self.loss_value
- self.gradient_old
- self.gradient
- self.raw_prediction
"""
... | Backtracking line search.
Sets:
- self.coef_old
- self.coef
- self.loss_value_old
- self.loss_value
- self.gradient_old
- self.gradient
- self.raw_prediction
| line_search | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/_newton_solver.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/_newton_solver.py | BSD-3-Clause |
def check_convergence(self, X, y, sample_weight):
"""Check for convergence.
Sets self.converged.
"""
if self.verbose:
print(" Check Convergence")
# Note: Checking maximum relative change of coefficient <= tol is a bad
# convergence criterion because even a l... | Check for convergence.
Sets self.converged.
| check_convergence | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/_newton_solver.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/_newton_solver.py | BSD-3-Clause |
def solve(self, X, y, sample_weight):
"""Solve the optimization problem.
This is the main routine.
Order of calls:
self.setup()
while iteration:
self.update_gradient_hessian()
self.inner_solve()
self.line_search()
... | Solve the optimization problem.
This is the main routine.
Order of calls:
self.setup()
while iteration:
self.update_gradient_hessian()
self.inner_solve()
self.line_search()
self.check_convergence()
self... | solve | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/_newton_solver.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/_newton_solver.py | BSD-3-Clause |
def glm_dataset(global_random_seed, request):
"""Dataset with GLM solutions, well conditioned X.
This is inspired by ols_ridge_dataset in test_ridge.py.
The construction is based on the SVD decomposition of X = U S V'.
Parameters
----------
type : {"long", "wide"}
If "long", then n_sa... | Dataset with GLM solutions, well conditioned X.
This is inspired by ols_ridge_dataset in test_ridge.py.
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_feature... | glm_dataset | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_regression(solver, fit_intercept, glm_dataset):
"""Test that GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
"""
model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset
params = dict(
al... | Test that GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
| test_glm_regression | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_regression_hstacked_X(solver, fit_intercept, glm_dataset):
"""Test that GLM 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] ... | Test that GLM 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 still a long but singular matrix.
| test_glm_regression_hstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_regression_vstacked_X(solver, fit_intercept, glm_dataset):
"""Test that GLM 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 GLM 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 1 * alpha.
It is the same alpha as the average los... | test_glm_regression_vstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_regression_unpenalized(solver, fit_intercept, glm_dataset):
"""Test that unpenalized GLM 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:
... | Test that unpenalized GLM 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 w = argmin deviance(X, y, w)
| test_glm_regression_unpenalized | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_regression_unpenalized_hstacked_X(solver, fit_intercept, glm_dataset):
"""Test that unpenalized GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
GLM fit on [X] is the same as fit on [X, X]/2.
For long X, [X, X] is a singular... | Test that unpenalized GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
GLM 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 subject to ... | test_glm_regression_unpenalized_hstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_regression_unpenalized_vstacked_X(solver, fit_intercept, glm_dataset):
"""Test that unpenalized GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
GLM fit on [X] is the same as fit on [X], [y]
... | Test that unpenalized GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
GLM 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 the minimu... | test_glm_regression_unpenalized_vstacked_X | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_sample_weights_validation():
"""Test the raised errors in the validation of sample_weight."""
# scalar value but not positive
X = [[1]]
y = [1]
weights = 0
glm = _GeneralizedLinearRegressor()
# Positive weights are accepted
glm.fit(X, y, sample_weight=1)
# 2d array
wei... | Test the raised errors in the validation of sample_weight. | test_sample_weights_validation | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_wrong_y_range(glm):
"""
Test that fitting a GLM model raises a ValueError when `y` contains
values outside the valid range for the given distribution.
Generalized Linear Models (GLMs) with certain distributions, such as
Poisson, Gamma, and Tweedie (with power > 1), require `y` to be
... |
Test that fitting a GLM model raises a ValueError when `y` contains
values outside the valid range for the given distribution.
Generalized Linear Models (GLMs) with certain distributions, such as
Poisson, Gamma, and Tweedie (with power > 1), require `y` to be
non-negative. This test ensures that p... | test_glm_wrong_y_range | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_identity_regression(fit_intercept):
"""Test GLM regression with identity link on a simple dataset."""
coef = [1.0, 2.0]
X = np.array([[1, 1, 1, 1, 1], [0, 1, 2, 3, 4]]).T
y = np.dot(X, coef)
glm = _GeneralizedLinearRegressor(
alpha=0,
fit_intercept=fit_intercept,
... | Test GLM regression with identity link on a simple dataset. | test_glm_identity_regression | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_sample_weight_consistency(fit_intercept, alpha, GLMEstimator):
"""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 = rng.rand(n_samples)
glm_params = dict(alpha=alpha, fit_inter... | Test that the impact of sample_weight is consistent | test_glm_sample_weight_consistency | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_glm_log_regression(solver, fit_intercept, estimator):
"""Test GLM regression with log link on a simple dataset."""
coef = [0.2, -0.1]
X = np.array([[0, 1, 2, 3, 4], [1, 1, 1, 1, 1]]).T
y = np.exp(np.dot(X, coef))
glm = clone(estimator).set_params(
alpha=0,
fit_intercept=fit_... | Test GLM regression with log link on a simple dataset. | test_glm_log_regression | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_warm_start(solver, fit_intercept, global_random_seed):
"""
Test that `warm_start=True` enables incremental fitting in PoissonRegressor.
This test verifies that when using `warm_start=True`, the model continues
optimizing from previous coefficients instead of restarting from scratch.
It ens... |
Test that `warm_start=True` enables incremental fitting in PoissonRegressor.
This test verifies that when using `warm_start=True`, the model continues
optimizing from previous coefficients instead of restarting from scratch.
It ensures that after an initial fit with `max_iter=1`, the model has a
h... | test_warm_start | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_normal_ridge_comparison(
n_samples, n_features, fit_intercept, sample_weight, request
):
"""Compare with Ridge regression for Normal distributions."""
test_size = 10
X, y = make_regression(
n_samples=n_samples + test_size,
n_features=n_features,
n_informative=n_features ... | Compare with Ridge regression for Normal distributions. | test_normal_ridge_comparison | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_poisson_glmnet(solver):
"""Compare Poisson regression with L2 regularization and LogLink to glmnet"""
# library("glmnet")
# options(digits=10)
# df <- data.frame(a=c(-2,-1,1,2), b=c(0,0,1,1), y=c(0,1,1,2))
# x <- data.matrix(df[,c("a", "b")])
# y <- df$y
# fit <- glmnet(x=x, y=y, al... | Compare Poisson regression with L2 regularization and LogLink to glmnet | test_poisson_glmnet | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_tweedie_link_argument(name, link_class):
"""Test GLM link argument set as string."""
y = np.array([0.1, 0.5]) # in range of all distributions
X = np.array([[1], [2]])
glm = TweedieRegressor(power=1, link=name).fit(X, y)
assert isinstance(glm._base_loss.link, link_class) | Test GLM link argument set as string. | test_tweedie_link_argument | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_tweedie_link_auto(power, expected_link_class):
"""Test that link='auto' delivers the expected link function"""
y = np.array([0.1, 0.5]) # in range of all distributions
X = np.array([[1], [2]])
glm = TweedieRegressor(link="auto", power=power).fit(X, y)
assert isinstance(glm._base_loss.link,... | Test that link='auto' delivers the expected link function | test_tweedie_link_auto | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_tweedie_score(regression_data, power, link):
"""Test that GLM score equals d2_tweedie_score for Tweedie losses."""
X, y = regression_data
# make y positive
y = np.abs(y) + 1.0
glm = TweedieRegressor(power=power, link=link).fit(X, y)
assert glm.score(X, y) == pytest.approx(
d2_tw... | Test that GLM score equals d2_tweedie_score for Tweedie losses. | test_tweedie_score | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_linalg_warning_with_newton_solver(global_random_seed):
"""
Test that the Newton solver raises a warning and falls back to LBFGS when
encountering a singular or ill-conditioned Hessian matrix.
This test assess the behavior of `PoissonRegressor` with the "newton-cholesky"
solver.
It veri... |
Test that the Newton solver raises a warning and falls back to LBFGS when
encountering a singular or ill-conditioned Hessian matrix.
This test assess the behavior of `PoissonRegressor` with the "newton-cholesky"
solver.
It verifies the following:-
- The model significantly improves upon the co... | test_linalg_warning_with_newton_solver | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def test_newton_solver_verbosity(capsys, verbose):
"""Test the std output of verbose newton solvers."""
y = np.array([1, 2], dtype=float)
X = np.array([[1.0, 0], [0, 1]], dtype=float)
linear_loss = LinearModelLoss(base_loss=HalfPoissonLoss(), fit_intercept=False)
sol = NewtonCholeskySolver(
... | Test the std output of verbose newton solvers. | test_newton_solver_verbosity | python | scikit-learn/scikit-learn | sklearn/linear_model/_glm/tests/test_glm.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/_glm/tests/test_glm.py | BSD-3-Clause |
def reconstruction_error(self):
"""Compute the reconstruction error for the embedding.
Returns
-------
reconstruction_error : float
Reconstruction error.
Notes
-----
The cost function of an isomap embedding is
``E = frobenius_norm[K(D) - K(D... | Compute the reconstruction error for the embedding.
Returns
-------
reconstruction_error : float
Reconstruction error.
Notes
-----
The cost function of an isomap embedding is
``E = frobenius_norm[K(D) - K(D_fit)] / n_samples``
Where D is th... | reconstruction_error | python | scikit-learn/scikit-learn | sklearn/manifold/_isomap.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_isomap.py | BSD-3-Clause |
def transform(self, X):
"""Transform X.
This is implemented by linking the points X into the graph of geodesic
distances of the training data. First the `n_neighbors` nearest
neighbors of X are found in the training data, and from these the
shortest geodesic distances from each ... | Transform X.
This is implemented by linking the points X into the graph of geodesic
distances of the training data. First the `n_neighbors` nearest
neighbors of X are found in the training data, and from these the
shortest geodesic distances from each point in X to each point in
... | transform | python | scikit-learn/scikit-learn | sklearn/manifold/_isomap.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_isomap.py | BSD-3-Clause |
def barycenter_weights(X, Y, indices, reg=1e-3):
"""Compute barycenter weights of X from Y along the first axis
We estimate the weights to assign to each point in Y[indices] to recover
the point X[i]. The barycenter weights sum to 1.
Parameters
----------
X : array-like, shape (n_samples, n_di... | Compute barycenter weights of X from Y along the first axis
We estimate the weights to assign to each point in Y[indices] to recover
the point X[i]. The barycenter weights sum to 1.
Parameters
----------
X : array-like, shape (n_samples, n_dim)
Y : array-like, shape (n_samples, n_dim)
in... | barycenter_weights | python | scikit-learn/scikit-learn | sklearn/manifold/_locally_linear.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_locally_linear.py | BSD-3-Clause |
def barycenter_kneighbors_graph(X, n_neighbors, reg=1e-3, n_jobs=None):
"""Computes the barycenter weighted graph of k-Neighbors for points in X
Parameters
----------
X : {array-like, NearestNeighbors}
Sample data, shape = (n_samples, n_features), in the form of a
numpy array or a Neare... | Computes the barycenter weighted graph of k-Neighbors for points in X
Parameters
----------
X : {array-like, NearestNeighbors}
Sample data, shape = (n_samples, n_features), in the form of a
numpy array or a NearestNeighbors object.
n_neighbors : int
Number of neighbors for each... | barycenter_kneighbors_graph | python | scikit-learn/scikit-learn | sklearn/manifold/_locally_linear.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_locally_linear.py | BSD-3-Clause |
def null_space(
M, k, k_skip=1, eigen_solver="arpack", tol=1e-6, max_iter=100, random_state=None
):
"""
Find the null space of a matrix M.
Parameters
----------
M : {array, matrix, sparse matrix, LinearOperator}
Input covariance matrix: should be symmetric positive semi-definite
k ... |
Find the null space of a matrix M.
Parameters
----------
M : {array, matrix, sparse matrix, LinearOperator}
Input covariance matrix: should be symmetric positive semi-definite
k : int
Number of eigenvalues/vectors to return
k_skip : int, default=1
Number of low eigenv... | null_space | python | scikit-learn/scikit-learn | sklearn/manifold/_locally_linear.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_locally_linear.py | BSD-3-Clause |
def locally_linear_embedding(
X,
*,
n_neighbors,
n_components,
reg=1e-3,
eigen_solver="auto",
tol=1e-6,
max_iter=100,
method="standard",
hessian_tol=1e-4,
modified_tol=1e-12,
random_state=None,
n_jobs=None,
):
"""Perform a Locally Linear Embedding analysis on the ... | Perform a Locally Linear Embedding analysis on the data.
Read more in the :ref:`User Guide <locally_linear_embedding>`.
Parameters
----------
X : {array-like, NearestNeighbors}
Sample data, shape = (n_samples, n_features), in the form of a
numpy array or a NearestNeighbors object.
... | locally_linear_embedding | python | scikit-learn/scikit-learn | sklearn/manifold/_locally_linear.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_locally_linear.py | BSD-3-Clause |
def transform(self, X):
"""
Transform new points into embedding space.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training set.
Returns
-------
X_new : ndarray of shape (n_samples, n_components)
Returns ... |
Transform new points into embedding space.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training set.
Returns
-------
X_new : ndarray of shape (n_samples, n_components)
Returns the instance itself.
Notes... | transform | python | scikit-learn/scikit-learn | sklearn/manifold/_locally_linear.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_locally_linear.py | BSD-3-Clause |
def _smacof_single(
dissimilarities,
metric=True,
n_components=2,
init=None,
max_iter=300,
verbose=0,
eps=1e-6,
random_state=None,
normalized_stress=False,
):
"""Computes multidimensional scaling using SMACOF algorithm.
Parameters
----------
dissimilarities : ndarray... | Computes multidimensional scaling using SMACOF algorithm.
Parameters
----------
dissimilarities : ndarray of shape (n_samples, n_samples)
Pairwise dissimilarities between the points. Must be symmetric.
metric : bool, default=True
Compute metric or nonmetric SMACOF algorithm.
Wh... | _smacof_single | python | scikit-learn/scikit-learn | sklearn/manifold/_mds.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_mds.py | BSD-3-Clause |
def smacof(
dissimilarities,
*,
metric=True,
n_components=2,
init=None,
n_init="warn",
n_jobs=None,
max_iter=300,
verbose=0,
eps=1e-6,
random_state=None,
return_n_iter=False,
normalized_stress="auto",
):
"""Compute multidimensional scaling using the SMACOF algorit... | Compute multidimensional scaling using the SMACOF algorithm.
The SMACOF (Scaling by MAjorizing a COmplicated Function) algorithm is a
multidimensional scaling algorithm which minimizes an objective function
(the *stress*) using a majorization technique. Stress majorization, also
known as the Guttman Tr... | smacof | python | scikit-learn/scikit-learn | sklearn/manifold/_mds.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_mds.py | BSD-3-Clause |
def fit_transform(self, X, y=None, init=None):
"""
Fit the data from `X`, and returns the embedded coordinates.
Parameters
----------
X : array-like of shape (n_samples, n_features) or \
(n_samples, n_samples)
Input data. If ``dissimilarity=='precompu... |
Fit the data from `X`, and returns the embedded coordinates.
Parameters
----------
X : array-like of shape (n_samples, n_features) or (n_samples, n_samples)
Input data. If ``dissimilarity=='precomputed'``, the input should
be the dissimilarity ma... | fit_transform | python | scikit-learn/scikit-learn | sklearn/manifold/_mds.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_mds.py | BSD-3-Clause |
def _graph_connected_component(graph, node_id):
"""Find the largest graph connected components that contains one
given node.
Parameters
----------
graph : array-like of shape (n_samples, n_samples)
Adjacency matrix of the graph, non-zero weight means an edge
between the nodes.
... | Find the largest graph connected components that contains one
given node.
Parameters
----------
graph : array-like of shape (n_samples, n_samples)
Adjacency matrix of the graph, non-zero weight means an edge
between the nodes.
node_id : int
The index of the query node of th... | _graph_connected_component | python | scikit-learn/scikit-learn | sklearn/manifold/_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_spectral_embedding.py | BSD-3-Clause |
def _graph_is_connected(graph):
"""Return whether the graph is connected (True) or Not (False).
Parameters
----------
graph : {array-like, sparse matrix} of shape (n_samples, n_samples)
Adjacency matrix of the graph, non-zero weight means an edge
between the nodes.
Returns
----... | Return whether the graph is connected (True) or Not (False).
Parameters
----------
graph : {array-like, sparse matrix} of shape (n_samples, n_samples)
Adjacency matrix of the graph, non-zero weight means an edge
between the nodes.
Returns
-------
is_connected : bool
Tru... | _graph_is_connected | python | scikit-learn/scikit-learn | sklearn/manifold/_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_spectral_embedding.py | BSD-3-Clause |
def _set_diag(laplacian, value, norm_laplacian):
"""Set the diagonal of the laplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition.
Parameters
----------
laplacian : {ndarray, sparse matrix}
The graph laplacian.
value : float
The value of th... | Set the diagonal of the laplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition.
Parameters
----------
laplacian : {ndarray, sparse matrix}
The graph laplacian.
value : float
The value of the diagonal.
norm_laplacian : bool
Whether t... | _set_diag | python | scikit-learn/scikit-learn | sklearn/manifold/_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_spectral_embedding.py | BSD-3-Clause |
def spectral_embedding(
adjacency,
*,
n_components=8,
eigen_solver=None,
random_state=None,
eigen_tol="auto",
norm_laplacian=True,
drop_first=True,
):
"""Project the sample on the first eigenvectors of the graph Laplacian.
The adjacency matrix is used to compute a normalized gra... | Project the sample on the first eigenvectors of the graph Laplacian.
The adjacency matrix is used to compute a normalized graph Laplacian
whose spectrum (especially the eigenvectors associated to the
smallest eigenvalues) has an interpretation in terms of minimal
number of cuts necessary to split the g... | spectral_embedding | python | scikit-learn/scikit-learn | sklearn/manifold/_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_spectral_embedding.py | BSD-3-Clause |
def _get_affinity_matrix(self, X, Y=None):
"""Calculate the affinity matrix from data
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples
and `n_features` is the number of features.
... | Calculate the affinity matrix from data
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples
and `n_features` is the number of features.
If affinity is "precomputed"
X : ... | _get_affinity_matrix | python | scikit-learn/scikit-learn | sklearn/manifold/_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_spectral_embedding.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the model from data in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples
and `n_features` is the number of features.
... | Fit the model from data in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where `n_samples` is the number of samples
and `n_features` is the number of features.
If affinity is "precomputed"
... | fit | python | scikit-learn/scikit-learn | sklearn/manifold/_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_spectral_embedding.py | BSD-3-Clause |
def _kl_divergence(
params,
P,
degrees_of_freedom,
n_samples,
n_components,
skip_num_points=0,
compute_error=True,
):
"""t-SNE objective function: gradient of the KL divergence
of p_ijs and q_ijs and the absolute error.
Parameters
----------
params : ndarray of shape (n_... | t-SNE objective function: gradient of the KL divergence
of p_ijs and q_ijs and the absolute error.
Parameters
----------
params : ndarray of shape (n_params,)
Unraveled embedding.
P : ndarray of shape (n_samples * (n_samples-1) / 2,)
Condensed joint probability matrix.
degrees... | _kl_divergence | python | scikit-learn/scikit-learn | sklearn/manifold/_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_t_sne.py | BSD-3-Clause |
def _kl_divergence_bh(
params,
P,
degrees_of_freedom,
n_samples,
n_components,
angle=0.5,
skip_num_points=0,
verbose=False,
compute_error=True,
num_threads=1,
):
"""t-SNE objective function: KL divergence of p_ijs and q_ijs.
Uses Barnes-Hut tree methods to calculate the ... | t-SNE objective function: KL divergence of p_ijs and q_ijs.
Uses Barnes-Hut tree methods to calculate the gradient that
runs in O(NlogN) instead of O(N^2).
Parameters
----------
params : ndarray of shape (n_params,)
Unraveled embedding.
P : sparse matrix of shape (n_samples, n_sample)... | _kl_divergence_bh | python | scikit-learn/scikit-learn | sklearn/manifold/_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_t_sne.py | BSD-3-Clause |
def _gradient_descent(
objective,
p0,
it,
max_iter,
n_iter_check=1,
n_iter_without_progress=300,
momentum=0.8,
learning_rate=200.0,
min_gain=0.01,
min_grad_norm=1e-7,
verbose=0,
args=None,
kwargs=None,
):
"""Batch gradient descent with momentum and individual gain... | Batch gradient descent with momentum and individual gains.
Parameters
----------
objective : callable
Should return a tuple of cost and gradient for a given parameter
vector. When expensive to compute, the cost can optionally
be None and can be computed every n_iter_check steps usin... | _gradient_descent | python | scikit-learn/scikit-learn | sklearn/manifold/_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_t_sne.py | BSD-3-Clause |
def trustworthiness(X, X_embedded, *, n_neighbors=5, metric="euclidean"):
r"""Indicate to what extent the local structure is retained.
The trustworthiness is within [0, 1]. It is defined as
.. math::
T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1}
\sum_{j \in \mathcal{N}_{i}^{k}} \... | Indicate to what extent the local structure is retained.
The trustworthiness is within [0, 1]. It is defined as
.. math::
T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1}
\sum_{j \in \mathcal{N}_{i}^{k}} \max(0, (r(i, j) - k))
where for each sample i, :math:`\mathcal{N}_{i}^{k}` ar... | trustworthiness | python | scikit-learn/scikit-learn | sklearn/manifold/_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_t_sne.py | BSD-3-Clause |
def _fit(self, X, skip_num_points=0):
"""Private function to fit the model using X as training data."""
if isinstance(self.init, str) and self.init == "pca" and issparse(X):
raise TypeError(
"PCA initialization is currently not supported "
"with the sparse in... | Private function to fit the model using X as training data. | _fit | python | scikit-learn/scikit-learn | sklearn/manifold/_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_t_sne.py | BSD-3-Clause |
def fit_transform(self, X, y=None):
"""Fit X into an embedded space and return that transformed output.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples)
If the metric is 'precomputed' X must be a s... | Fit X into an embedded space and return that transformed output.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
If the metric is 'precomputed' X must be a square distance
matrix. Otherwise it c... | fit_transform | python | scikit-learn/scikit-learn | sklearn/manifold/_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/_t_sne.py | BSD-3-Clause |
def test_isomap_fitted_attributes_dtype(global_dtype):
"""Check that the fitted attributes are stored accordingly to the
data type of X."""
iso = manifold.Isomap(n_neighbors=2)
X = np.array([[1, 2], [3, 4], [5, 6]], dtype=global_dtype)
iso.fit(X)
assert iso.dist_matrix_.dtype == global_dtype
... | Check that the fitted attributes are stored accordingly to the
data type of X. | test_isomap_fitted_attributes_dtype | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_isomap.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_isomap.py | BSD-3-Clause |
def test_isomap_dtype_equivalence():
"""Check the equivalence of the results with 32 and 64 bits input."""
iso_32 = manifold.Isomap(n_neighbors=2)
X_32 = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32)
iso_32.fit(X_32)
iso_64 = manifold.Isomap(n_neighbors=2)
X_64 = np.array([[1, 2], [3, 4]... | Check the equivalence of the results with 32 and 64 bits input. | test_isomap_dtype_equivalence | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_isomap.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_isomap.py | BSD-3-Clause |
def test_normed_stress(k):
"""Test that non-metric MDS normalized stress is scale-invariant."""
sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]])
X1, stress1 = mds.smacof(sim, metric=False, max_iter=5, random_state=0)
X2, stress2 = mds.smacof(k * sim, metric=False, max_iter=5, ra... | Test that non-metric MDS normalized stress is scale-invariant. | test_normed_stress | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_mds.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_mds.py | BSD-3-Clause |
def _assert_equal_with_sign_flipping(A, B, tol=0.0):
"""Check array A and B are equal with possible sign flipping on
each column"""
tol_squared = tol**2
for A_col, B_col in zip(A.T, B.T):
assert (
np.max((A_col - B_col) ** 2) <= tol_squared
or np.max((A_col + B_col) ** 2)... | Check array A and B are equal with possible sign flipping on
each column | _assert_equal_with_sign_flipping | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_spectral_embedding.py | BSD-3-Clause |
def test_spectral_embedding_preserves_dtype(eigen_solver, dtype):
"""Check that `SpectralEmbedding is preserving the dtype of the fitted
attribute and transformed data.
Ideally, this test should be covered by the common test
`check_transformer_preserve_dtypes`. However, this test only run
with tran... | Check that `SpectralEmbedding is preserving the dtype of the fitted
attribute and transformed data.
Ideally, this test should be covered by the common test
`check_transformer_preserve_dtypes`. However, this test only run
with transformers implementing `transform` while `SpectralEmbedding`
implement... | test_spectral_embedding_preserves_dtype | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_spectral_embedding.py | BSD-3-Clause |
def test_spectral_eigen_tol_auto(monkeypatch, solver, csr_container):
"""Test that `eigen_tol="auto"` is resolved correctly"""
if solver == "amg" and not pyamg_available:
pytest.skip("PyAMG is not available.")
X, _ = make_blobs(
n_samples=200, random_state=0, centers=[[1, 1], [-1, -1]], clus... | Test that `eigen_tol="auto"` is resolved correctly | test_spectral_eigen_tol_auto | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_spectral_embedding.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_spectral_embedding.py | BSD-3-Clause |
def test_trustworthiness_n_neighbors_error():
"""Raise an error when n_neighbors >= n_samples / 2.
Non-regression test for #18567.
"""
regex = "n_neighbors .+ should be less than .+"
rng = np.random.RandomState(42)
X = rng.rand(7, 4)
X_embedded = rng.rand(7, 2)
with pytest.raises(ValueE... | Raise an error when n_neighbors >= n_samples / 2.
Non-regression test for #18567.
| test_trustworthiness_n_neighbors_error | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py | BSD-3-Clause |
def test_optimization_minimizes_kl_divergence():
"""t-SNE should give a lower KL divergence with more iterations."""
random_state = check_random_state(0)
X, _ = make_blobs(n_features=3, random_state=random_state)
kl_divergences = []
for max_iter in [250, 300, 350]:
tsne = TSNE(
n... | t-SNE should give a lower KL divergence with more iterations. | test_optimization_minimizes_kl_divergence | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py | BSD-3-Clause |
def test_sparse_precomputed_distance(sparse_container):
"""Make sure that TSNE works identically for sparse and dense matrix"""
random_state = check_random_state(0)
X = random_state.randn(100, 2)
D_sparse = kneighbors_graph(X, n_neighbors=100, mode="distance", include_self=True)
D = pairwise_distan... | Make sure that TSNE works identically for sparse and dense matrix | test_sparse_precomputed_distance | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py | BSD-3-Clause |
def test_uniform_grid(method):
"""Make sure that TSNE can approximately recover a uniform 2D grid
Due to ties in distances between point in X_2d_grid, this test is platform
dependent for ``method='barnes_hut'`` due to numerical imprecision.
Also, t-SNE is not assured to converge to the right solution ... | Make sure that TSNE can approximately recover a uniform 2D grid
Due to ties in distances between point in X_2d_grid, this test is platform
dependent for ``method='barnes_hut'`` due to numerical imprecision.
Also, t-SNE is not assured to converge to the right solution because bad
initialization can lea... | test_uniform_grid | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.py | BSD-3-Clause |
def test_tsne_with_different_distance_metrics(metric, dist_func, method):
"""Make sure that TSNE works for different distance metrics"""
if method == "barnes_hut" and metric == "manhattan":
# The distances computed by `manhattan_distances` differ slightly from those
# computed internally by Nea... | Make sure that TSNE works for different distance metrics | test_tsne_with_different_distance_metrics | python | scikit-learn/scikit-learn | sklearn/manifold/tests/test_t_sne.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/tests/test_t_sne.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.