-
Notifications
You must be signed in to change notification settings - Fork 1
/
lasso.py
2552 lines (2208 loc) · 85.2 KB
/
lasso.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
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
"""
This module contains a class `lasso`_ that implements
post selection for the lasso
as described in `post selection LASSO`_.
.. _covTest: http://arxiv.org/abs/1301.7161
.. _Kac Rice: http://arxiv.org/abs/1308.3020
.. _Spacings: http://arxiv.org/abs/1401.3889
.. _post selection LASSO: http://arxiv.org/abs/1311.6238
.. _sample carving: http://arxiv.org/abs/1410.2597
"""
from __future__ import division
import warnings, functools
from copy import copy
import numpy as np
import pandas as pd
from scipy.stats import norm as ndist, t as tdist
from scipy.linalg import block_diag
from regreg.api import (
glm,
weighted_l1norm,
simple_problem,
smooth_sum,
squared_error,
identity_quadratic,
quadratic_loss,
)
from .sqrt_lasso import solve_sqrt_lasso, estimate_sigma
from .debiased_lasso import debiasing_matrix, pseudoinverse_debiasing_matrix
from ..constraints.affine import (
constraints,
selection_interval,
interval_constraints,
sample_from_constraints,
gibbs_test,
stack,
)
from ..distributions.discrete_family import discrete_family
from ..truncated.gaussian import truncated_gaussian_old as TG
from ..glm import pairs_bootstrap_glm
class lasso(object):
r"""
A class for the LASSO for post-selection inference.
The problem solved is
.. math::
\text{minimize}_{\beta} \frac{1}{2n} \|y-X\beta\|^2_2 +
\lambda \|\beta\|_1
where $\lambda$ is `lam`.
"""
def __init__(
self,
loglike,
feature_weights,
covariance_estimator=None,
ignore_inactive_constraints=False,
):
r"""
Create a new post-selection dor the LASSO problem
Parameters
----------
loglike : `regreg.smooth.glm.glm`
A (negative) log-likelihood as implemented in `regreg`.
feature_weights : np.ndarray
Feature weights for L-1 penalty. If a float,
it is brodcast to all features.
covariance_estimator : callable (optional)
If None, use the parameteric
covariance estimate of the selected model.
Notes
-----
If not None, `covariance_estimator` should
take arguments (beta, active, inactive)
and return an estimate of the covariance of
$(\bar{\beta}_E, \nabla \ell(\bar{\beta}_E)_{-E})$,
the unpenalized estimator and the inactive
coordinates of the gradient of the likelihood at
the unpenalized estimator.
"""
self.loglike = loglike
if np.asarray(feature_weights).shape == ():
feature_weights = np.ones(loglike.shape) * feature_weights
self.feature_weights = np.asarray(feature_weights)
self.covariance_estimator = covariance_estimator
self.ignore_inactive_constraints = ignore_inactive_constraints
def fit(self, lasso_solution=None, solve_args={"tol": 1.0e-12, "min_its": 50}):
"""
Fit the lasso using `regreg`.
This sets the attributes `soln`, `onestep` and
forms the constraints necessary for post-selection inference
by calling `form_constraints()`.
Parameters
----------
lasso_solution : optional
If not None, this is taken to be the solution
of the optimization problem. No checks
are done, though the implied affine
constraints will generally not be satisfied.
solve_args : keyword args
Passed to `regreg.problems.simple_problem.solve`.
Returns
-------
soln : np.float
Solution to lasso.
Notes
-----
If `self` already has an attribute `lasso_solution`
this will be taken to be the solution and
no optimization problem will be solved. Supplying
the optional argument `lasso_solution` will
overwrite `self`'s `lasso_solution`.
"""
self._penalty = weighted_l1norm(self.feature_weights, lagrange=1.0)
if lasso_solution is None and not hasattr(self, "lasso_solution"):
problem = simple_problem(self.loglike, self._penalty)
self.lasso_solution = problem.solve(**solve_args)
elif lasso_solution is not None:
self.lasso_solution = lasso_solution
lasso_solution = (
self.lasso_solution
) # shorthand after setting it correctly above
if not np.all(lasso_solution == 0):
self.active = np.nonzero(lasso_solution != 0)[0]
self.inactive = lasso_solution == 0
self.active_signs = np.sign(lasso_solution[self.active])
self._active_soln = lasso_solution[self.active]
H = self.loglike.hessian(self.lasso_solution)
H_AA = H[self.active][:, self.active]
H_AAinv = np.linalg.inv(H_AA)
Q = self.loglike.quadratic
G_Q = Q.objective(self.lasso_solution, "grad")
G = self.loglike.gradient(self.lasso_solution) + G_Q
G_A = G[self.active]
G_I = self._G_I = G[self.inactive]
dbeta_A = H_AAinv.dot(G_A)
self.onestep_estimator = self._active_soln - dbeta_A
self.active_penalized = self.feature_weights[self.active] != 0
if self.active_penalized.sum():
self._constraints = constraints(
-np.diag(self.active_signs)[self.active_penalized],
(self.active_signs * dbeta_A)[self.active_penalized],
covariance=H_AAinv,
)
else:
self._constraints = constraints(
np.identity(self.active.shape[0]),
1.0e12 * np.ones(self.active.shape[0]) * H_AAinv.max(),
# XXX np.inf seems to fail tests
covariance=H_AAinv,
)
if self.inactive.sum():
# inactive constraints
H_IA = H[self.inactive][:, self.active]
H_II = H[self.inactive][:, self.inactive]
inactive_cov = H_II - H_IA.dot(H_AAinv).dot(H_IA.T)
irrepresentable = H_IA.dot(H_AAinv)
inactive_mean = irrepresentable.dot(-G_A)
self._inactive_constraints = constraints(
np.vstack(
[
np.identity(self.inactive.sum()),
-np.identity(self.inactive.sum()),
]
),
np.hstack(
[
self.feature_weights[self.inactive],
self.feature_weights[self.inactive],
]
),
covariance=inactive_cov,
mean=inactive_mean,
)
if not self._inactive_constraints(G_I):
warnings.warn(
"inactive constraint of KKT conditions not satisfied -- perhaps need to solve with more accuracy"
)
if self.covariance_estimator is not None:
# make full constraints
# A: active
# I: inactive
# F: full, (A,I) stacked
_cov_FA = self.covariance_estimator(
self.onestep_estimator, self.active, self.inactive
)
_cov_IA = _cov_FA[len(self.active) :]
_cov_AA = _cov_FA[: len(self.active)]
_beta_bar = self.onestep_estimator
if not self.ignore_inactive_constraints:
# X_{-E}^T(y - X_E \bar{\beta}_E)
_inactive_score = -G_I - inactive_mean
_indep_linear_part = _cov_IA.dot(np.linalg.inv(_cov_AA))
# we "fix" _nuisance, effectively conditioning on it
_nuisance = _inactive_score - _indep_linear_part.dot(_beta_bar)
_upper_lim = (
self.feature_weights[self.inactive]
- _nuisance
- inactive_mean
)
_lower_lim = (
_nuisance
+ self.feature_weights[self.inactive]
+ inactive_mean
)
_upper_linear = _indep_linear_part
_lower_linear = -_indep_linear_part
C = self._constraints
_full_linear = np.vstack(
[C.linear_part, _upper_linear, _lower_linear]
)
_full_offset = np.hstack([C.offset, _upper_lim, _lower_lim])
self._constraints = constraints(
_full_linear, _full_offset, covariance=_cov_AA
)
else:
self._constraints.covariance[:] = _cov_AA
if not self._constraints(_beta_bar):
warnings.warn(
"constraints of KKT conditions on one-step estimator "
+ " not satisfied -- perhaps need to solve with more"
+ "accuracy"
)
else:
self._inactive_constraints = None
else:
self.active = []
self.active_signs = []
self.inactive = np.arange(lasso_solution.shape[0])
self._constraints = None
self._inactive_constraints = None
return self.lasso_solution
def summary(
self,
alternative="twosided",
level=0.95,
compute_intervals=False,
dispersion=None,
truth=None,
):
"""
Summary table for inference adjusted for selection.
Parameters
----------
alternative : str
One of ["twosided","onesided"]
level : float
Form level*100% selective confidence intervals.
compute_intervals : bool
Should we compute confidence intervals?
dispersion : float
Scalar to multiply `self.constraints.covaraince`
truth : np.array
True values of each beta for selected variables. If not None, a column 'pval' are p-values
computed under these corresponding null hypotheses.
Returns
-------
pval_summary : np.recarray
Array with one entry per active variable.
Columns are 'variable', 'pval', 'lasso', 'onestep', 'lower_trunc', 'upper_trunc', 'sd'.
"""
if alternative not in ["twosided", "onesided"]:
raise ValueError("alternative must be one of ['twosided', 'onesided']")
if truth is None:
truth = np.zeros_like(self.active_signs)
if dispersion is None:
dispersion = 1.0
result = []
C = self.constraints
if C is not None:
_cov = C.covariance.copy()
C.covariance = _cov * dispersion
one_step = self.onestep_estimator
for i in range(one_step.shape[0]):
eta = np.zeros_like(one_step)
eta[i] = self.active_signs[i]
_alt = {"onesided": "greater", "twosided": "twosided"}[alternative]
if C.linear_part.shape[0] > 0: # there were some constraints
_pval = C.pivot(
eta, one_step, null_value=truth[i], alternative=_alt
)
else:
obs = (eta * one_step).sum()
sd = np.sqrt((eta * C.covariance.dot(eta)))
Z = obs / sd
_pval = 2 * ndist.sf(np.fabs(Z))
alpha = 1 - level
if compute_intervals:
if C.linear_part.shape[0] > 0: # there were some constraints
try:
_interval = C.interval(eta, one_step, alpha=alpha)
except OverflowError:
_interval = (-np.inf, np.inf)
_interval = sorted(
[
_interval[0] * self.active_signs[i],
_interval[1] * self.active_signs[i],
]
)
else:
_interval = (
obs - ndist.ppf(1 - alpha / 2) * sd,
obs + ndist.ppf(1 - alpha / 2) * sd,
)
else:
_interval = [np.nan, np.nan]
_bounds = np.array(C.bounds(eta, one_step))
sd = _bounds[-1]
lower_trunc, est, upper_trunc = sorted(
_bounds[:3] * self.active_signs[i]
)
result.append(
(
self.active[i],
_pval,
self.lasso_solution[self.active[i]],
one_step[i],
_interval[0],
_interval[1],
lower_trunc,
upper_trunc,
sd,
)
)
C.covariance = _cov
df = pd.DataFrame(
index=self.active,
data=dict(
[
(n, d)
for n, d in zip(
[
"variable",
"pvalue",
"lasso",
"onestep",
"lower_confidence",
"upper_confidence",
"lower_trunc",
"upper_trunc",
"sd",
],
np.array(result).T,
)
]
),
)
if len(df) > 0:
df["variable"] = df["variable"].astype(int)
return df
@property
def soln(self):
"""
Solution to the lasso problem, set by `fit` method.
"""
if not hasattr(self, "lasso_solution"):
self.fit()
return self.lasso_solution
@property
def constraints(self):
"""
Affine constraints for this LASSO problem.
These are the constraints determined only
by the active block.
"""
return self._constraints
@classmethod
def gaussian(
klass,
X,
Y,
feature_weights,
sigma=1.0,
covariance_estimator=None,
quadratic=None,
):
r"""
Squared-error LASSO with feature weights.
Objective function is
$$
\beta \mapsto \frac{1}{2} \|Y-X\beta\|^2_2 + \sum_{i=1}^p \lambda_i |\beta_i|
$$
where $\lambda$ is `feature_weights`.
Parameters
----------
X : ndarray
Shape (n,p) -- the design matrix.
Y : ndarray
Shape (n,) -- the response.
feature_weights: [float, sequence]
Penalty weights. An intercept, or other unpenalized
features are handled by setting those entries of
`feature_weights` to 0. If `feature_weights` is
a float, then all parameters are penalized equally.
sigma : float (optional)
Noise variance. Set to 1 if `covariance_estimator` is not None.
This scales the loglikelihood by `sigma**(-2)`.
covariance_estimator : callable (optional)
If None, use the parameteric
covariance estimate of the selected model.
quadratic : `regreg.identity_quadratic.identity_quadratic` (optional)
An optional quadratic term to be added to the objective.
Can also be a linear term by setting quadratic
coefficient to 0.
Returns
-------
L : `selection.algorithms.lasso.lasso`
Notes
-----
If not None, `covariance_estimator` should
take arguments (beta, active, inactive)
and return an estimate of some of the
rows and columns of the covariance of
$(\bar{\beta}_E, \nabla \ell(\bar{\beta}_E)_{-E})$,
the unpenalized estimator and the inactive
coordinates of the gradient of the likelihood at
the unpenalized estimator.
"""
if covariance_estimator is not None:
sigma = 1.0
loglike = glm.gaussian(X, Y, coef=1.0 / sigma**2, quadratic=quadratic)
return klass(
loglike,
np.asarray(feature_weights) / sigma**2,
covariance_estimator=covariance_estimator,
)
@classmethod
def logistic(
klass,
X,
successes,
feature_weights,
trials=None,
covariance_estimator=None,
quadratic=None,
):
r"""
Logistic LASSO with feature weights.
Objective function is
$$
\beta \mapsto \ell(X\beta) + \sum_{i=1}^p \lambda_i |\beta_i|
$$
where $\ell$ is the negative of the logistic
log-likelihood (half the logistic deviance)
and $\lambda$ is `feature_weights`.
Parameters
----------
X : ndarray
Shape (n,p) -- the design matrix.
successes : ndarray
Shape (n,) -- response vector. An integer number of successes.
For data that is proportions, multiply the proportions
by the number of trials first.
feature_weights: [float, sequence]
Penalty weights. An intercept, or other unpenalized
features are handled by setting those entries of
`feature_weights` to 0. If `feature_weights` is
a float, then all parameters are penalized equally.
trials : ndarray (optional)
Number of trials per response, defaults to
ones the same shape as Y.
covariance_estimator : optional
If None, use the parameteric
covariance estimate of the selected model.
quadratic : `regreg.identity_quadratic.identity_quadratic` (optional)
An optional quadratic term to be added to the objective.
Can also be a linear term by setting quadratic
coefficient to 0.
Returns
-------
L : `selection.algorithms.lasso.lasso`
Notes
-----
If not None, `covariance_estimator` should
take arguments (beta, active, inactive)
and return an estimate of the covariance of
$(\bar{\beta}_E, \nabla \ell(\bar{\beta}_E)_{-E})$,
the unpenalized estimator and the inactive
coordinates of the gradient of the likelihood at
the unpenalized estimator.
"""
loglike = glm.logistic(X, successes, trials=trials, quadratic=quadratic)
return klass(
loglike, feature_weights, covariance_estimator=covariance_estimator
)
@classmethod
def cox(
klass,
X,
times,
status,
feature_weights,
covariance_estimator=None,
quadratic=None,
):
r"""
Cox proportional hazards LASSO with feature weights.
Objective function is
$$
\beta \mapsto \ell^{\text{Cox}}(\beta) + \sum_{i=1}^p \lambda_i |\beta_i|
$$
where $\ell^{\text{Cox}}$ is the
negative of the log of the Cox partial
likelihood and $\lambda$ is `feature_weights`.
Uses Efron's tie breaking method.
Parameters
----------
X : ndarray
Shape (n,p) -- the design matrix.
times : ndarray
Shape (n,) -- the survival times.
status : ndarray
Shape (n,) -- the censoring status.
feature_weights: [float, sequence]
Penalty weights. An intercept, or other unpenalized
features are handled by setting those entries of
`feature_weights` to 0. If `feature_weights` is
a float, then all parameters are penalized equally.
covariance_estimator : optional
If None, use the parameteric
covariance estimate of the selected model.
quadratic : `regreg.identity_quadratic.identity_quadratic` (optional)
An optional quadratic term to be added to the objective.
Can also be a linear term by setting quadratic
coefficient to 0.
Returns
-------
L : `selection.algorithms.lasso.lasso`
Notes
-----
If not None, `covariance_estimator` should
take arguments (beta, active, inactive)
and return an estimate of the covariance of
$(\bar{\beta}_E, \nabla \ell(\bar{\beta}_E)_{-E})$,
the unpenalized estimator and the inactive
coordinates of the gradient of the likelihood at
the unpenalized estimator.
"""
loglike = glm.cox(X, times, status, quadratic=quadratic)
return klass(
loglike, feature_weights, covariance_estimator=covariance_estimator
)
@classmethod
def poisson(
klass, X, counts, feature_weights, covariance_estimator=None, quadratic=None
):
r"""
Poisson log-linear LASSO with feature weights.
Objective function is
$$
\beta \mapsto \ell^{\text{Poisson}}(\beta) + \sum_{i=1}^p \lambda_i |\beta_i|
$$
where $\ell^{\text{Poisson}}$ is the negative
of the log of the Poisson likelihood (half the deviance)
and $\lambda$ is `feature_weights`.
Parameters
----------
X : ndarray
Shape (n,p) -- the design matrix.
counts : ndarray
Shape (n,) -- the response.
feature_weights: [float, sequence]
Penalty weights. An intercept, or other unpenalized
features are handled by setting those entries of
`feature_weights` to 0. If `feature_weights` is
a float, then all parameters are penalized equally.
covariance_estimator : optional
If None, use the parameteric
covariance estimate of the selected model.
quadratic : `regreg.identity_quadratic.identity_quadratic` (optional)
An optional quadratic term to be added to the objective.
Can also be a linear term by setting quadratic
coefficient to 0.
Returns
-------
L : `selection.algorithms.lasso.lasso`
Notes
-----
If not None, `covariance_estimator` should
take arguments (beta, active, inactive)
and return an estimate of the covariance of
$(\bar{\beta}_E, \nabla \ell(\bar{\beta}_E)_{-E})$,
the unpenalized estimator and the inactive
coordinates of the gradient of the likelihood at
the unpenalized estimator.
"""
loglike = glm.poisson(X, counts, quadratic=quadratic)
return klass(
loglike, feature_weights, covariance_estimator=covariance_estimator
)
@classmethod
def sqrt_lasso(
klass,
X,
Y,
feature_weights,
quadratic=None,
covariance="parametric",
sigma_estimate="truncated",
solve_args={"min_its": 200},
):
r"""
Use sqrt-LASSO to choose variables.
Objective function is
$$
\beta \mapsto \|Y-X\beta\|_2 + \sum_{i=1}^p \lambda_i |\beta_i|
$$
where $\lambda$ is `feature_weights`. After solving the problem
treat as if `gaussian` with implied variance and choice of
multiplier. See arxiv.org/abs/1504.08031 for details.
Parameters
----------
X : ndarray
Shape (n,p) -- the design matrix.
Y : ndarray
Shape (n,) -- the response.
feature_weights: [float, sequence]
Penalty weights. An intercept, or other unpenalized
features are handled by setting those entries of
`feature_weights` to 0. If `feature_weights` is
a float, then all parameters are penalized equally.
quadratic : `regreg.identity_quadratic.identity_quadratic` (optional)
An optional quadratic term to be added to the objective.
Can also be a linear term by setting quadratic
coefficient to 0.
covariance : str
One of 'parametric' or 'sandwich'. Method
used to estimate covariance for inference
in second stage.
sigma_estimate : str
One of 'truncated' or 'OLS'. Method
used to estimate $\sigma$ when using
parametric covariance.
solve_args : dict
Arguments passed to solver.
Returns
-------
L : `selection.algorithms.lasso.lasso`
Notes
-----
Unlike other variants of LASSO, this
solves the problem on construction as the active
set is needed to find equivalent gaussian LASSO.
Assumes parametric model is correct for inference,
i.e. does not accept a covariance estimator.
"""
n, p = X.shape
if np.asarray(feature_weights).shape == ():
feature_weights = np.ones(p) * feature_weights
feature_weights = np.asarray(feature_weights)
# TODO: refits sqrt lasso more than once -- make an override for avoiding refitting?
soln = solve_sqrt_lasso(
X, Y, weights=feature_weights, quadratic=quadratic, solve_args=solve_args
)[0]
# find active set, and estimate of sigma
active = soln != 0
nactive = active.sum()
if nactive:
subgrad = np.sign(soln[active]) * feature_weights[active]
X_E = X[:, active]
X_Ei = np.linalg.pinv(X_E)
sigma_E = np.linalg.norm(Y - X_E.dot(X_Ei.dot(Y))) / np.sqrt(n - nactive)
multiplier = np.sqrt(
(n - nactive) / (1 - np.linalg.norm(X_Ei.T.dot(subgrad)) ** 2)
)
# check truncation interval for sigma_E
# the KKT conditions imply an inequality like
# \hat{\sigma}_E \cdot LHS \leq RHS
penalized = feature_weights[active] != 0
if penalized.sum():
D_E = np.sign(soln[active][penalized]) # diagonal matrix of signs
LHS = D_E * np.linalg.solve(X_E.T.dot(X_E), subgrad)[penalized]
RHS = D_E * X_Ei.dot(Y)[penalized]
ratio = RHS / LHS
group1 = LHS > 0
upper_bound = np.inf
if group1.sum():
upper_bound = min(
upper_bound, np.min(ratio[group1])
) # necessarily these will have RHS > 0
group2 = (LHS <= 0) * (
RHS <= 0
) # we can ignore the other possibility since this gives a lower bound of 0
lower_bound = 0
if group2.sum():
lower_bound = max(lower_bound, np.max(ratio[group2]))
upper_bound /= multiplier
lower_bound /= multiplier
else:
lower_bound = 0
upper_bound = np.inf
_sigma_estimator_args = (sigma_E, n - nactive, lower_bound, upper_bound)
if sigma_estimate == "truncated":
_sigma_hat = estimate_sigma(*_sigma_estimator_args)
elif sigma_estimate == "OLS":
_sigma_hat = sigma_E
else:
raise ValueError('sigma_estimate must be one of ["truncated", "OLS"]')
else:
_sigma_hat = np.linalg.norm(Y) / np.sqrt(n)
multiplier = np.sqrt(n)
sigma_E = _sigma_hat
# XXX how should quadratic be changed?
# multiply everything by sigma_E?
if quadratic is not None:
qc = quadratic.collapsed()
qc.coef *= np.sqrt(n - nactive) / sigma_E
qc.linear_term *= np.sqrt(n - nactive) / sigma_E
quadratic = qc
loglike = glm.gaussian(X, Y, quadratic=quadratic)
if covariance == "parametric":
cov_est = glm_parametric_estimator(loglike, dispersion=_sigma_hat)
elif covariance == "sandwich":
cov_est = glm_sandwich_estimator(loglike, B=2000)
else:
raise ValueError('covariance must be one of ["parametric", "sandwich"]')
L = klass(
loglike,
feature_weights * multiplier * sigma_E,
covariance_estimator=cov_est,
ignore_inactive_constraints=True,
)
# these arguments are reused for data carving
if nactive:
L._sigma_hat = _sigma_hat
L._sigma_estimator_args = _sigma_estimator_args
L._weight_multiplier = multiplier * sigma_E
L._multiplier = multiplier
L.lasso_solution = soln
return L
def nominal_intervals(lasso_obj, level=0.95):
"""
Intervals for OLS parameters of active variables
that have not been adjusted for selection.
"""
unadjusted_intervals = []
alpha = 1 - level
if lasso_obj.active is not []:
SigmaE = lasso_obj.constraints.covariance
for i in range(lasso_obj.active.shape[0]):
eta = np.ones_like(lasso_obj.onestep_estimator)
eta[i] = 1.0
center = lasso_obj.onestep_estimator[i]
width = ndist.ppf(1 - alpha / 2.0) * np.sqrt(SigmaE[i, i])
_interval = [center - width, center + width]
unadjusted_intervals.append((lasso_obj.active[i], eta, center, _interval))
return unadjusted_intervals
def glm_sandwich_estimator(loss, B=1000):
"""
Bootstrap estimator of covariance of
.. math::
(\bar{\beta}_E, X_{-E}^T(y-X_E\bar{\beta}_E)
the OLS estimator of population regression
coefficients and inactive correlation with the
OLS residuals.
Returns
-------
estimator : callable
Takes arguments (beta, active, inactive)
"""
def _estimator(loss, B, beta, active, inactive):
X, Y = loss.data
n, p = X.shape # shorthand
beta_full = np.zeros(p)
beta_full[active] = beta
# make sure active / inactive are bool
active_bool = np.zeros(p, np.bool)
active_bool[active] = 1
inactive_bool = np.zeros(p, np.bool)
inactive_bool[inactive] = 1
bootstrapper = pairs_bootstrap_glm(
loss, active_bool, beta_full=beta_full, inactive=inactive_bool
)[0]
nactive = active_bool.sum()
first_moment = np.zeros(p)
second_moment = np.zeros((p, nactive))
for b in range(B):
indices = np.random.choice(n, n, replace=True)
Z_star = bootstrapper(indices)
first_moment += Z_star
second_moment += np.multiply.outer(Z_star, Z_star[:nactive])
first_moment /= B
second_moment /= B
cov = second_moment - np.multiply.outer(first_moment, first_moment[:nactive])
return cov
return functools.partial(_estimator, loss, B)
def glm_parametric_estimator(loglike, dispersion=None):
"""
Parametric estimator of covariance of
.. math::
(\bar{\beta}_E, X_{-E}^T(y-\nabla \ell(X_E\bar{\beta}_E))
the OLS estimator of population regression
coefficients and inactive correlation with the
OLS residuals.
If `sigma` is None, it computes usual unbiased estimate
of variance in Gaussian model and plugs it in,
assuming parametric form is correct.
Returns
-------
estimator : callable
Takes arguments (beta, active, inactive)
"""
def _estimator(loglike, dispersion, beta, active, inactive):
X, Y = loglike.data
n, p = X.shape
nactive = len(active)
linear_predictor = X[:, active].dot(beta)
W = loglike.saturated_loss.hessian(linear_predictor)
Sigma_A = X[:, active].T.dot(W[:, None] * X[:, active])
Sigma_Ainv = np.linalg.inv(Sigma_A)
_unscaled = np.zeros((p, len(active)))
_unscaled[:nactive] = Sigma_Ainv
# the lower block is left at 0 because
# under the parametric model, these pieces
# are independent
# if no dispersion, use Pearson's X^2
if dispersion is None:
eta = X[:, active].dot(beta)
dispersion = (
(loglike.saturated_loss.smooth_objective(eta, "grad")) ** 2 / W
).sum() / (n - nactive)
_unscaled *= dispersion**2
return _unscaled
return functools.partial(_estimator, loglike, dispersion)
def standard_lasso(X, y, sigma=1, lam_frac=1.0, **solve_args):
"""
Fit a LASSO with a default choice of Lagrange parameter
equal to `lam_frac` times $\sigma \cdot E(|X^T\epsilon|)$
with $\epsilon$ IID N(0,1).
Parameters
----------
y : np.float
Response vector
X : np.float
Design matrix
sigma : np.float
Noise variance
lam_frac : float
Multiplier for choice of $\lambda$
solve_args : keyword args
Passed to `regreg.problems.simple_problem.solve`.
Returns
-------
lasso_selection : `lasso`
Instance of `lasso` after fitting.
"""
n, p = X.shape
lam = (
lam_frac
* np.mean(np.fabs(X.T.dot(np.random.standard_normal((n, 50000)))).max(0))
* sigma
)
lasso_selector = lasso.gaussian(X, y, lam, sigma=sigma)
lasso_selector.fit(**solve_args)
return lasso_selector
class data_carving(lasso):
"""
Notes
-----
Even if a covariance estimator is supplied,
we assume that we can drop inactive constraints,
i.e. the same (asymptotic) independence that
holds for parametric model is assumed to hold here
as well.
"""
def __init__(
self,
loglike_select,
loglike_inference,
loglike_full,
feature_weights,
covariance_estimator=None,
):
lasso.__init__(
self,
loglike_select,
feature_weights,
covariance_estimator=covariance_estimator,