-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathimplementations.py
328 lines (235 loc) · 9.03 KB
/
implementations.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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# License: BSD 2-Clause
from sklearn.linear_model import LinearRegression, Ridge, RidgeClassifier, Lasso, ElasticNet, LogisticRegression
from sklearn_pmml_model.base import PMMLBaseRegressor, PMMLBaseClassifier, OneHotEncodingMixin
from sklearn_pmml_model.linear_model.base import PMMLGeneralizedLinearRegressor, PMMLGeneralizedLinearClassifier
from itertools import chain
import numpy as np
class PMMLLinearRegression(OneHotEncodingMixin, PMMLBaseRegressor, LinearRegression):
"""
Ordinary least squares Linear Regression.
The PMML model consists out of a <RegressionModel> element, containing at
least one <RegressionTable> element. Every table element contains a
<NumericPredictor> element for numerical fields and <CategoricalPredictor>
per value of a categorical field, describing the coefficients.
Parameters
----------
pmml : str, object
Filename or file object containing PMML data.
Notes
-----
Specification: http://dmg.org/pmml/v4-3/Regression.html
"""
def __init__(self, pmml):
PMMLBaseRegressor.__init__(self, pmml)
OneHotEncodingMixin.__init__(self)
# Import coefficients and intercepts
model = self.root.find('RegressionModel')
if model is None:
raise Exception('PMML model does not contain RegressionModel.')
tables = model.findall('RegressionTable')
self.coef_ = np.array([
_get_coefficients(self, table)
for table in tables
])
self.intercept_ = np.array([
float(table.get('intercept'))
for table in tables
])
if self.coef_.shape[0] == 1:
self.coef_ = self.coef_[0]
if self.intercept_.shape[0] == 1:
self.intercept_ = self.intercept_[0]
def fit(self, x, y):
return PMMLBaseRegressor.fit(self, x, y)
def _more_tags(self):
return LinearRegression._more_tags(self)
class PMMLLogisticRegression(OneHotEncodingMixin, PMMLBaseClassifier, LogisticRegression):
"""
Logistic Regression (aka logit, MaxEnt) classifier.
The PMML model consists out of a <RegressionModel> element, containing at
least one <RegressionTable> element. Every table element contains a
<NumericPredictor> element for numerical fields and <CategoricalPredictor>
per value of a categorical field, describing the coefficients.
Parameters
----------
pmml : str, object
Filename or file object containing PMML data.
Notes
-----
Specification: http://dmg.org/pmml/v4-3/Regression.html
"""
def __init__(self, pmml):
PMMLBaseClassifier.__init__(self, pmml)
OneHotEncodingMixin.__init__(self)
LogisticRegression.__init__(self)
# Import coefficients and intercepts
model = self.root.find('RegressionModel')
mining_model = self.root.find('MiningModel')
tables = []
if mining_model is not None and self.n_classes_ > 2:
self.multi_class = 'ovr'
segmentation = mining_model.find('Segmentation')
if segmentation.get('multipleModelMethod') not in ['modelChain']:
raise Exception('PMML model for multi-class logistic regression should use modelChain method.')
# Parse segments
segments = segmentation.findall('Segment')
valid_segments = [segment for segment in segments if segment.find('True') is not None]
models = [segment.find('RegressionModel') for segment in valid_segments]
tables = [
models[i].find('RegressionTable') for i in range(self.n_classes_)
]
elif model is not None:
self.multi_class = 'auto'
tables = [
table for table in model.findall('RegressionTable')
if table.find('NumericPredictor') is not None
]
else:
raise Exception('PMML model does not contain RegressionModel or Segmentation.')
self.coef_ = [
_get_coefficients(self, table)
for table in tables
]
self.intercept_ = [
float(table.get('intercept'))
for table in tables
]
if len(self.coef_) == 1:
self.coef_ = [self.coef_[0]]
if len(self.intercept_) == 1:
self.intercept_ = [self.intercept_[0]]
self.coef_ = np.array(self.coef_)
self.intercept_ = np.array(self.intercept_)
self.solver = 'lbfgs'
def fit(self, x, y):
return PMMLBaseClassifier.fit(self, x, y)
def _more_tags(self):
return LogisticRegression._more_tags(self)
def _get_coefficients(est, table):
"""
Obtain coefficients for <RegressionTable> PMML elements.
Parameters
----------
est : PMMLBaseEstimator
Base estimator containing information about `fields` and `field_mapping`.
table : eTree.Element
The <RegressionTable> element which contains the feature coefficients.
"""
def coefficient_for_category(predictors, category):
predictor = [p for p in predictors if p.get('value') == category]
if not predictor:
return 0
return float(predictor[0].get('coefficient'))
def coefficients_for_field(name, field):
predictors = table.findall(f"*[@name='{name}']")
if field.get('optype') != 'categorical':
if len(predictors) > 1:
raise Exception('PMML model is not linear.')
return [float(predictors[0].get('coefficient'))]
return [
coefficient_for_category(predictors, c)
for c in est.field_mapping[name][1].categories
]
return list(chain.from_iterable([
coefficients_for_field(name, field)
for name, field in est.fields.items()
if table.find(f"*[@name='{name}']") is not None
]))
# NOTE: Many of these variants only differ in the training part, not the
# classification part. Hence they are equivalent in terms of parsing.
class PMMLRidge(PMMLGeneralizedLinearRegressor, Ridge):
"""
Linear least squares with l2 regularization.
Minimizes the objective function::
||y - Xw||^2_2 + alpha * ||w||^2_2
This model solves a regression model where the loss function is
the linear least squares function and regularization is given by
the l2-norm. Also known as Ridge Regression or Tikhonov regularization.
This estimator has built-in support for multi-variate regression
(i.e., when y is a 2d-array of shape (n_samples, n_targets)).
Parameters
----------
pmml : str, object
Filename or file object containing PMML data.
Notes
-----
Specification: http://dmg.org/pmml/v4-3/GeneralRegression.html
"""
def fit(self, x, y):
return PMMLGeneralizedLinearRegressor.fit(self, x, y)
def _more_tags(self):
return Ridge._more_tags(self)
class PMMLRidgeClassifier(PMMLGeneralizedLinearClassifier, RidgeClassifier):
"""
Classifier using Ridge regression.
This classifier first converts the target values into ``{-1, 1}`` and
then treats the problem as a regression task (multi-output regression in
the multiclass case).
Parameters
----------
pmml : str, object
Filename or file object containing PMML data.
Notes
-----
Specification: http://dmg.org/pmml/v4-3/GeneralRegression.html
"""
def __init__(self, pmml):
PMMLGeneralizedLinearClassifier.__init__(self, pmml)
RidgeClassifier.__init__(self)
def fit(self, x, y):
return PMMLGeneralizedLinearClassifier.fit(self, x, y)
def _more_tags(self):
return RidgeClassifier._more_tags(self)
class PMMLLasso(PMMLGeneralizedLinearRegressor, Lasso):
"""
Linear Model trained with L1 prior as regularizer (aka the Lasso).
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
Technically the Lasso model is optimizing the same objective function as
the Elastic Net with ``l1_ratio=1.0`` (no L2 penalty).
Parameters
----------
pmml : str, object
Filename or file object containing PMML data.
Notes
-----
Specification: http://dmg.org/pmml/v4-3/GeneralRegression.html
"""
def __init__(self, pmml):
PMMLGeneralizedLinearRegressor.__init__(self, pmml)
self.n_iter_ = 0
def fit(self, x, y):
return PMMLGeneralizedLinearRegressor.fit(self, x, y)
def _more_tags(self):
return Lasso._more_tags(self)
class PMMLElasticNet(PMMLGeneralizedLinearRegressor, ElasticNet):
"""
Linear regression with combined L1 and L2 priors as regularizer.
Minimizes the objective function::
1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
If you are interested in controlling the L1 and L2 penalty
separately, keep in mind that this is equivalent to::
a * ||w||_1 + 0.5 * b * ||w||_2^2
where::
alpha = a + b and l1_ratio = a / (a + b)
The parameter l1_ratio corresponds to alpha in the glmnet R package while
alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio
= 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable,
unless you supply your own sequence of alpha.
Parameters
----------
pmml : str, object
Filename or file object containing PMML data.
Notes
-----
Specification: http://dmg.org/pmml/v4-3/GeneralRegression.html
"""
def __init__(self, pmml):
PMMLGeneralizedLinearRegressor.__init__(self, pmml)
self.n_iter_ = 0
def fit(self, x, y):
return PMMLGeneralizedLinearRegressor.fit(self, x, y)
def _more_tags(self):
return ElasticNet._more_tags(self)