Skip to content

Commit aa66938

Browse files
committed
Fixes Issue 2751
1 parent 7c621fc commit aa66938

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

sklearn/linear_model/tests/test_ridge.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import numpy as np
22
import scipy.sparse as sp
3+
from scipy.linalg import inv
34

45
from sklearn.utils.testing import assert_true
56
from sklearn.utils.testing import assert_almost_equal
@@ -128,6 +129,33 @@ def test_ridge_sample_weights():
128129
alpha=alpha, solver=solver)
129130
assert_array_almost_equal(coefs, coefs2)
130131

132+
# Test for fit_intercept = True
133+
est = Ridge(alpha=alpha, solver=solver)
134+
est.fit(X, y, sample_weight=sample_weight)
135+
136+
# Check using Newtons Method
137+
# Quadratic function should be solved in a single step.
138+
newX = np.ones([n_samples, n_features + 1])
139+
coef_ = np.zeros(n_features + 1)
140+
grad = np.zeros(n_features + 1)
141+
newX[:, 1:] = X
142+
sample_weight = np.sqrt(sample_weight)
143+
newX *= sample_weight[:, np.newaxis]
144+
newy = y * sample_weight
145+
146+
# Gradient
147+
grad = np.dot((np.dot(newX, coef_) - newy), newX)
148+
grad[1:] += alpha * coef_[1:]
149+
150+
# Hessian
151+
diag = alpha * np.ones(n_features + 1)
152+
diag[0] = 0.
153+
hess = np.dot(newX.T, newX)
154+
hess.flat[::n_features + 2] += diag
155+
coef_ = coef_ - np.dot(inv(hess), grad)
156+
assert_almost_equal(coef_[0], est.intercept_)
157+
assert_array_almost_equal(coef_[1:], est.coef_)
158+
131159

132160
def test_ridge_shapes():
133161
"""Test shape of coef_ and intercept_

0 commit comments

Comments
 (0)