|
1 | 1 | import numpy as np |
2 | 2 | import scipy.sparse as sp |
| 3 | +from scipy.linalg import inv |
3 | 4 |
|
4 | 5 | from sklearn.utils.testing import assert_true |
5 | 6 | from sklearn.utils.testing import assert_almost_equal |
@@ -128,6 +129,33 @@ def test_ridge_sample_weights(): |
128 | 129 | alpha=alpha, solver=solver) |
129 | 130 | assert_array_almost_equal(coefs, coefs2) |
130 | 131 |
|
| 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 | + |
131 | 159 |
|
132 | 160 | def test_ridge_shapes(): |
133 | 161 | """Test shape of coef_ and intercept_ |
|
0 commit comments