Skip to content

Commit 6b4f824

Browse files
authored
FIX ElasticNet.fit does not modify sample_weight in place (scikit-learn#19055)
1 parent 3cdfb56 commit 6b4f824

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

doc/whats_new/v1.0.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ Changelog
5656
in multicore settings. :pr:`19052` by
5757
:user:`Yusuke Nagasaka <YusukeNagasaka>`.
5858

59+
:mod:`sklearn.linear_model`
60+
...........................
61+
62+
- |Fix| :meth:`ElasticNet.fit` no longer modifies `sample_weight` in place.
63+
:pr:`19055` by `Thomas Fan`_.
64+
5965
Code and Documentation Contributors
6066
-----------------------------------
6167

sklearn/linear_model/_coordinate_descent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -790,7 +790,7 @@ def fit(self, X, y, sample_weight=None, check_input=True):
790790
dtype=X.dtype)
791791
# simplify things by rescaling sw to sum up to n_samples
792792
# => np.average(x, weights=sw) = np.mean(sw * x)
793-
sample_weight *= (n_samples / np.sum(sample_weight))
793+
sample_weight = sample_weight * (n_samples / np.sum(sample_weight))
794794
# Objective function is:
795795
# 1/2 * np.average(squared error, weights=sw) + alpha * penalty
796796
# but coordinate descent minimizes:

sklearn/linear_model/tests/test_coordinate_descent.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1214,3 +1214,22 @@ def test_linear_models_cv_fit_for_all_backends(backend, estimator):
12141214

12151215
with joblib.parallel_backend(backend=backend):
12161216
estimator(n_jobs=2, cv=3).fit(X, y)
1217+
1218+
1219+
@pytest.mark.parametrize("check_input", [True, False])
1220+
def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input):
1221+
"""Check that ElasticNet does not overwrite sample_weights."""
1222+
1223+
rng = np.random.RandomState(0)
1224+
n_samples, n_features = 10, 5
1225+
1226+
X = rng.rand(n_samples, n_features)
1227+
y = rng.rand(n_samples)
1228+
1229+
sample_weight_1_25 = 1.25 * np.ones_like(y)
1230+
sample_weight = sample_weight_1_25.copy()
1231+
1232+
reg = ElasticNet()
1233+
reg.fit(X, y, sample_weight=sample_weight, check_input=check_input)
1234+
1235+
assert_array_equal(sample_weight, sample_weight_1_25)

0 commit comments

Comments
 (0)