-
Notifications
You must be signed in to change notification settings - Fork 0
/
lbfgs_nnls.py
43 lines (30 loc) · 1.18 KB
/
lbfgs_nnls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# (C) Mathieu Blondel 2012
import numpy as np
from scipy.optimize import fmin_l_bfgs_b
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.utils.extmath import safe_sparse_dot
class LbfgsNNLS(BaseEstimator, RegressorMixin):
def __init__(self, tol=1e-6, callback=None):
self.tol = tol
self.callback = callback
def fit(self, X, y):
n_features = X.shape[1]
def f(w, *args):
return np.sum(np.power((safe_sparse_dot(X, w) - y), 2))
def fprime(w, *args):
if self.callback is not None:
self.coef_ = w
self.callback(self)
return 2 * np.ravel(safe_sparse_dot(X.T, (safe_sparse_dot(X, w) - y).T))
coef0 = np.zeros(n_features, dtype=np.float64)
w, f, d = fmin_l_bfgs_b(f, x0=coef0, fprime=fprime, pgtol=self.tol,
bounds=[(0, None)] * n_features)
self.coef_ = w
return self
def n_nonzero(self, percentage=False):
nz = np.sum(self.coef_ != 0)
if percentage:
nz /= float(self.coef_.shape[0])
return nz
def predict(self, X):
return safe_sparse_dot(X, self.coef_)