-
Notifications
You must be signed in to change notification settings - Fork 3
/
lasso2.ado
2058 lines (1933 loc) · 66.3 KB
/
lasso2.ado
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
*! lasso2 1.0.13 05jan2024
*! lassopack package 1.4.3
*! authors aa/ms
* additional notes
* return dof for 1 lambda
* eclass wrapper for elastic net & sqrt-lasso estimation
* all partialling, transformations, standardization, FE, tempvars handled here
* keeps lists of original and temp varlists
* plotting supported using "plotpath" program
* display of output handled by "DisplayPath" and "DisplayCoefs" programs
* marksample and markout used here so that e(sample) can be saved
* options relevant to eclass and saved results spelled out here
* all varlists and options passed to lassoshooting
* supports replay syntax
* lasso2 accommodates two cases: scalar lambda or list of lambdas (default)
* Updates (release date):
* 1.0.03 (30jan2018)
* First public release.
* Promoted to require version 13 or higher.
* Added holdout option and related changes.
* Replaced noprestd with prestd and related changes; added unitloadings option.
* Recoding of cons and demeaning flags. Std loadings based on demeaned vars even with nocons.
* partial and nocons no longer compatible.
* 1.0.04 (10feb2018)
* Support for Sergio Correia's FTOOLS FE transform (if installed).
* 1.0.05 (4apr2018)
* Support for information criteria added. DisplayPath program has been modified accordingly.
* lic(string) and ic(string) options were added. Added various results that are stored in e().
* See lassoutils 1.0.08 for underlying technical changes.
* Added ic(none) and noic options; both suppress calculation of information criteria.
* 1.0.06 (4sep2018)
* Fixed small typo in error message ("type 'lasso2, lic(ebic)' after estimation").
* lasso2 can now be directly called with lic() option, e.g. "lasso2 y x*, lic(ebic)" [24/04/18]
* Added plotpath(lnlambda) and adjusted parameters of plotlabel option. [27/04/18]
* Added "ebicgamma" option, see notes in lassoutils.ado. [04/09/2018]
* Fixed bug when fe used with partial(.).
* 1.0.07 (8nov2018)
* Added saved value of objective function for estimation with a single lambda/alpha.
* Added version option
* Replaced "postest" option with name "postresults"; legacy support for postest.
* 1.0.08 (12jan2019)
* Replace Ups terminology with Psi (penalty loadings)
* Bug fix - FE + weights would fail if data were not sorted on xtset panel var.
* 1.0.09 (28jun2019)
* Minor tweaks to display table (to get line to default 80 chars) and message.
* Bug fix - plotvar(.) option would fail with FV interactions.
* Fix to accommodate if inrange(.) syntax.
* 1.0.10 (4oct2019)
* Fixed bug that occured when partial was used.
* Fixed bug: post-lasso coefficients were sometimes not returned in e(b)
* 1.1.11 (29july2020)
* Misc bug fixes: norecover option (should be ignored in DisplayCoefs - ignore if nothing
* partialled-out); stdcoef+prestd (stdcoef implies prestd); fe option requires earlier
* pre-check for markout; plot no longer assumes varabbrev=on.
* Model s (#selected) now excludes constant; consistently excludes constant, #partialled, #FE.
* Model df includes constant (if not FE), #partialled.
* Added dofminus/sdofminus to capture lost degrees of freedom from partial/FE.
* Added e(.) macros r2, df & untrunc lists lambdamat0, lmin0, lmax0.
* Added support for psolver option.
* 1.1.12 (27sept2020)
* stdcoef option implies norecover (can't recover std coefs for partialled out vars or constant).
* stdcoef option implemented here; lassoutils returns both std and unstd coefs.
* Combination of ploadings(.)+unitloadings and adaptive+unitloadings now allowed.
* Added nostd option - synonym for unitloadings but clearer when used with lglmnet.
* Added stdall option - standardized lambda, L1, ICs, as well as coefficients. stdall=>stdcoef.
* Fixed bug in display in partialled-out vs factor variables.
* e(objfn) replaces e(pmse) and e(prmse).
* 1.1.13 (5jan2024)
* Misc code snippets to support sklearn option.
program lasso2, eclass sortpreserve
version 13
syntax [anything] [if] [in] [, ///
PLOTpath(string) /// "norm" or "lambda" allowed
PLOTVar(varlist min=1 fv ts) /// optional subset of variables to plot
partial(varlist fv ts) ///
psolver(string) /// optional solver for partialling out
PLOTOpt(string) /// options to pass to graph command
PLOTLabel ///
POSTRESults ///
POSTEst /// legacy option, now replaced by postresults
NEWLambda(numlist >0 min=1 max=1) ///
NEWAlpha(numlist >=0 min=1 max=1) ///
wnorm ///
NOPATH /// suppress display
displayall /// display zeros of beta, only applicable for one lambda
NORecover /// don't recover partialled-out coeffs
long ///
lic(string) /// for replay
ic(string) /// for lasso2 output
NOIC ///
VERsion ///
OLS ///
* ///
]
local lversion 1.0.12
local pversion 1.4.1
if "`version'" != "" { // Report program version number, then exit.
di in gr "lasso2 version `lversion'"
di in gr "lassopack package version `pversion'"
ereturn clear
ereturn local version `lversion'
ereturn local pkgversion `pversion'
exit
}
*** legacy option postest replaced by postresults
if "`postest'" != "" {
local postresults postresults
di as err "'postest' option has been renamed to 'postresults'. Please use 'postresults' instead."
}
*
*** noic and ic(none)
// omit calculation of IC if either noic or ic(none) is used
if "`noic'"!="" {
local ic none
}
if "`ic'"=="none" {
local noic noic
}
*
*** initialise local that saves whether est results are in hold
local inhold=0
*** first run of _lasso2; there is a 2nd _lasso2 call if lic() is specified
// 3 cases:
// (a) no replay syntax (with or w/o lic): standard case; also used by cvlasso
// (b) replay syntax and lic(): re-run with lambda selected by IC
// (c) replay syntax and newlambda(): re-run with newlambda, used by lasso2_p
if (~replay()) {
// no replay. estimate model.
// this is the standard case of a fully specified model.
// newlambda() and newalpha() are required for cvlasso.
// noic and lic are incompatible
if ("`noic'"!="") & ("`lic'"!="") {
di as err "lic and noic are incompatible. noic ignored."
local noic
}
if ("`lic'"!="") {
local notypemessage notypemessage
}
*
// estimate
_lasso2 `anything' `if' `in', `options' ///
newlambda(`newlambda') ///
newalpha(`newalpha') ///
partial(`partial') ///
psolver(`psolver') ///
`norecover' ///
`noic' ///
`ols'
ereturn local lasso2opt `options'
}
else if (replay()) & ("`newlambda'`newalpha'"!="") & ("`lic'"=="") {
// replay syntax.
// re-estimate model with (new) single lambda (and alpha) value.
// newlambda() and newalpha() options are undocumented.
// this case is (primarily) intended for lasso2_p.
// check for lasso2 results
if ("`e(cmd)'"!="lasso2") {
di as error "lasso2 estimation results not found"
exit 301
}
// estimate
local depvar `e(depvar)'
local varXmodel `e(varXmodel)'
local lasso2opt `e(lasso2opt)'
local partial_vars `e(partial_var)'
tempvar esample
gen `esample' = e(sample) // ensure same sample is used
_lasso2 `depvar' `varXmodel' `partial_vars' if `esample', ///
partial(`partial_vars') ///
psolver(`psolver') ///
`lasso2opt' ///
newlambda(`newlambda') ///
newalpha(`newalpha') ///
`ols'
ereturn local lasso2opt `lasso2opt'
}
else if (replay()) & ("`newlambda'`newalpha'"=="") & ("`lic'"!="") {
// replay syntax.
// re-estimate model with lic value.
// check for lasso2 results
if ("`e(cmd)'"!="lasso2") {
di as error "lasso2 estimation results not found"
exit 301
}
*
// set newlambda to lambda selected by IC
if ("`lic'"=="bic") {
local newlambda = e(lbic)
}
else if ("`lic'"=="aic") {
local newlambda = e(laic)
}
else if ("`lic'"=="aicc") {
local newlambda = e(laicc)
}
else if ("`lic'"=="ebic") {
//local ic ebic // is this required?
local newlambda = e(lebic)
}
else {
di as err "lic(`lic') not allowed. Select aic, bic, aicc or ebic."
exit 198
}
*
// estimate
local depvar `e(depvar)'
local varXmodel `e(varXmodel)'
local lasso2opt `e(lasso2opt)'
local partial_vars `e(partial_var)'
local licstrupper=strupper("`lic'")
di as text ""
di as text "Use lambda=`newlambda' (selected by `licstrupper')."
tempvar esample
gen `esample' = e(sample) // ensure same sample is used
if ("`postresults'"=="") {
tempname model0
_estimates hold `model0'
local inhold = 1
}
_lasso2 `depvar' `varXmodel' `partial_vars' if `esample', ///
partial(`partial_vars') ///
psolver(`psolver') ///
`lasso2opt' ///
newlambda(`newlambda') ///
`ols'
ereturn local lasso2opt `lasso2opt'
}
else {
if ("`newlambda'`newalpha'"!="") & ("`lic'"!="") {
di as error "internal lasso2 error. newlambda and lic specified."
exit 301
}
}
*
*** show output if lambda is a list
if (`e(lcount)'>1) & !missing(`e(lcount)') {
// display should be the same as lic()
if "`lic'"!="" {
local ic `lic'
}
*
if "`nopath'"=="" {
DisplayPath, `wnorm' `long' ic(`ic') `notypemessage'
}
if ("`plotpath'`plotvar'`plotopt'"!="") {
plotpath, plotpath(`plotpath') ///
plotvar(`plotvar') ///
plotopt(`plotopt') ///
`plotlabel' ///
`wnorm'
}
}
*
*** second run of _lasso2
// only applicable if lasso2 is called with lic option
// re-estimate for single lambda
if (~replay()) & ("`lic'"!="") {
* check that lambda was a list in previous estimation
if (`e(lcount)'==1) {
di as err "lic() only allowed if lambda() is a list."
exit 198
}
* set newlambda to lambda selected by IC
if ("`lic'"=="aic") {
local newlambda = e(laic)
}
else if ("`lic'"=="bic") {
local newlambda = e(lbic)
}
else if ("`lic'"=="aicc") {
local newlambda = e(laicc)
}
else if ("`lic'"=="ebic") {
local newlambda = e(lebic)
}
else {
di as err "lic(`lic') not allowed. Select aic, bic, aicc or ebic."
exit 198
}
local depvar `e(depvar)'
local varXmodel `e(varXmodel)'
local lasso2opt `e(lasso2opt)'
local partial_vars `e(partial_var)'
local licstrupper=strupper("`lic'")
di as text ""
di as text "Use lambda=`newlambda' (selected by `licstrupper')."
tempvar esample
gen `esample' = e(sample) // ensure same sample is used
if ("`postresults'"=="") {
tempname model0
_estimates hold `model0'
local inhold = 1
}
_lasso2 `depvar' `varXmodel' `partial_vars' if `esample', ///
partial(`partial_vars') ///
psolver(`psolver') ///
`lasso2opt' ///
newlambda(`newlambda') ///
`ols'
ereturn local lasso2opt `lasso2opt'
}
*
*** Show ouput if lambda is a scalar
if `e(lcount)'==1 {
// norecover should be ignored in DisplayCoefs, depends only on what was estimated
DisplayCoefs, `displayall'
if ("`plotpath'`plotvar'`plotopt'`plotlabel'"!="") {
di as error "Plotting only supported for list of lambda values."
di as error "Plotting options ignored."
}
}
*
*** unhold estimation results
if ("`postresults'"=="") & (`inhold'==1) {
_estimates unhold `model0'
}
end
program _lasso2, eclass sortpreserve
version 13
syntax varlist(numeric min=2 fv ts) [if] [in] [, ///
NOTPen(string) /// list of variables not penalised
PARtial(string) /// string so that list can contain "_cons"
psolver(string) /// optional solver for partialling out
fe /// do within-transformation
NOCONStant ///
NORecover /// recover partialled out coefficients
///
/// debug & more info
debug /// used for debugging
Verbose /// pass to lassoshooting
VVerbose /// pass to lassoshooting
displaynames_o(string) /// dictionary with names of vars as supplied in varlist
displaynames_d(string) /// corresponding display names of vars
pminus(int 0) /// not used; just means rlasso code also works here
///
/// lambda
Lambda(numlist >0 min=1 descending) /// L1 penalty, either list or scalar
lambda2(numlist >0 min=1 descending) /// optional L2 penalty, either list or scalar
LFactor(real 1) ///
LAMBDAMat(string) /// alternative: specify L1 lambda as matrix
lambda2mat(string) /// alternative: specify L2 lambda as matrix
NEWLambda(numlist >0 min=1 max=1 ) /// scalar
NEWPloadings(string) ///
Ploadings(string) /// L1 norm loadings
ploadings2(string) /// L2 norm loadings
UNITLoadings ///
lglmnet /// use glmnet parameterization
sklearn /// use sklearn code
///
/// standardization
PREStd ///
STDCoef ///
STDAll ///
NOSTD /// synonym for unitloadings; for use with lglmnet
///
/// choice of estimator
ADAptive /// adaptive lasso
ADATheta(real 1) /// gamma paramater for adapLASSO
ADALoadings(string) ///
ALPha(numlist >=0 ascending) /// elastic net parameter
NEWAlpha(numlist >=0 min=1 max=1) ///
SQRT /// square-root lasso
OLS ///
///
POSTAll ///
holdout(varlist numeric min=1 max=1) ///
///
NOFTOOLS ///
///
NOIC ///
* ///
]
*** convenience option for lglmnet
if "`nostd'"~="" {
local unitloadings unitloadings
}
*
*** flags
local feflag =("`fe'"~="")
local debugflag =("`debug'"~="")
local lglmnetflag =("`lglmnet'"~="")
local sklearnflag =("`sklearn'"~="")
local prestdflag =("`prestd'"~="")
*
** reset lambda, used for predict & replay
if ("`newlambda'"!="") {
local lambda = `newlambda'
}
if ("`newalpha'"!="") {
local alpha = `newalpha'
}
if ("`newploadings'"!="") {
tempname ploadings
mat `ploadings' = `newploadings'
// clear these macros
local adaptive
local prestd
}
// set alpha default.
local alphacount : word count `alpha'
if (`alphacount'==0) {
local alpha = 1
}
else if (`alphacount'>1) {
di as err "alpha() must be a scalar."
exit 198
}
// adapative - any adaptive options/variants implies adaptive
if ("`adaloadings'"~="") | (`adatheta'~=1) {
local adaptive adaptive
}
*
****** syntax checks *******************************************************
if (`alpha'>1) | (`alpha'<0) {
di as err "alpha is out of range."
exit 198
}
if ("`sqrt'"!="") & (`alpha'!=1) {
di as error "sqrt-lasso only allowed with alpha=1."
exit 198
}
local notpenpar : list notpen & partial
if ("`notpenpar'"!="") {
di as error "`notpenpar' listed in both notpen(.) and partial(.)"
exit 198
}
local checkflag = ("`ploadings'"!="")+("`adaptive'"!="")
if `checkflag'>1 {
di as error "error: cannot combine options ploadings(.) and adaptive"
exit 198
}
*
****************************************************************************
*** Record which observations have non-missing values
marksample touse
// need to check panel var up here
if `feflag' {
cap xtset
local ivar `r(panelvar)'
}
markout `touse' `varlist' `ivar' `holdout'
sum `touse' if `touse', meanonly // will sum weight var when weights are used
local N = r(N)
tempvar toest
qui gen `toest' = `touse'
if ("`holdout'"!="") {
assert `holdout' == 1 | `holdout'==0 if `touse'
qui replace `toest' = 0 if `holdout'
}
*
*** FEs.
if `feflag' {
if "`ivar'"=="" {
di as err "Error: fe option requires data to be xtset"
exit 459
}
// fe transformation may expect data to be sorted on ivar
local sortvar : sortedby
local sortvar : word 1 of `sortvar' // in case sorted on multiple variables
if "`ivar'"~="`sortvar'" {
di as text "(sorting by xtset panelvar `ivar')"
sort `ivar'
}
}
*
*** sklearn
// sklearn requires lglmnet
if `sklearnflag' & ~`lglmnetflag' {
di as res "note - sklearn option implies lglmnet option/parameterization"
local lglmnet lglmnet
local lglmnetflag=1
}
*
*** lglmnet
// glmnet treats penalty loadings and standardization separately
if `lglmnetflag' {
// requires either prestandardization or unit loadings
if "`unitloadings'"=="" {
local prestd prestd
}
}
*
*** constant, partial, etc.
// conmodel: constant in original model
// consflag: constant in transformed equation to estimate
local consmodel =("`noconstant'"=="") & ~`feflag' // if fe, then cons=0 & partialcons=""
local partial : subinstr local partial "_cons" "", all word count(local pconscount)
local notpen : subinstr local notpen "_cons" "", all word count(local notpenconscount)
if (`notpenconscount'>1) {
di as err "Warning: notpen(_cons) not supported. Constant is always partialled out."
}
local partialflag = ("`partial'"~="") // =1 if regressor other than constant is partialled out
local notpenflag = ("`notpen'"~="") // =1 if regressor other than constant is not penalised
local stdallflag = ("`stdall'"~="") // return everything in std units
if `stdallflag' {
local stdcoef stdcoef // stdall => stdcoef
}
local stdcoefflag = ("`stdcoef'"~="") // return coef estimates in std units
local prestdflag = ("`prestd'"~="") // =1 if data to be pre-standardized
// default is to use standardization loadings; overridden by ploadings, unitloadings, pre-standardization, adaptive
local stdloadflag = ("`ploadings'`unitloadings'`prestd'`adaptive'"=="")
local sqrtflag = ("`sqrt'"!="")
// ignore norecover if no partialled-out variables
local parrflag = ("`norecover'"=="") & (`partialflag' | `prestdflag')
*
// if partial list has factor vars, will need to be replaced with tempvars
cap _fv_check_depvar `partial'
local partialfvflag =(_rc==198)
// Tell estimation code if cons has been partialled out or there isn't one in the first place
if `feflag' | `partialflag' | `prestdflag' | (~`consmodel') {
local consflag 0
}
else {
local consflag 1
}
*
*** create main varlist and tempvars
// remove duplicates from varlist
// _o list is vars with original names
fvexpand `varlist' if `touse'
local varlist_o `r(varlist)'
// check for duplicates has to follow expand
local dups : list dups varlist_o
if "`dups'"~="" {
di as text "Dropping duplicates: `dups'"
}
local varlist_o : list uniq varlist_o
*
*** Create separate _o varlists: Y, X, notpen, partial
// Y, X
local varY_o : word 1 of `varlist_o'
local varX_o : list varlist_o - varY_o // incl notpen/partial
// notpen
fvexpand `notpen' if `touse'
local notpen_o `r(varlist)'
local dups : list dups notpen_o
if "`dups'"~="" {
di as text "Dropping duplicates: `dups'"
}
local notpen_o : list uniq notpen_o
// partial
fvexpand `partial' if `touse'
local partial_o `r(varlist)'
local dups : list dups partial_o
if "`dups'"~="" {
di as text "Dropping duplicates: `dups'"
}
local partial_o : list uniq partial_o
// "model" = vars without partialled-out
local varXmodel_o : list varX_o - partial_o
*
*** syntax checks
// check that notpen vars are in full list
local checklist : list notpen_o - varX_o
local checknum : word count `checklist'
if `checknum' {
di as err "syntax error - `checklist' in notpen(.) but not in list of regressors"
exit 198
}
// check that partial vars are in full list
local checklist : list partial_o - varX_o
local checknum : word count `checklist'
if `checknum' {
di as err "syntax error - `checklist' in partial(.) but not in list of regressors"
exit 198
}
// check that ivar (FE) is not a used variable
if `feflag' {
fvrevar `varY_o' `varX_o', list // list option means we get only base vars
local vlist `r(varlist)'
local checklist : list ivar - vlist
local checknum : word count `checklist'
if `checknum'==0 {
di as err "syntax error - `ivar' is xtset variable and cannot be used in model"
exit 198
}
}
// other checks
if `pconscount' & `feflag' {
di as err "error: incompatible options, partial(_cons) and fe"
exit 198
}
if "`partial'"~="" & "`noconstant'"~="" {
di as err "error: incompatible options, partial and nocons"
exit 198
}
if `feflag' & "`noconstant'"~="" {
di as err "error: incompatible options, fe and nocons"
exit 198
}
*
*** Create _t varlists: Y, X, notpen, partial
// _o list is vars with original names
// _t list is temp vars if transform needed, original vars if not
if `feflag' { // everything needs to be transformed including partial
local temp_ct : word count `varlist_o'
mata: s_maketemps(`temp_ct')
local varlist_t `r(varlist)'
}
else if `partialflag' | `prestdflag' { // everything except partial_o needs to be transformed
local varYXmodel_o `varY_o' `varXmodel_o'
local temp_ct : word count `varYXmodel_o'
mata: s_maketemps(`temp_ct')
local varYXmodel_t `r(varlist)'
matchnames "`varlist_o'" "`varYXmodel_o'" "`varYXmodel_t'"
local varlist_t `r(names)'
}
else { // no transformation needed but still need temps
fvrevar `varlist_o' if `touse' // fvrevar creates temps only when needed
local varlist_t `r(varlist)'
}
// dictionary is now varlist_o / varlist_t
// now create separate _o and _t varlists using dictionary
foreach vlist in varY varX varXmodel notpen partial {
matchnames "``vlist'_o'" "`varlist_o'" "`varlist_t'"
local `vlist'_t `r(names)' // corresponding tempnames; always need this because of possible fvs
}
*
******************* Display names ***********************************************************
// may be called by another program with tempvars and display names for them
// if display names option not used, use _o names as provided in rlasso command
// if display names option used, use display names matched with _o names
// if display names macros are empty, has no effect
matchnames "`varY_o'" "`displaynames_o'" "`displaynames_d'"
local varY_d `r(names)'
matchnames "`varXmodel_o'" "`displaynames_o'" "`displaynames_d'"
local varXmodel_d `r(names)'
matchnames "`varX_o'" "`displaynames_o'" "`displaynames_d'"
local varX_d `r(names)'
matchnames "`notpen_o'" "`displaynames_o'" "`displaynames_d'"
local notpen_d `r(names)'
matchnames "`partial_o'" "`displaynames_o'" "`displaynames_d'"
local partial_d `r(names)'
*
*** summary varlists and flags:
* cons = 1 if constant, 0 if not
* varY_o = dep var
* varY_t = dep var, temp var
* varX_o = full, expanded set of RHS, original names, includes partial
* varX_t = as above but with temp names for all variables
* varXmodel_o = full, expanded set of RHS, original names, excludes partial
* varXmodel_t = as above but with temp names for all variables
* notpen_o = full, expanded set of not-penalized
* notpen_t = as above but with temp names for all variables
// p is calculated in lassoutils as number of model vars excluding constant
// here we calculate which of the model vars are omitted/base vars
// to provide as `pminus' to lassoutils
// use _o names / display names since they have info on whether var is omitted/base/etc.
if ~`pminus' {
foreach vn of local varXmodel_d { // display names
_ms_parse_parts `vn'
// increment pminus if model variable is MISSING
if r(omit) {
local ++pminus
}
}
}
// p0 here is total number of variables provided to model EXCLUDING constant
local p0 : word count `varXmodel_o'
local p =`p0'-`pminus'
*
******************* FE, partialling out, standardization ************************************
// If FE: partial-out FEs from temp variables, then preserve,
// then partial-out low-dim ctrls from temp variables
// restore will restore all temp vars with only FEs partialled-out
// If no FE: leave original variables unchanged.
// partial-out low-dim ctrls from temp variables.
// if no FE/low-dim ctrls, no transform needed
// dofminus/sdofminus captures lost degrees of freedom from FE/partialling
local dofminus =0 // overwritten by FE count
local sdofminus =`consmodel' // initial "small" df count is cons/nocons
local dmflag =0 // initialize demeaned flag
if `feflag' { // FE-transform all variables
fvrevar `varY_o' `varX_o' if `touse' // in case any FV or TS vars in _o list
local vlist `r(varlist)'
lassoutils `vlist', /// call on _o list
touse(`touse') ///
toest(`toest') ///
tvarlist(`varY_t' `varX_t') /// overwrite/initialize these
`noftools' ///
fe(`ivar') // triggers branching to FE utility
local dofminus =r(N_g) // overwrite dofminus
local N_g =r(N_g) // N_g will be empty if no FEs
local noftools `r(noftools)' // either not installed or user option
local dmflag=1 // data are now demeaned
if `partialflag' { // And then partial out any additional vars
preserve // preserve the original values of tempvars before partialling out
lassoutils `varY_t' `varXmodel_t', /// _t vars have been created and filled so use here
touse(`touse') /// don't need tvarlist because vars already created
toest(`toest') /// don't need tvarlist because vars already created
partial(`partial_t') /// _t vars have been created and filled so use here
partialflag(`partialflag') /// triggers branching to partial utility
psolver(`psolver') /// optional choice of solver
dmflag(1) // FE => mean zero
local sdofminus =r(rank) // small dof is #partialled
}
if `prestdflag' {
tempname prestdY prestdX
lassoutils `varY_t', /// _t vars have been created and filled so use here
touse(`touse') /// don't need tvarlist because vars already created
toest(`toest') ///
std ///
dmflag(1) // FE => data already mean zero
mat `prestdY'=r(stdvec)
lassoutils `varXmodel_t', ///
touse(`touse') ///
toest(`toest') ///
std ///
dmflag(1) // FE => data already mean zero
mat `prestdX'=r(stdvec)
}
}
else if `partialflag' { // Just partial out
fvrevar `varY_o' `varXmodel_o' if `touse' // in case any FV or TS vars in _o list
local vlist `r(varlist)'
fvrevar `partial_o' if `touse' // in case any FV or TS vars in _o list
local pvlist `r(varlist)'
lassoutils `vlist', /// call on _o list
touse(`touse') ///
toest(`toest') ///
partial(`pvlist') ///
tvarlist(`varY_t' `varXmodel_t') /// overwrite/initialize these
partialflag(`partialflag') /// triggers branching to partial utility
psolver(`psolver') /// optional choice of solver
dmflag(0) // data are not yet demeaned
local sdofminus =r(rank) // overwrite sdofminus with #partialled
local dmflag =1 // data are now demeaned
if `prestdflag' {
tempname prestdY prestdX
lassoutils `varY_t', /// _t vars have been created and filled so use here
touse(`touse') /// don't need tvarlist because vars already created
toest(`toest') ///
std ///
dmflag(1) // partial => already mean zero
mat `prestdY'=r(stdvec)
lassoutils `varXmodel_t', ///
touse(`touse') ///
toest(`toest') ///
std ///
dmflag(1) // partial => already mean zero
mat `prestdX'=r(stdvec)
}
}
else if `prestdflag' {
tempname prestdY prestdX
lassoutils `varY_o', /// call on _o list
touse(`touse') ///
toest(`toest') ///
std ///
tvarlist(`varY_t') /// overwrite/initialize these
consmodel(`consmodel') /// =1 => data should be demeaned
dmflag(0) // data not (yet) mean zero
mat `prestdY'=r(stdvec)
fvrevar `varXmodel_o' if `touse' // in case any FV or TS vars in _o list
local vlist `r(varlist)'
lassoutils `vlist', /// call on _o list
touse(`touse') ///
toest(`toest') ///
std ///
tvarlist(`varXmodel_t') /// overwrite/initialize these
consmodel(`consmodel') /// =1 => data should be demeaned
dmflag(0) // data not yet mean zero
mat `prestdX'=r(stdvec)
if `consmodel' {
local dmflag =1 // if cons in model, data are now demeaned
}
}
*************** lambda to matrix **************************************************
// lambda provided either as scalar(s) or matrix; convert to matrix
// macro lambdamat0 will be empty if not provided
// optional adjustment using undocumented lfactor option used for CV
if "`lambda'`lambdamat'"!="" {
tempname lambdamat0
getlambdamat, lscalar(`lambda') lmatrix(`lambdamat') lfactor(`lfactor')
mat `lambdamat0' = r(lambdamat)
}
// optional L2 norm lambda
if "`lambda2'`lambda2mat'"!="" {
tempname lambda2mat0
getlambdamat, lscalar(`lambda2') lmatrix(`lambda2mat') lfactor(`lfactor')
mat `lambda2mat0' = r(lambdamat)
}
*
************* Partialling/standardization END ***********************************************
*** Lasso estimation with transformed/partialled-out vars
if "`verbose'`vverbose'"=="" {
local quietly "quietly" // don't show lassoutils output
}
*** Lasso estimation
`quietly' lassoutils `varY_t', ///
path /// branches to _lassopath
toest(`toest') ///
xnames_o(`varXmodel_d') /// display name
xnames_t(`varXmodel_t') ///
consflag(`consflag') /// =0 if cons already partialled out or if no cons
stdallflag(`stdallflag') /// =1 if lambdas etc. are provided in the standardized metric
dmflag(`dmflag') /// =1 if data have been demeaned
dofminus(`dofminus') /// dofs lost from FEs
sdofminus(`sdofminus') /// dofs lost from partialling
pminus(`pminus') ///
notpen_o(`notpen_d') /// not penalised (display name)
notpen_t(`notpen_t') ///
lambda(`lambdamat0') ///
lambda2(`lambda2mat0') ///
`adaptive' ///
adatheta(`adatheta') ///
adaloadings(`adaloadings') ///
`sqrt' ///
`ols' ///
alpha(`alpha') ///
stdy(`prestdY') ///
stdx(`prestdX') ///
stdl(`stdloadflag') /// use standardization loadings
ploadings(`ploadings') /// L1 norm loadings
ploadings2(`ploadings2') /// L2 norm loadings
`verbose' `vverbose' ///
holdout(`holdout') ///
`noic' ///
`lglmnet' /// use glmnet parameterization
`sklearn' /// use sklearn code
`options'
************* Finish up ********************************************************
*** Create macros etc.
local lcount =r(lcount)
if (`lcount'==1) { //------- scalar lambda -----------------------------------------------//
// message relevant for single lambda only
if `stdcoefflag' {
di as text "note: option stdcoef implies norecover; no constant reported"
// set partial-recovery flag to 0
local parrflag 0
}
*** e-return lasso estimation results
tempname b beta betaOLS sbeta sbetaOLS Psi stdvec
tempname betaAll betaAllOLS sbetaAll sbetaAllOLS
tempname lambda slambda lambda0 rmse rmseOLS objfn srmse srmseOLS sobjfn r2 df
if "`cluster'" ~= "" {
local N_clust =r(N_clust)
}
mat `beta' =r(beta) // may be empty!
mat `betaOLS' =r(betaOLS) // may be empty!
mat `betaAll' =r(betaAll)
mat `sbeta' =r(sbeta)
mat `sbetaOLS' =r(sbetaOLS)
mat `betaAllOLS' =r(betaAllOLS)
mat `sbetaAll' =r(sbetaAll)
mat `sbetaAllOLS' =r(sbetaAllOLS)
mat `Psi' =r(Psi)
//*//mat `sPsi' =r(sPsi)
mat `stdvec' =r(stdvec)
scalar `lambda' =r(lambda)
scalar `slambda' =r(slambda)
scalar `lambda0' =r(lambda0)
scalar `rmse' =r(rmse) // Lasso RMSE
scalar `rmseOLS' =r(rmseOLS) // post-Lasso RMSE
scalar `srmse' =r(srmse) // Standardized Lasso RMSE
scalar `srmseOLS' =r(srmseOLS) // Standardized post-Lasso RMSE
scalar `r2' =r(r2)
scalar `df' =r(df)
scalar `objfn' =r(objfn)
scalar `sobjfn' =r(sobjfn)
local selected `r(selected)' // EXCL NOTPEN/CONS
local selected0 `r(selected0)' // INCL NOTPEN, EXCL CONS
local s =r(s) // EXCL NOTPEN/CONS; number of elements in selected
local s0 =r(s0) // INCL NOTPEN, EXCL CONS; number of elements in selected0
local k =r(k) // number of all variables in beta INCL NOTPEN/CONS (if present)
local p0 =r(p0) // number of all variables in betaAll INCL NOTPEN/CONS (if present)
//*//local clustvar `r(clustvar)'
//*//local robust `r(robust)'
//*//local center =r(center)
local sqrtflag =r(sqrt)
local alpha =r(alpha)
local olsflag = r(olsflag)
local method `r(method)' // lasso or sqrt-lasso
local niter =r(niter)
local maxiter =r(maxiter)
//*//local nupsiter =r(nupsiter)
//*//local maxupsiter =r(maxupsiter)
// issue warning if lasso max iteration limit hit
if `niter'==`maxiter' {
di as text "Warning: reached max shooting iterations w/o achieving convergence."
}
// fix depvar (rownames) of beta vectors to use _o (or _d if display names provided) not _t
mat rownames `beta' = `varY_d'
mat rownames `betaOLS' = `varY_d'
mat rownames `betaAll' = `varY_d'
mat rownames `betaAllOLS' = `varY_d'
mat rownames `sbeta' = `varY_d'
mat rownames `sbetaOLS' = `varY_d'
mat rownames `sbetaAll' = `varY_d'
mat rownames `sbetaAllOLS' = `varY_d'
// used below
if `k'>0 { // cnames will be empty if k=0
local cnames_o : colnames `beta'
fvstrip `cnames_o' // colnames may insert b/n/o operators - remove
local cnames_o `r(varlist)'
matchnames "`cnames_o'" "`varlist_o'" "`varlist_t'"
local cnames_t `r(names)'
}
if `debugflag' {
di as text "selected: `selected'"
di as text "Returned results from lassoutils:"
return list
di as text "beta and betaOLS:"
mat list `beta'
mat list `betaOLS'
}
*
*********** Get coeff estimates for partialled-out vars. ********************
if `feflag' & `partialflag' { // FE case and there are partialled-out notpen vars
restore // Restores dataset with tempvars after FE transform but before notpen partialled out
}
if (`partialflag' | (`prestdflag' & `consmodel')) & (`parrflag') { // standardization removes constant so must enter for that
if `feflag' {
local depvar `varY_t' // use FE-transformed depvar and X vars
local scorevars `cnames_t'
}
else {
local depvar `varY_o' // use original depvar and X vars
local scorevars `cnames_o'
}
lassoutils `depvar', ///
unpartial ///
touse(`toest') ///
beta(`beta') ///
scorevars(`scorevars') ///
partial(`partial_t') ///
names_o(`varlist_o') /// dictionary
names_t(`varlist_t') /// dictionary
consmodel(`consmodel')
mat `beta' = r(b)
mat `betaAll' = `betaAll', r(bpartial)
lassoutils `depvar', ///
unpartial ///
touse(`toest') ///
beta(`betaOLS') ///
scorevars(`scorevars') ///
partial(`partial_t') ///
names_o(`varlist_o') /// dictionary
names_t(`varlist_t') /// dictionary
consmodel(`consmodel')
mat `betaOLS' = r(b)
mat `betaAllOLS' = `betaAllOLS', r(bpartial)
// finish by adding partialled-out to k
local k =colsof(`beta')