-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmodels.py
More file actions
1440 lines (1316 loc) · 48.1 KB
/
models.py
File metadata and controls
1440 lines (1316 loc) · 48.1 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Models that can be fitted in Meterstick."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import itertools
from typing import List, Optional, Sequence, Text, Union
from meterstick import metrics
from meterstick import operations
from meterstick import sql
from meterstick import utils
import numpy as np
import pandas as pd
from sklearn import linear_model
class Model(operations.Operation):
"""Base class for model fitting."""
def __init__(
self,
y: Optional[metrics.Metric] = None,
x: Optional[
Union[metrics.Metric, Sequence[metrics.Metric], metrics.MetricList]
] = None,
group_by: Optional[Union[Text, List[Text]]] = None,
model=None,
model_name=None,
where=None,
name=None,
fit_intercept=True,
normalize=False,
additional_fingerprint_attrs: Optional[List[str]] = None,
):
"""Initialize the model.
Args:
y: The Metric whose result will be used as the response variable.
x: The Metrics whose results will be used as the explanatory variables.
group_by: The column(s) to aggregate and compute x and y. The model will
be fit on MetricList([y, x]).compute_on(df, group_by).
model: The model to fit. It's either a sklearn.linear_model or obeys the
API convention, namely, has a method fit(X, y) and attributes
model.coef_ and model.intercept_.
model_name: The name of the model, will be used to auto-generate a name if
name is not given.
where: A string or list of strings to be concatenated that will be passed
to df.query() as a prefilter.
name: The name to use for the model.
fit_intercept: If to include intercept in the model.
normalize: This parameter is ignored when fit_intercept is False. If True,
the regressors X will be normalized before regression by subtracting the
mean and dividing by the l2-norm.
additional_fingerprint_attrs: Additioinal attributes to be encoded into
the fingerprint. See get_fingerprint() for how it's used.
"""
if y and not isinstance(y, metrics.Metric):
raise ValueError('y must be a Metric!')
if y and operations.count_features(y) != 1:
raise ValueError(
'y must be a 1D array but is %iD!' % operations.count_features(y)
)
if isinstance(x, metrics.Metric):
x = [x]
child = None
if x and y:
child = metrics.MetricList([y] + x)
self.model = model
self.model_name = model_name
additional_fingerprint_attrs = (
[additional_fingerprint_attrs]
if isinstance(additional_fingerprint_attrs, str)
else list(additional_fingerprint_attrs or [])
)
self.name_ = None
self.name_tmpl_ = None
super(Model, self).__init__(
child,
None,
group_by,
[],
name=name,
where=where,
additional_fingerprint_attrs=['fit_intercept', 'normalize']
+ additional_fingerprint_attrs,
)
self.fit_intercept = fit_intercept
self.normalize = normalize
def compute(self, df):
x, y = df.iloc[:, 1:], df.iloc[:, 0]
if self.normalize and self.fit_intercept:
x_scaled = x - x.mean()
norms = np.sqrt((x_scaled**2).sum())
x = x_scaled / norms
self.model.fit(x, y)
coef = self.model.coef_
if self.normalize and self.fit_intercept:
coef = coef / norms.values
names = list(df.columns[1:])
if self.fit_intercept:
if self.normalize:
intercept = y.mean() - df.iloc[:, 1:].mean().dot(coef)
else:
intercept = self.model.intercept_
coef = [intercept] + list(coef)
names = ['intercept'] + names
return pd.DataFrame([coef], columns=names)
def compute_through_sql(self, table, split_by, execute, mode):
try:
if mode == 'magic':
if self.where:
table = sql.Sql(None, table, self.where_)
res = self.compute_on_sql_magic_mode(table, split_by, execute)
return utils.apply_name_tmpl(self.name_tmpl, res)
return super(Model, self).compute_through_sql(
table, split_by, execute, mode
)
except NotImplementedError:
raise
except Exception as e: # pylint: disable=broad-except
msg = (
"Please see the root cause of the failure above. If it's caused by"
' the query being too large/complex, you can try '
"compute_on_sql(..., mode='%s')."
)
if mode == 'magic':
raise ValueError(msg % 'mixed') from e
raise ValueError(msg % 'magic') from e
def compute_on_sql_magic_mode(self, table, split_by, execute):
raise NotImplementedError
@property
def y(self):
if not self.children or not isinstance(
self.children[0], metrics.MetricList
):
raise ValueError('y must be a Metric!')
return self.children[0][0]
@property
def x(self):
if not self.children or not isinstance(
self.children[0], metrics.MetricList
):
raise ValueError('x must be a MetricList!')
return metrics.MetricList(self.children[0][1:])
@property
def k(self):
return operations.count_features(self.x)
@property
def name(self):
if self.name_:
return self.name_
if not self.children:
return self.model_name
x_names = [m.name for m in self.x]
return '%s(%s ~ %s)' % (
self.model_name,
self.y.name,
' + '.join(x_names),
)
@name.setter
def name(self, name):
self.name_ = name
@property
def name_tmpl(self):
if self.name_tmpl_:
return self.name_tmpl_
return self.name + ' Coefficient: {}'
@name_tmpl.setter
def name_tmpl(self, name_tmpl):
self.name_tmpl_ = name_tmpl
@property
def group_by(self):
return self.extra_split_by
def __call__(self, child: metrics.Metric):
model = copy.deepcopy(self) if self.children else self
model.children = (child,)
return model
def get_extra_idx(self, return_superset=False):
# Model's extra indexes don't apply to descendants.
return ()
class LinearRegression(Model):
"""A class that can fit a linear regression."""
def __init__(
self,
y: Optional[metrics.Metric] = None,
x: Optional[
Union[metrics.Metric, Sequence[metrics.Metric], metrics.MetricList]
] = None,
group_by: Optional[Union[Text, List[Text]]] = None,
fit_intercept: bool = True,
normalize: bool = False,
where: Optional[str] = None,
name: Optional[str] = None,
):
"""Initialize a sklearn.LinearRegression model."""
model = linear_model.LinearRegression(fit_intercept=fit_intercept)
super(LinearRegression, self).__init__(
y, x, group_by, model, 'OLS', where, name, fit_intercept, normalize
)
def compute_on_sql_magic_mode(self, table, split_by, execute):
return Ridge(
self.y,
self.x,
self.group_by,
0,
self.fit_intercept,
self.normalize,
self.where_,
self.name,
).compute_on_sql_magic_mode(table, split_by, execute)
class Ridge(Model):
"""A class that can fit a ridge regression."""
def __init__(
self,
y: Optional[metrics.Metric] = None,
x: Optional[
Union[metrics.Metric, Sequence[metrics.Metric], metrics.MetricList]
] = None,
group_by: Optional[Union[Text, List[Text]]] = None,
alpha=1,
fit_intercept: bool = True,
normalize: bool = False,
where: Optional[str] = None,
name: Optional[str] = None,
copy_X=True,
max_iter=None,
tol=0.001,
solver='auto',
random_state=None,
):
"""Initialize a sklearn.Ridge model."""
model = linear_model.Ridge(
alpha=alpha,
fit_intercept=fit_intercept,
copy_X=copy_X,
max_iter=max_iter,
tol=tol,
solver=solver,
random_state=random_state,
)
super(Ridge, self).__init__(
y,
x,
group_by,
model,
'Ridge',
where,
name,
fit_intercept,
normalize,
['alpha'],
)
self.alpha = alpha
def compute_on_sql_magic_mode(self, table, split_by, execute):
# Never normalize for the sufficient_stats. Normalization is handled in
# compute_ridge_coefs() instead.
xs, sufficient_stats, _, _ = get_sufficient_stats_elements(
self, table, split_by, execute, normalize=False, include_n_obs=True
)
return apply_algorithm_to_sufficient_stats_elements(
sufficient_stats, split_by, compute_ridge_coefs, xs, self
)
def get_sufficient_stats_elements(
m,
table,
split_by,
execute,
normalize=None,
include_n_obs=False,
):
"""Computes the elements of X'X and X'y.
Args:
m: A Model instance.
table: The table we want to query from.
split_by: The columns that we use to split the data.
execute: A function that can executes a SQL query and returns a DataFrame.
normalize: If to normalize the X. Note that only has effect when
m.fit_intercept is True, which is consistent to sklearn.
include_n_obs: If to include the number of observations in the return.
Returns:
xs: A list of the column names of x1, x2, ...
sufficient_stats_elements: A DataFrame holding all unique elements of
sufficient stats. Each row corresponds to one slice in split_by. The
columns are
split_by,
avg(x0), avg(x1), ..., # if fit_intercept
avg(x0 * x0), avg(x0 * x1), avg(x0 * x2), avg(x1 * x2), ...,
avg(y), # if fit_intercept
avg(x0 * y), avg(x1 * y), ...,
n_observation # if include_n_obs.
The column are named as
split_by, x0, x1,..., x0x0, x0x1,..., y, x0y, x1y,..., n_obs.
avg_x: Nonempty only when normalize. A pd.DataFrame which holds the
avg(x0), avg(x1), ... of the UNNORMALIZED x.
Don't confuse it with the ones in the sufficient_stats_elements, which are
the average of normalized x, which are just 0s.
norms: Nonempty only when normalize. A pd.DataFrame which holds the l2-norm
values of all centered-x columns.
"""
if normalize is None:
normalize = m.normalize and m.fit_intercept
table, with_data, xs_cols, y, avg_x, norms = get_data(
m, table, split_by, execute, normalize
)
xs = xs_cols.aliases
x_t_x = []
x_t_y = []
if m.fit_intercept:
if not normalize:
x_t_x = [sql.Column(f'AVG({x})', alias=f'x{i}') for i, x in enumerate(xs)]
x_t_y = [sql.Column(f'AVG({y})', alias='y')]
for i, x1 in enumerate(xs):
for j, x2 in enumerate(xs[i:]):
x_t_x.append(sql.Column(f'AVG({x1} * {x2})', alias=f'x{i}x{i + j}'))
x_t_y += [
sql.Column(f'AVG({x} * {y})', alias=f'x{i}y') for i, x in enumerate(xs)
]
cols = sql.Columns(x_t_x + x_t_y)
if include_n_obs:
cols.add(sql.Column('COUNT(*)', alias='n_obs'))
sufficient_stats_elements = sql.Sql(
cols, table, groupby=sql.Columns(split_by).aliases, with_data=with_data
)
sufficient_stats_elements = execute(str(sufficient_stats_elements))
if normalize:
col_names = list(sufficient_stats_elements.columns)
avg_x_names = [f'x{i}' for i in range(len(xs))]
sufficient_stats_elements[avg_x_names] = 0
sufficient_stats_elements = sufficient_stats_elements[
col_names[: len(split_by)] + avg_x_names + col_names[len(split_by) :]
]
return xs_cols, sufficient_stats_elements, avg_x, norms
def get_data(m, table, split_by, execute, normalize=False):
"""Retrieves the data that the model will be fit on.
We compute a Model by first computing its children, and then fitting
the model on it. This function retrieves the necessary variables to compute
the children.
We first get the result of m.to_sql(table, split_by + m.group_by). If
`normalize` is False, we already get what we need. Otherwise we center and
normalize the columns for `x`s and returns the centered-and-normalized table,
together with the average of `x`s and the norms of centered `x`s.
Args:
m: A Model instance.
table: The table we want to query from.
split_by: The columns that we use to split the data.
execute: A function that can executes a SQL query and returns a DataFrame.
normalize: If the Model normalizes x.
Returns:
table: A string representing the table name which we can query from. The
table has columns `split_by`, y, x1, x2, .... If normalize is True, x
columns are centered then normalized.
with_data: The WITH clause that holds all necessary subqueries so we can
query the `table`.
xs_cols: A list of the sql.Columns of x1, x2, ...
y: The column name of the y column.
avgs: Nonempty only when normalize is True. A pd.DataFrame which holds the
average of all x and y columns.
norms: Nonempty only when normalize is True. A pd.DataFrame which holds the
l2-norm values of all centered-x columns.
"""
data = m.children[0].to_sql(table, split_by + m.group_by)
with_data = data.with_data
data.with_data = None
table = with_data.merge(sql.Datasource(data, 'DataToFit'))
y = data.columns[-m.k - 1].alias
xs_cols = sql.Columns(data.columns[-m.k :])
if not normalize:
return table, with_data, xs_cols, y, pd.DataFrame(), pd.DataFrame()
xs = xs_cols.aliases
split_by = sql.Columns(split_by).aliases
avg_x_and_y = sql.Columns([sql.Column(f'AVG({x})', alias=x) for x in xs])
avg_x_and_y.add(sql.Column(f'AVG({y})', alias=y))
cols = sql.Columns(split_by).add(avg_x_and_y)
avgs = execute(
str(sql.Sql(cols, table, groupby=split_by, with_data=with_data))
)
avg_table = sql.Sql(
cols,
table,
groupby=split_by,
)
avg_table = with_data.merge(sql.Datasource(avg_table, 'AverageValueTable'))
table_with_centered_x = sql.Columns(split_by)
table_with_centered_x.add(sql.Column(y, '%s.{}' % table, y))
for x in avg_x_and_y.aliases[:-1]:
centered = sql.Column(x, '%s.{}' % table) - sql.Column(
x, '%s.{}' % avg_table
)
centered.alias = x
table_with_centered_x.add(centered)
join = 'LEFT' if split_by else 'CROSS'
table = with_data.merge(
sql.Datasource(
sql.Sql(
table_with_centered_x,
sql.Join(table, avg_table, using=split_by, join=join),
),
'DataCentered',
)
)
x_norms = [sql.Column(f'SQRT(SUM(POWER({x}, 2)))', alias=x) for x in xs]
norms = sql.Sql(
sql.Columns(split_by).add(x_norms),
table,
groupby=split_by,
with_data=with_data,
)
norms = execute(str(norms))
x_norm_squared = [sql.Column(f'SUM(POWER({x}, 2))', alias=x) for x in xs]
norm_squared_table = sql.Sql(
sql.Columns(split_by).add(x_norm_squared),
table,
groupby=split_by,
)
norm_squared_table = with_data.merge(
sql.Datasource(norm_squared_table, 'NormSquaredValueTable')
)
table_with_x_norms = sql.Columns(split_by)
table_with_x_norms.add(sql.Column(y, '%s.{}' % table, y))
for x in sql.Columns(x_norms).aliases:
norm = (
sql.Column(x, '%s.{}' % table)
/ sql.Column(x, '%s.{}' % norm_squared_table) ** 0.5
)
norm.alias = x
table_with_x_norms.add(norm)
table = with_data.merge(
sql.Datasource(
sql.Sql(
table_with_x_norms,
sql.Join(table, norm_squared_table, using=split_by, join=join),
),
'DataNormalized',
)
)
return table, with_data, xs_cols, y, avgs, norms
def apply_algorithm_to_sufficient_stats_elements(
sufficient_stats_elements, split_by, algorithm, *args, **kwargs
):
"""Applies algorithm to sufficient stats to get the coefficients of Models.
Args:
sufficient_stats_elements: Contains the elements to construct sufficient
stats. It's one of the return of get_sufficient_stats_elements().
split_by: The columns that we use to split the data.
algorithm: A function that can take the sufficient_stats_elements of a slice
of data and computes the coefficients of the Model.
*args: Additional args passed to the algorithm.
**kwargs: Additional kwargs passed to the algorithm.
Returns:
The coefficients of the Model.
"""
fn = lambda row: algorithm(row, *args, **kwargs)
if split_by:
# Special characters in split_by got escaped during SQL execution.
sufficient_stats_elements.columns = (
split_by + list(sufficient_stats_elements.columns)[len(split_by) :]
)
return sufficient_stats_elements.groupby(split_by, observed=True).apply(fn)
return fn(sufficient_stats_elements)
def compute_ridge_coefs(sufficient_stats, xs, m):
"""Computes coefficients of linear/ridge regression from sufficient_stats."""
if isinstance(sufficient_stats, pd.DataFrame):
sufficient_stats = sufficient_stats.iloc[0]
fit_intercept = m.fit_intercept
if fit_intercept and m.normalize:
return compute_coef_for_normalize_ridge(sufficient_stats, xs, m)
x_t_x, x_t_y = construct_matrix_from_elements(sufficient_stats, fit_intercept)
if isinstance(m, Ridge):
n_obs = sufficient_stats['n_obs']
penalty = np.identity(len(x_t_y))
if fit_intercept:
penalty[0, 0] = 0
# We use AVG() to compute x_t_x so the penalty needs to be scaled.
x_t_x += m.alpha / n_obs * penalty
cond = np.linalg.cond(x_t_x)
if cond > 20:
print(
"WARNING: The condition number of X'X is %i, which might be too large."
' The model coefficients might be inaccurate.' % cond
)
coef = np.linalg.solve(x_t_x, x_t_y)
xs = [x.alias_raw for x in xs]
if fit_intercept:
xs = ['intercept'] + xs
return pd.DataFrame([coef], columns=xs)
def compute_coef_for_normalize_ridge(sufficient_stats, xs, m):
"""Computes the coefficient of OLS or Ridge with normalization."""
n = len(xs)
# Compute the elements of X_scaled^T * X_scaled. See
# https://colab.research.google.com/drive/1wOWgdNzKGT_xl4A7Mrs_GbRKiVQACFfy#scrollTo=HrMCbB5SxS0A
x_t_x_elements = []
x_t_y = []
for i in range(n):
x_t_y.append(
sufficient_stats[f'x{i}y']
- sufficient_stats[f'x{i}'] * sufficient_stats['y']
)
for j in range(i, n):
x_t_x_elements.append(
sufficient_stats[f'x{i}x{j}']
- sufficient_stats[f'x{i}'] * sufficient_stats[f'x{j}']
)
x_t_x = symmetrize_triangular(x_t_x_elements)
if isinstance(m, Ridge):
x_t_x += m.alpha * np.diag(x_t_x.diagonal())
cond = np.linalg.cond(x_t_x)
if cond > 20:
print(
"WARNING: The condition number of X'X is %i, which might be too large."
' The model coefficients might be inaccurate.' % cond
)
coef = np.linalg.solve(x_t_x, x_t_y)
xs = [x.alias_raw for x in xs]
intercept = sufficient_stats.y - coef.dot(
[sufficient_stats[f'x{i}'] for i in range(n)]
)
coef = [intercept] + list(coef)
xs = ['intercept'] + xs
return pd.DataFrame([coef], columns=xs)
def symmetrize_triangular(tril_elements):
"""Converts a list of upper triangular matrix to a symmetric matrix.
For example, [1, 2, 3] -> [[1, 2], [2, 3]].
Args:
tril_elements: A list that can form a triangular matrix.
Returns:
A symmetric matrix whose upper triangular part is formed from tril_elements.
"""
n = int(np.floor((2 * len(tril_elements)) ** 0.5))
if n * (n + 1) / 2 != len(tril_elements):
raise ValueError('The elements cannot form a symmetric matrix!')
sym = np.zeros([n, n])
sym[np.triu_indices(n)] = tril_elements
return sym + sym.T - np.diag(sym.diagonal())
def construct_matrix_from_elements(sufficient_stats_elements, fit_intercept):
"""Constructs matries X'X and X'y from the elements.
Args:
sufficient_stats_elements: A DataFrame holding all unique elements of
sufficient stats. See the doc of get_sufficient_stats_elements() for its
shape and content.
fit_intercept: If the model includes an intercept.
Returns:
x_t_x: X'X / n_observations in a numpy array.
x_t_y: X'y / n_observations in a numpy array.
"""
if isinstance(sufficient_stats_elements, pd.DataFrame):
if len(sufficient_stats_elements) > 1:
raise ValueError('Only support 1D input!')
sufficient_stats_elements = sufficient_stats_elements.iloc[0]
elif not isinstance(sufficient_stats_elements, pd.Series):
raise ValueError('The input must be a panda Series!')
xny = (
sufficient_stats_elements.index[-2]
if sufficient_stats_elements.index[-1] == 'n_obs'
else sufficient_stats_elements.index[-1]
)
n = int(xny[1:-1]) + 1
x_t_x_cols = []
x_t_y_cols = []
if fit_intercept:
x_t_x_cols = [f'x{i}' for i in range(n)]
x_t_y_cols = ['y']
for i in range(n):
for j in range(i, n):
x_t_x_cols.append(f'x{i}x{j}')
x_t_y_cols += [f'x{i}y' for i in range(n)]
x_t_x_elements = list(sufficient_stats_elements[x_t_x_cols])
if fit_intercept:
x_t_x_elements = [1] + x_t_x_elements
x_t_y = sufficient_stats_elements[x_t_y_cols]
x_t_x = symmetrize_triangular(x_t_x_elements)
return x_t_x, np.array(x_t_y)
class Lasso(Model):
"""A class that can fit a Lasso regression."""
def __init__(
self,
y: Optional[metrics.Metric] = None,
x: Optional[
Union[metrics.Metric, Sequence[metrics.Metric], metrics.MetricList]
] = None,
group_by: Optional[Union[Text, List[Text]]] = None,
alpha=1,
fit_intercept: bool = True,
normalize: bool = False,
where: Optional[str] = None,
name: Optional[str] = None,
precompute=False,
copy_X=True,
max_iter=1000,
tol=0.0001,
warm_start=False,
positive=False,
random_state=None,
selection='cyclic',
):
"""Initialize a sklearn.Lasso model."""
model = linear_model.Lasso(
alpha=alpha,
fit_intercept=fit_intercept,
copy_X=copy_X,
max_iter=max_iter,
tol=tol,
warm_start=warm_start,
positive=positive,
random_state=random_state,
selection=selection,
)
super(Lasso, self).__init__(
y,
x,
group_by,
model,
'Lasso',
where,
name,
fit_intercept,
normalize,
['alpha', 'tol', 'max_iter', 'random_state'],
)
self.alpha = alpha
self.tol = tol
self.max_iter = max_iter
self.random_state = random_state
def compute_on_sql_magic_mode(self, table, split_by, execute):
return ElasticNet(
self.y,
self.x,
self.group_by,
self.alpha,
1,
self.fit_intercept,
self.normalize,
self.where_,
self.name,
tol=self.tol,
max_iter=self.max_iter,
).compute_on_sql_magic_mode(table, split_by, execute)
class ElasticNet(Model):
"""A class that can fit a ElasticNet regression."""
def __init__(
self,
y: Optional[metrics.Metric] = None,
x: Optional[
Union[metrics.Metric, Sequence[metrics.Metric], metrics.MetricList]
] = None,
group_by: Optional[Union[Text, List[Text]]] = None,
alpha=1,
l1_ratio=0.5,
fit_intercept: bool = True,
normalize: bool = False,
where: Optional[str] = None,
name: Optional[str] = None,
precompute=False,
copy_X=True,
max_iter=1000,
tol=0.0001,
warm_start=False,
positive=False,
random_state=None,
selection='cyclic',
):
"""Initialize a sklearn.ElasticNet model."""
model = linear_model.ElasticNet(
alpha=alpha,
l1_ratio=l1_ratio,
fit_intercept=fit_intercept,
copy_X=copy_X,
max_iter=max_iter,
tol=tol,
warm_start=warm_start,
positive=positive,
random_state=random_state,
selection=selection,
)
super(ElasticNet, self).__init__(
y,
x,
group_by,
model,
'ElasticNet',
where,
name,
fit_intercept,
normalize,
['alpha', 'tol', 'max_iter', 'l1_ratio', 'random_state'],
)
self.alpha = alpha
self.tol = tol
self.max_iter = max_iter
self.l1_ratio = l1_ratio
self.random_state = random_state
def compute_on_sql_magic_mode(self, table, split_by, execute):
if not self.l1_ratio or not 0 <= self.l1_ratio <= 1:
raise ValueError(
f'l1_ratio must be between 0 and 1; got (l1_ratio={self.l1_ratio})'
)
l1 = self.l1_ratio * self.alpha
l2 = (1 - self.l1_ratio) * self.alpha
xs, sufficient_stats_elements, avgs, norms = get_sufficient_stats_elements(
self, table, split_by, execute
)
np.random.seed(
self.random_state if isinstance(self.random_state, int) else 42
)
coef = apply_algorithm_to_sufficient_stats_elements(
sufficient_stats_elements,
split_by,
compute_coef_for_elastic_net,
xs,
l1,
l2,
self.fit_intercept,
self.tol,
self.max_iter,
)
if self.fit_intercept and self.normalize:
coef = compute_normalized_coef(coef, norms, avgs, split_by)
columns = list(coef.columns)
columns[-len(xs) :] = [x.alias_raw for x in xs]
coef.columns = columns
return coef
def compute_coef_for_elastic_net(
sufficient_stats_elements, xs, l1, l2, fit_intercept, tol, max_iter
):
"""Computes the coefficients for ElasticNet. Lasso is just a special case."""
if fit_intercept:
sufficient_stats_elements, avg_xs, avg_y = center_x(
sufficient_stats_elements, len(xs)
)
x_t_x, x_t_y = construct_matrix_from_elements(
sufficient_stats_elements, fit_intercept
)
init_guess = np.random.random(*x_t_y.shape)
coef = fista_for_elastic_net(
init_guess, l1, l2, x_t_x, x_t_y, tol, max_iter, fit_intercept
)
columns = list(xs.aliases)
if fit_intercept:
# We centered x and y above so the intercept from optimization is not right.
coef[0] = (avg_y - avg_xs @ coef[1:]).values[0]
columns = ['intercept'] + columns
return pd.DataFrame([list(coef)], columns=columns)
def center_x(sufficient_stats_elements, n):
"""Compute the sufficient_stats_elements of centered x for better convergence.
sufficient_stats_elements has four types of elements. The ones under 'x{i}'
are the average values of the i-th feature. The 'y' column is the average
of the dependent variable. The 'x{i}x{j}' are the normalized elements of
matrix X'X, namely, 'x{i}x{j}' has value of AVG(xi * xj). Similarly, 'x{i}y'
contains the normalized elements of X'y.
We want to center X and y for better numerical stability and convergence. As
a result, we need to update 'x{i}x{j}'. The new value would be
AVG((xi - xi_bar) * (xj - xj_bar)) = AVG(xi * xj) - xi_bar * xj_bar. 'x{i}y'
can be updated similarly.
Args:
sufficient_stats_elements: The sufficient_stats_elements computed from
original x.
n: The number of x.
Returns:
The sufficient_stats_elements computed from centered x and y.
Average of original x.
Average of original y.
"""
sufficient_stats_elements = sufficient_stats_elements.copy()
avg_xs = sufficient_stats_elements[[f'x{i}' for i in range(n)]]
avg_y = sufficient_stats_elements['y']
for i in range(n):
sufficient_stats_elements[f'x{i}y'] -= avg_xs[f'x{i}'] * avg_y
for j in range(i, n):
sufficient_stats_elements[f'x{i}x{j}'] -= (
avg_xs[f'x{i}'] * avg_xs[f'x{j}']
)
sufficient_stats_elements[[f'x{i}' for i in range(n)]] = 0
return sufficient_stats_elements, avg_xs, avg_y
def fista_for_elastic_net(
coef, l1, l2, x_t_x, x_t_y, tol, max_iter, fit_intercept
):
"""Applies FISTA algorithm to elastic net.
Lasso is just a special case.
The algorithm is also called accelerated proximal gradient descent. The
parameters are the same as those in proximal gradient descent. A derivation
can be found in
https://web.archive.org/save/https://yuxinchen2020.github.io/ele520_math_data/lectures/lasso_algorithm_extension.pdf.
There are variants for the acceleration. Here we implemented the one in
https://web.archive.org/web/20220616072055/http://www.cs.cmu.edu/~pradeepr/convexopt/Lecture_Slides/prox-grad_2.pdf.
The function is used for Lasso/ElasticNet, the differentiable g(x) in the loss
function used by sklearn is (1 / (2 * n_samples)) * ||y - Xw||^2_2. Its
Lipschitz constant, L, is the largest eigenvalue of X'X / n_samples, so the
max step size is 1/L. For proof, see Example 2.2 in
Beck, A., & Teboulle, M. (2009). A fast iterative shrinkage-thresholding
algorithm for linear inverse problems.
SIAM journal on imaging sciences, 2(1), 183-202.
Args:
coef: The initial guess of the coefficients.
l1: L1 penalty strength. In terms of the args of ElasticNet in sklearn, it
equals alpha * l1_ratio.
l2: L2 penalty strength. In terms of the args of ElasticNet in sklearn, it
equals alpha * (1 - l1_ratio).
x_t_x: X'X / n_observations.
x_t_y: X'y / n_observations.
tol: The tolerance for the optimization.
max_iter: The maximum number of iterations.
fit_intercept: If the coefficients include an intercept.
Returns:
The converged coef, namely, the coefficients of the model.
"""
delta = np.zeros_like(coef)
# If we just use 1, depending on how a float is stored, maybe the step_size
# will be slightly larger than the max allowed? I don't know if it will ever
# happen but to be safe I use 1 - 1e-6.
step_size = (1 - 1e-6) / np.linalg.eigvals(x_t_x).max()
k = l2 * step_size + 1
threshold = l1 * step_size / k
for i in range(int(max_iter)):
v = coef + (i - 1) / (i + 2) * delta
coef_old = coef
coef = v - step_size * (x_t_x @ v - x_t_y)
if fit_intercept:
coef[1:] = soft_thresholding(coef[1:] / k, threshold)
else:
coef = soft_thresholding(coef / k, threshold)
delta = coef - coef_old
if abs(delta).sum() < tol:
return coef
print("WARNING: Lasso/ElasticNet didn't converge! Try increasing `max_iter`.")
return coef
def soft_thresholding(x, thresh):
return np.maximum(x - thresh, 0) + np.minimum(x + thresh, 0)
def compute_normalized_coef(coef, norms, avgs, split_by):
"""Scale the coef by the norms of x to get the coef for normalized models.
Compute the coeffients of model(normalized=True).fit(x, y) from the coeffients
of model.fit(x_normalized, y). The former is the latter divided by the norms
of centered x, except for the intercept. Once the coefficients are calculated,
the intercept can be computed from coefficients and the average of original x
and y.
Args:
coef: The coeffients of model.fit(x_normalized, y), including intercept as
the first column.
norms: The norms of centered x.
avgs: The average of normalized x and y.
split_by: The columns that we use to split the data.
Returns:
The coeffients of model(normalized=True).fit(x, y).
"""
coef = utils.remove_empty_level(coef)
cols = coef.columns
coef.drop(columns='intercept', inplace=True)
if split_by:
norms = norms.set_index(coef.index.names).reindex(coef.index)
avgs = avgs.set_index(coef.index.names).reindex(coef.index)
coef /= norms
avg_x, avg_y = avgs.iloc[:, :-1], avgs.iloc[:, -1]
coef['intercept'] = avg_y - (avg_x.values * coef.values).sum(1)
return coef[cols]
class LogisticRegression(Model):
"""A class that can fit a logistic regression."""
def __init__(
self,
y: metrics.Metric,
x: Union[metrics.Metric, Sequence[metrics.Metric], metrics.MetricList],
group_by: Optional[Union[Text, List[Text]]] = None,
fit_intercept: bool = True,
where: Optional[str] = None,
name: Optional[str] = None,
penalty='l2',
dual=False,
tol=0.0001,
C=1.0,
intercept_scaling=1,
class_weight=None,
random_state=None,
solver='lbfgs',
max_iter=100,
verbose=0,
warm_start=False,
n_jobs=None,
l1_ratio=None,
):
"""Initialize a sklearn.LogisticRegression model."""
if penalty not in (None, 'l1', 'l2', 'elasticnet'):
raise ValueError(
"Penalty must be one of (None, 'l1', 'l2', 'elasticnet') but is"
f' {penalty}!'
)
if penalty == 'elasticnet' and (not l1_ratio or not 0 <= l1_ratio <= 1):
raise ValueError(
f'l1_ratio must be between 0 and 1; got (l1_ratio={l1_ratio})'
)
if l1_ratio is not None and penalty != 'elasticnet':
raise ValueError(
"l1_ratio parameter is only used when penalty is 'elasticnet'. Got"
f' (penalty={penalty})'
)
model = linear_model.LogisticRegression(
fit_intercept=fit_intercept,
penalty=penalty,
dual=dual,
tol=tol,
C=C,
intercept_scaling=intercept_scaling,
class_weight=class_weight,
random_state=random_state,