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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
|
- '''
- Wrapper for sparse, integer linear models.
- minimizes norm(X * w - y, 2) + alpha * norm(w, 1)
- with integer coefficients in w
- Requires installation of a solver for mixed-integer linear programs, e.g. gurobi, mosek, or cplex
- '''
- import warnings
- import numpy as np
- from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
- from sklearn.linear_model import LinearRegression, Lasso, LogisticRegression
- from sklearn.utils.multiclass import check_classification_targets
- from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
- class SLIMRegressor(BaseEstimator, RegressorMixin):
- '''Sparse integer linear model
- Params
- ------
- alpha: float
- weight for sparsity penalty
- '''
- def __init__(self, alpha=0.01):
- self.alpha = alpha
- def fit(self, X, y, sample_weight=None):
- '''fit a linear model with integer coefficient and L1 regularization.
- In case the optimization fails, fit lasso and round coefs.
-
- Params
- ------
- _sample_weight: np.ndarray (n,), optional
- weight for each individual sample
- '''
- X, y = check_X_y(X, y)
- self.n_features_in_ = X.shape[1]
- self.model_ = LinearRegression()
- try:
- import cvxpy as cp # package for optimization, import here to make it optional
- from cvxpy.error import SolverError
- # declare the integer-valued optimization variable
- w = cp.Variable(X.shape[1], integer=True)
- # set up the minimization problem
- residuals = X @ w - y
- if sample_weight is not None:
- residuals = cp.multiply(sample_weight, residuals)
- mse = cp.sum_squares(residuals)
- l1_penalty = self.alpha * cp.norm(w, 1)
- obj = cp.Minimize(mse + l1_penalty)
- prob = cp.Problem(obj)
- try:
- # solve the problem using an appropriate solver
- prob.solve()
- self.model_.coef_ = w.value.astype(int)
- self.model_.intercept_ = 0
- except SolverError:
- warnings.warn("gurobi, mosek, or cplex solver required for mixed-integer "
- "quadratic programming. Rounding non-integer coefficients instead.")
- self._fit_backup(X, y, sample_weight)
-
- except ImportError:
- warnings.warn("Should install cvxpy with pip install cvxpy. Rounding non-integer "
- "coefficients instead.")
- self._fit_backup(X, y, sample_weight)
- return self
-
- def _fit_backup(self, X, y, sample_weight):
- m = Lasso(alpha=self.alpha)
- m.fit(X, y, sample_weight=sample_weight)
- self.model_.coef_ = np.round(m.coef_).astype(int)
- self.model_.intercept_ = m.intercept_
- def predict(self, X):
- check_is_fitted(self)
- X = check_array(X)
- return self.model_.predict(X)
- class SLIMClassifier(BaseEstimator, ClassifierMixin):
- def __init__(self, alpha=1):
- '''Model is initialized during fitting
- Params
- ------
- alpha: float
- weight for sparsity penalty
- '''
- self.alpha = alpha
- def fit(self, X, y, sample_weight=None):
- '''fit a logistic model with integer coefficient and L1 regularization.
- In case the optimization fails, fit lasso and round coefs.
-
- Params
- ------
- _sample_weight: np.ndarray (n,), optional
- weight for each individual sample
- '''
- X, y = check_X_y(X, y)
- check_classification_targets(y)
- self.n_features_in_ = X.shape[1]
- self.classes_, y = np.unique(y, return_inverse=True) # deals with str inputs
- self.model_ = LogisticRegression()
- self.model_.classes_ = self.classes_
- try:
- import cvxpy as cp # package for optimization, import here to make it optional
- from cvxpy.error import SolverError
- # declare the integer-valued optimization variable
- w = cp.Variable(X.shape[1], integer=True)
- # set up the minimization problem
- logits = -X @ w
- residuals = cp.multiply(1 - y, logits) - cp.logistic(logits)
- if sample_weight is not None:
- residuals = cp.multiply(sample_weight, residuals)
- celoss = -cp.sum(residuals)
- l1_penalty = self.alpha * cp.norm(w, 1)
- obj = cp.Minimize(celoss + l1_penalty)
- prob = cp.Problem(obj)
- try:
- # solve the problem using an appropriate solver
- prob.solve()
- self.model_.coef_ = np.array([w.value.astype(int)])
- self.model_.intercept_ = 0
- except SolverError:
- warnings.warn("mosek solver required for mixed-integer exponential cone "
- "programming. Rounding non-integer coefficients instead")
- self._fit_backup(X, y, sample_weight)
- except ImportError:
- warnings.warn("Should install cvxpy with pip install cvxpy. Rounding non-integer "
- "coefficients instead.")
- self._fit_backup(X, y, sample_weight)
-
- return self
- def _fit_backup(self, X, y, sample_weight=None):
- m = LogisticRegression(C=1 / self.alpha)
- m.fit(X, y, sample_weight=sample_weight)
- self.model_.coef_ = np.round(m.coef_).astype(int)
- self.model_.intercept_ = m.intercept_
- def predict(self, X):
- check_is_fitted(self)
- X = check_array(X)
- return self.model_.predict(X)
- def predict_proba(self, X):
- check_is_fitted(self)
- X = check_array(X)
- return self.model_.predict_proba(X)
|