Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

slim.py 5.7 KB

You have to be logged in to leave a comment. Sign In
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
  1. '''
  2. Wrapper for sparse, integer linear models.
  3. minimizes norm(X * w - y, 2) + alpha * norm(w, 1)
  4. with integer coefficients in w
  5. Requires installation of a solver for mixed-integer linear programs, e.g. gurobi, mosek, or cplex
  6. '''
  7. import warnings
  8. import numpy as np
  9. from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
  10. from sklearn.linear_model import LinearRegression, Lasso, LogisticRegression
  11. from sklearn.utils.multiclass import check_classification_targets
  12. from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
  13. class SLIMRegressor(BaseEstimator, RegressorMixin):
  14. '''Sparse integer linear model
  15. Params
  16. ------
  17. alpha: float
  18. weight for sparsity penalty
  19. '''
  20. def __init__(self, alpha=0.01):
  21. self.alpha = alpha
  22. def fit(self, X, y, sample_weight=None):
  23. '''fit a linear model with integer coefficient and L1 regularization.
  24. In case the optimization fails, fit lasso and round coefs.
  25. Params
  26. ------
  27. _sample_weight: np.ndarray (n,), optional
  28. weight for each individual sample
  29. '''
  30. X, y = check_X_y(X, y)
  31. self.n_features_in_ = X.shape[1]
  32. self.model_ = LinearRegression()
  33. try:
  34. import cvxpy as cp # package for optimization, import here to make it optional
  35. from cvxpy.error import SolverError
  36. # declare the integer-valued optimization variable
  37. w = cp.Variable(X.shape[1], integer=True)
  38. # set up the minimization problem
  39. residuals = X @ w - y
  40. if sample_weight is not None:
  41. residuals = cp.multiply(sample_weight, residuals)
  42. mse = cp.sum_squares(residuals)
  43. l1_penalty = self.alpha * cp.norm(w, 1)
  44. obj = cp.Minimize(mse + l1_penalty)
  45. prob = cp.Problem(obj)
  46. try:
  47. # solve the problem using an appropriate solver
  48. prob.solve()
  49. self.model_.coef_ = w.value.astype(int)
  50. self.model_.intercept_ = 0
  51. except SolverError:
  52. warnings.warn("gurobi, mosek, or cplex solver required for mixed-integer "
  53. "quadratic programming. Rounding non-integer coefficients instead.")
  54. self._fit_backup(X, y, sample_weight)
  55. except ImportError:
  56. warnings.warn("Should install cvxpy with pip install cvxpy. Rounding non-integer "
  57. "coefficients instead.")
  58. self._fit_backup(X, y, sample_weight)
  59. return self
  60. def _fit_backup(self, X, y, sample_weight):
  61. m = Lasso(alpha=self.alpha)
  62. m.fit(X, y, sample_weight=sample_weight)
  63. self.model_.coef_ = np.round(m.coef_).astype(int)
  64. self.model_.intercept_ = m.intercept_
  65. def predict(self, X):
  66. check_is_fitted(self)
  67. X = check_array(X)
  68. return self.model_.predict(X)
  69. class SLIMClassifier(BaseEstimator, ClassifierMixin):
  70. def __init__(self, alpha=1):
  71. '''Model is initialized during fitting
  72. Params
  73. ------
  74. alpha: float
  75. weight for sparsity penalty
  76. '''
  77. self.alpha = alpha
  78. def fit(self, X, y, sample_weight=None):
  79. '''fit a logistic model with integer coefficient and L1 regularization.
  80. In case the optimization fails, fit lasso and round coefs.
  81. Params
  82. ------
  83. _sample_weight: np.ndarray (n,), optional
  84. weight for each individual sample
  85. '''
  86. X, y = check_X_y(X, y)
  87. check_classification_targets(y)
  88. self.n_features_in_ = X.shape[1]
  89. self.classes_, y = np.unique(y, return_inverse=True) # deals with str inputs
  90. self.model_ = LogisticRegression()
  91. self.model_.classes_ = self.classes_
  92. try:
  93. import cvxpy as cp # package for optimization, import here to make it optional
  94. from cvxpy.error import SolverError
  95. # declare the integer-valued optimization variable
  96. w = cp.Variable(X.shape[1], integer=True)
  97. # set up the minimization problem
  98. logits = -X @ w
  99. residuals = cp.multiply(1 - y, logits) - cp.logistic(logits)
  100. if sample_weight is not None:
  101. residuals = cp.multiply(sample_weight, residuals)
  102. celoss = -cp.sum(residuals)
  103. l1_penalty = self.alpha * cp.norm(w, 1)
  104. obj = cp.Minimize(celoss + l1_penalty)
  105. prob = cp.Problem(obj)
  106. try:
  107. # solve the problem using an appropriate solver
  108. prob.solve()
  109. self.model_.coef_ = np.array([w.value.astype(int)])
  110. self.model_.intercept_ = 0
  111. except SolverError:
  112. warnings.warn("mosek solver required for mixed-integer exponential cone "
  113. "programming. Rounding non-integer coefficients instead")
  114. self._fit_backup(X, y, sample_weight)
  115. except ImportError:
  116. warnings.warn("Should install cvxpy with pip install cvxpy. Rounding non-integer "
  117. "coefficients instead.")
  118. self._fit_backup(X, y, sample_weight)
  119. return self
  120. def _fit_backup(self, X, y, sample_weight=None):
  121. m = LogisticRegression(C=1 / self.alpha)
  122. m.fit(X, y, sample_weight=sample_weight)
  123. self.model_.coef_ = np.round(m.coef_).astype(int)
  124. self.model_.intercept_ = m.intercept_
  125. def predict(self, X):
  126. check_is_fitted(self)
  127. X = check_array(X)
  128. return self.model_.predict(X)
  129. def predict_proba(self, X):
  130. check_is_fitted(self)
  131. X = check_array(X)
  132. return self.model_.predict_proba(X)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...