-
Notifications
You must be signed in to change notification settings - Fork 34
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
Solver - add a wrapper for scipy
L-BFGS solver
#165
Merged
mathurinm
merged 13 commits into
scikit-learn-contrib:main
from
Badr-MOUFAD:bfgs-wrapper
Jun 12, 2023
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0704506
init commit
Badr-MOUFAD 7e36421
bfgs wrapper implem
Badr-MOUFAD 0fdbcde
implement L2 penalty
Badr-MOUFAD c75b21f
gradient of logistic
Badr-MOUFAD d6358e1
unittest against scikit learn
Badr-MOUFAD ebbf0bc
fix verbosity and p_pbj computation
Badr-MOUFAD 92d6eda
BFGS --> L-BFGS
Badr-MOUFAD c130ca3
add convergence warning
Badr-MOUFAD 7161dcc
add to docs
Badr-MOUFAD 5e3afdb
cleanups
Badr-MOUFAD 63b3ad0
L2 to doc
Badr-MOUFAD eae3b81
cleanups tests
Badr-MOUFAD 251865e
lexicographic order
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 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 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 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 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 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 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,92 @@ | ||
import warnings | ||
from sklearn.exceptions import ConvergenceWarning | ||
|
||
import numpy as np | ||
import scipy.optimize | ||
from numpy.linalg import norm | ||
|
||
from skglm.solvers import BaseSolver | ||
|
||
|
||
class LBFGS(BaseSolver): | ||
"""A wrapper for scipy L-BFGS solver. | ||
|
||
Refer to `scipy L-BFGS-B <https://docs.scipy.org/doc/scipy/reference/optimize. | ||
minimize-lbfgsb.html#optimize-minimize-lbfgsb>`_ documentation for details. | ||
|
||
Parameters | ||
---------- | ||
max_iter : int, default 20 | ||
Maximum number of iterations. | ||
|
||
tol : float, default 1e-4 | ||
Tolerance for convergence. | ||
|
||
verbose : bool, default False | ||
Amount of verbosity. 0/False is silent. | ||
""" | ||
|
||
def __init__(self, max_iter=50, tol=1e-4, verbose=False): | ||
self.max_iter = max_iter | ||
self.tol = tol | ||
self.verbose = verbose | ||
|
||
def solve(self, X, y, datafit, penalty, w_init=None, Xw_init=None): | ||
|
||
def objective_function(w): | ||
Xw = X @ w | ||
datafit_value = datafit.value(y, w, Xw) | ||
penalty_value = penalty.value(w) | ||
|
||
return datafit_value + penalty_value | ||
|
||
def jacobian_function(w): | ||
Xw = X @ w | ||
datafit_grad = datafit.gradient(X, y, Xw) | ||
penalty_grad = penalty.gradient(w) | ||
|
||
return datafit_grad + penalty_grad | ||
|
||
def callback_post_iter(w_k): | ||
# save p_obj | ||
p_obj = objective_function(w_k) | ||
p_objs_out.append(p_obj) | ||
|
||
if self.verbose: | ||
grad = jacobian_function(w_k) | ||
stop_crit = norm(grad) | ||
|
||
it = len(p_objs_out) | ||
print( | ||
f"Iteration {it}: {p_obj:.10f}, " | ||
f"stopping crit: {stop_crit:.2e}" | ||
) | ||
|
||
n_features = X.shape[1] | ||
w = np.zeros(n_features) if w_init is None else w_init | ||
p_objs_out = [] | ||
|
||
result = scipy.optimize.minimize( | ||
fun=objective_function, | ||
jac=jacobian_function, | ||
x0=w, | ||
method="L-BFGS-B", | ||
options=dict( | ||
maxiter=self.max_iter, | ||
gtol=self.tol | ||
), | ||
callback=callback_post_iter, | ||
) | ||
|
||
if not result.success: | ||
warnings.warn( | ||
f"`LBFGS` did not converge for tol={self.tol:.3e} " | ||
f"and max_iter={self.max_iter}.\n" | ||
"Consider increasing `max_iter` and/or `tol`.", | ||
category=ConvergenceWarning | ||
) | ||
|
||
w = result.x | ||
stop_crit = norm(result.jac) | ||
|
||
return w, np.asarray(p_objs_out), stop_crit |
This file contains 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,40 @@ | ||
import numpy as np | ||
|
||
from skglm.solvers import LBFGS | ||
from skglm.penalties import L2 | ||
from skglm.datafits import Logistic | ||
|
||
from sklearn.linear_model import LogisticRegression | ||
|
||
from skglm.utils.data import make_correlated_data | ||
from skglm.utils.jit_compilation import compiled_clone | ||
|
||
|
||
def test_lbfgs_L2_logreg(): | ||
reg = 1. | ||
n_samples, n_features = 50, 10 | ||
|
||
X, y, _ = make_correlated_data( | ||
n_samples, n_features, random_state=0) | ||
y = np.sign(y) | ||
|
||
# fit L-BFGS | ||
datafit = compiled_clone(Logistic()) | ||
penalty = compiled_clone(L2(reg)) | ||
w, *_ = LBFGS().solve(X, y, datafit, penalty) | ||
|
||
# fit scikit learn | ||
estimator = LogisticRegression( | ||
penalty='l2', | ||
C=1 / (n_samples * reg), | ||
fit_intercept=False | ||
) | ||
estimator.fit(X, y) | ||
|
||
np.testing.assert_allclose( | ||
w, estimator.coef_.flatten(), atol=1e-4 | ||
) | ||
|
||
|
||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe this is quite small, is it enough on a 1000 x 1000 dataset for example?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
50?