-
Notifications
You must be signed in to change notification settings - Fork 42
[READY] ENH - Add Gram Solver for single task Quadratic datafit #59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Badr-MOUFAD
merged 27 commits into
scikit-learn-contrib:main
from
Badr-MOUFAD:gram-solver
Aug 26, 2022
Merged
Changes from 6 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
b8fd539
init commit
Badr-MOUFAD c2aecba
gram solver && unit test
Badr-MOUFAD 507fc8a
fix bug gram solver && tighten test
Badr-MOUFAD c9b64c2
add anderson acceleration
Badr-MOUFAD 20c1911
bug ``stop_criter`` && refactor
Badr-MOUFAD f2e985d
refactoring of var names
Badr-MOUFAD 2dbc8e4
handle ``w_init``
Badr-MOUFAD 8ca7a41
refactor ``_gram_cd_``
Badr-MOUFAD 3453233
gram epoch greedy and cyclic strategy
Badr-MOUFAD 8d3dbc1
extend to sparse case && unitest
Badr-MOUFAD cdd7e34
one implementation of _gram_cd && unittest
Badr-MOUFAD f4bfeaf
greedy_cd arg instead of cd_strategy
Badr-MOUFAD 95cf1d4
Merge branch 'main' of https://github.com/scikit-learn-contrib/skglm …
Badr-MOUFAD 4c0acca
add docs
Badr-MOUFAD dcab054
script fast gram, not faster than scipy
mathurinm e8bc96e
fast gram timing
Badr-MOUFAD 61a67c4
keep grads instead
Badr-MOUFAD 1b6c169
refactor ``chosen_j``
Badr-MOUFAD c9c5575
script to profile
Badr-MOUFAD 68a0458
potential improvements, docstring
mathurinm 3788cc4
warnings.warn arguments in correct order
mathurinm 1ce391d
cleanups: ann files
Badr-MOUFAD 2476a34
fix ``p_obj`` computation
Badr-MOUFAD 0f766e9
Merge branch 'main' of https://github.com/scikit-learn-contrib/skglm …
Badr-MOUFAD 3208dfa
typos + less cases in test, smaller X in tests
mathurinm 16f6ee4
typo: ``XtXw`` --> ``grad``
Badr-MOUFAD e9b7224
Merge branch 'gram-solver' of https://github.com/Badr-MOUFAD/skglm in…
Badr-MOUFAD File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import numpy as np | ||
| from numba import njit | ||
| from skglm.utils import AndersonAcceleration | ||
|
|
||
|
|
||
| def gram_cd_solver(X, y, penalty, max_iter=20, use_acc=True, tol=1e-4, verbose=False): | ||
| """Run coordinate descent while keeping the gradients up-to-date with Gram updates. | ||
|
|
||
| Minimize:: | ||
| 1 / (2*n_samples) * norm(y - Xw)**2 + penalty(w) | ||
|
|
||
| Which can be rewritten as:: | ||
| w.T @ Q @ w / (2*n_samples) - q.T @ w / n_samples + penalty(w) | ||
|
|
||
| where:: | ||
| Q = X.T @ X (gram matrix) | ||
| q = X.T @ y | ||
| """ | ||
| n_samples, n_features = X.shape | ||
| scaled_gram = X.T @ X / n_samples | ||
| scaled_Xty = X.T @ y / n_samples | ||
| scaled_y_norm2 = np.linalg.norm(y) ** 2 / (2 * n_samples) | ||
| all_features = np.arange(n_features) | ||
| stop_crit = np.inf # prevent ref before assign | ||
| p_objs_out = [] | ||
|
|
||
| w = np.zeros(n_features) | ||
Badr-MOUFAD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| scaled_gram_w = np.zeros(n_features) | ||
| opt = penalty.subdiff_distance(w, -scaled_Xty, all_features) # initial: grad = -Xty | ||
Badr-MOUFAD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if use_acc: | ||
mathurinm marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| accelerator = AndersonAcceleration(K=5) | ||
| w_acc = np.zeros(n_features) | ||
| scaled_gram_w_acc = np.zeros(n_features) | ||
|
|
||
| for t in range(max_iter): | ||
| # check convergences | ||
| stop_crit = np.max(opt) | ||
| if verbose: | ||
| p_obj = (0.5 * w @ scaled_gram_w - scaled_Xty @ w + | ||
| scaled_y_norm2 + penalty.value(w)) | ||
| print( | ||
| f"Iteration {t+1}: {p_obj:.10f}, " | ||
| f"stopping crit: {stop_crit:.2e}" | ||
| ) | ||
|
|
||
| if stop_crit <= tol: | ||
| if verbose: | ||
| print(f"Stopping criterion max violation: {stop_crit:.2e}") | ||
| break | ||
|
|
||
| # inplace update of w, XtXw | ||
| opt = _gram_cd_iter(scaled_gram, scaled_Xty, w, scaled_gram_w, penalty, | ||
| all_features, n_updates=n_features) | ||
|
|
||
| # perform anderson extrapolation | ||
Badr-MOUFAD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if use_acc: | ||
| w_acc, scaled_gram_w_acc, is_extrapolated = accelerator.extrapolate( | ||
| w, scaled_gram_w) | ||
|
|
||
| if is_extrapolated: | ||
| p_obj_acc = (0.5 * w_acc @ scaled_gram_w_acc - scaled_Xty @ w_acc + | ||
| penalty.value(w_acc)) | ||
| p_obj = 0.5 * w @ scaled_gram_w - scaled_Xty @ w + penalty.value(w) | ||
| if p_obj_acc < p_obj: | ||
| w[:] = w_acc | ||
| scaled_gram_w[:] = scaled_gram_w_acc | ||
|
|
||
| p_obj = 0.5 * w @ scaled_gram_w - scaled_Xty @ w + penalty.value(w) | ||
| p_objs_out.append(p_obj) | ||
| return w, np.array(p_objs_out), stop_crit | ||
|
|
||
|
|
||
| @njit | ||
| def _gram_cd_iter(scaled_gram, scaled_Xty, w, scaled_gram_w, penalty, ws, n_updates): | ||
| # inplace update of w, XtXw, opt | ||
| # perform greedy cd updates | ||
Badr-MOUFAD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| for _ in range(n_updates): | ||
| grad = scaled_gram_w - scaled_Xty | ||
Badr-MOUFAD marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| opt = penalty.subdiff_distance(w, grad, ws) | ||
| j_max = np.argmax(opt) | ||
|
|
||
| old_w_j = w[j_max] | ||
| step = 1 / scaled_gram[j_max, j_max] # 1 / lipchitz_j | ||
| w[j_max] = penalty.prox_1d(old_w_j - step * grad[j_max], step, j_max) | ||
|
|
||
| # Gram matrix update | ||
| if w[j_max] != old_w_j: | ||
| scaled_gram_w += (w[j_max] - old_w_j) * scaled_gram[:, j_max] | ||
| return opt | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import pytest | ||
| from itertools import product | ||
|
|
||
| import numpy as np | ||
| from numpy.linalg import norm | ||
| from sklearn.linear_model import Lasso | ||
|
|
||
| from skglm.penalties import L1 | ||
| from skglm.solvers.gram_cd import gram_cd_solver | ||
| from skglm.utils import make_correlated_data, compiled_clone | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("n_samples, n_features", | ||
| product([100, 200], [50, 90])) | ||
| def test_alpha_max(n_samples, n_features): | ||
| X, y, _ = make_correlated_data(n_samples, n_features, random_state=0) | ||
| alpha_max = norm(X.T @ y, ord=np.inf) / n_samples | ||
|
|
||
| l1_penalty = compiled_clone(L1(alpha_max)) | ||
| w = gram_cd_solver(X, y, l1_penalty, tol=1e-9, verbose=0)[0] | ||
|
|
||
| np.testing.assert_equal(w, 0) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("n_samples, n_features, rho", | ||
| product([500, 100], [30, 80], [1e-1, 1e-2, 1e-3])) | ||
| def test_vs_lasso_sklearn(n_samples, n_features, rho): | ||
| X, y, _ = make_correlated_data(n_samples, n_features, random_state=0) | ||
| alpha_max = norm(X.T @ y, ord=np.inf) / n_samples | ||
| alpha = rho * alpha_max | ||
|
|
||
| sk_lasso = Lasso(alpha, fit_intercept=False, tol=1e-9) | ||
| sk_lasso.fit(X, y) | ||
|
|
||
| l1_penalty = compiled_clone(L1(alpha)) | ||
| w = gram_cd_solver(X, y, l1_penalty, tol=1e-9, verbose=0, max_iter=1000)[0] | ||
|
|
||
| np.testing.assert_allclose(w, sk_lasso.coef_.flatten(), rtol=1e-7, atol=1e-7) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| pass |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.