-
Notifications
You must be signed in to change notification settings - Fork 3
/
lassologit.ado
2991 lines (2571 loc) · 75.3 KB
/
lassologit.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
*! lassologit (v0.3.1)
*! part of lassopack v1.4.3
*! last edited: 27mar2021
*! authors: aa/ms/cbh
* Updates (release date):
* v0.2 (10oct2019)
* fixed exp.exp bug that was affecting Stata 13
* v0.3 (15oct2019)
* fixed remaining exp.exp bug that was affecting Stata 13
* v0.3.1 (27mar2021)
* added warm-start lambda value if only one lambda
* predict doesn't re-estimate model by default but uses e(betas)
program lassologit, eclass sortpreserve
version 13
syntax [anything] [if] [in] [fw aw pw] ///
[, lic(string) ic(string) ///+
newlambda(numlist >0 min=1 max=1) ///~
POSTRESults ///
version ///
long ///
PLOTpath(string) ///
PLOTOpt(string) ///
PLOTVar(varlist) ///
PLOTLabel ///
lambdan nopath settingup ///
debug ///
* ]
if "`version'" != "" { // Report program version number, then exit.
di in gr "lassologit.ado version `lversion'"
di in gr "lassologit package version `pversion'"
ereturn clear
ereturn local version `lversion'
ereturn local pkgversion `pversion'
exit
}
//
*** initialise local that saves whether est results are in hold
local inhold=0
if (!replay()) {
tokenize "`0'", parse(",")
_lassologit `1', `options' newlambda(`newlambda') `lambdan' `debug'
ereturn local cmdoptions `options'
}
if (replay()) & ("`lic'"=="") & ("`newlambda'"!="") {
// re-estimate
local cmdoptions0 `e(cmdoptions)'
local depvar `e(depvar)'
local varX `e(varX)'
tempvar esample
qui gen byte `esample' = e(sample)
_lassologit `depvar' `varX' ///
if `esample' ///
[`weight' `exp'] , ///
`options' ///
newlambda(`newlambda') ///
`cmdoptions0' ///
`lambdan' `debug'
ereturn local cmdoptions `cmdoptions0'
}
if (replay()) & ("`lic'"!="") & ("`newlambda'"=="") {
// set lambda
if ("`lic'"=="ebic") {
local newlambda = `e(ebiclambda)'
}
else if ("`lic'"=="bic") {
local newlambda = `e(biclambda)'
}
else if ("`lic'"=="aic") {
local newlambda = `e(aiclambda)'
}
else if ("`lic'"=="aicc") {
local newlambda = `e(aicclambda)'
}
else if ("`lic'"!="") {
di as err "lic(`lic') not allowed."
di as err "Allowed options: 'ebic', 'bic', 'aic', 'aicc'."
exit 198
}
//
// re-estimate
local cmdoptions0 `e(cmdoptions)'
local depvar `e(depvar)'
local varX `e(varX)'
tempvar esample
gen byte `esample' = e(sample)
local licstrupper=strupper("`lic'")
//di as text ""
di as text "Use lambda=`newlambda' (selected by `licstrupper')."
if ("`postresults'"=="") {
tempname model0
_estimates hold `model0'
local inhold = 1
}
_lassologit `depvar' `varX' ///
if `esample' ///
[`weight' `exp'] , ///
`options' ///
newlambda(`newlambda') ///
`cmdoptions0' ///
`lambdan' `debug'
ereturn local cmdoptions `cmdoptions0'
}
else if (replay()) & ("`lic'"!="") & ("`newlamba'"!="") {
di as err "Internal error."
di as err "lic() and newlambda() not allowed at the same time."
exit 301
}
//
*** show output if lambda is a list
if (`e(lcount)'>1) {
// display should be the same as lic()
if "`lic'"!="" {
local ic `lic'
}
*
if "`nopath'"=="" & "`settingup'"=="" {
DisplayPath, `long' ic(`ic') `notypemessage' ///
`lambdan'
}
if ("`plotpath'`plotvar'`plotopt'"!="") {
plotpath2, plotpath(`plotpath') ///
plotvar(`plotvar') ///
plotopt(`plotopt') ///
`plotlabel' ///
`wnorm' ///
logistic
}
}
*
*** second run of _lassologit
// only applicable if lassologit 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(aiclambda)
}
else if ("`lic'"=="bic") {
local newlambda = e(biclambda)
}
else if ("`lic'"=="aicc") {
local newlambda = e(aicclambda)
}
else if ("`lic'"=="ebic") {
local newlambda = e(ebiclambda)
}
else {
di as err "lic(`lic') not allowed. Select aic, bic, aicc or ebic."
exit 198
}
local cmdoptions `e(cmdoptions)'
local depvar `e(depvar)'
local varX `e(varX)'
local licstrupper=strupper("`lic'")
di as text ""
di as text "Use lambda=`newlambda' (selected by `licstrupper')."
tempvar esample
qui gen byte `esample' = e(sample) // ensure same sample is used
if ("`postresults'"=="") {
tempname model0
_estimates hold `model0'
local inhold = 1
}
_lassologit `depvar' `varX' ///
if `esample' ///
[`weight' `exp'] , ///
`cmdoptions' ///
newlambda(`newlambda') ///
`lambdan' `debug'
ereturn local cmdoptions `cmdoptions'
}
*
*** Show ouput if lambda is a scalar
if (`e(lcount)'==1) {
DisplayCoefs, `displayall' `norecover'
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
cap program drop _lassologit
program _lassologit, eclass sortpreserve
version 13
syntax varlist(numeric min=1 fv ts) /// just y if x vars provided separately
[if] [in] [fw aw pw] [, ///
NOCONstant ///+
Lambda(numlist >0 min=1 descending) ///+
newlambda(numlist >0 min=1 max=1) ///~
VERBose ///+
///vverbose ///+
stdcoef ///+
NOStd ///+
stdfly ///~
stdsmart ///~
RIGorous ///~
c(real -1) ///+
gamma(real -1) ///+ the gamma of the rigorous lamba
EBICXi(real -1) ///+ EBIC gamma
///
vary_t(varlist numeric min=1) ///~ y var already parsed
varx_o(string) ///~ X vars already parsed
varx_t(varlist numeric min=1) ///~ X vars already parsed
bytelist(string) ///~ X vars already parsed
toest(varlist numeric min=1 max=1) ///~ estimation sample
holdout(varlist numeric min=1 max=1) ///+ holdout sample
touse(varlist numeric min=1 max=1) ///~ full sample
wvar(name) ///~
/// for out-of-sample prediction
psi(name) ///+ vector of (unstandardized) penalty loadings
spsi(name) /// vector of (standardized) penalty loadings
NOTPen(string) ///+
///Alpha(real 0) /// elastic net parameter [not implemented]
LOSSMeasure(string) ///+
///
/// optimisation
TOLOpt(real 10e-7) ///+
TOLZero(real 10e-10) ///+
MAXIter(int 10000) ///+
///
/// lambda
LCount(int 50) ///+
LMINRatio(real 10e-3) ///+
LMAX(real -1) ///+
LAMBDAN ///+ use as input/report as output lambda that incorporates 1/n
///
SETUPSTRUCT(name) ///~ don't estimate. return populated data struct and default lambda.
STRUCTNAME(name) ///~ use provided Mata data struct.
POSTLogit ///+
SAVEPred ///~
NOSEQRule ///~ use sequential rule
nopreserve ///~
debug ///~
QUADPrecision ///+
SUBSETRatio(real .5) ///~
NOPROgressbar ///+
hdmlambda /// use gamma as in hdm package
]
*** binary parameters
local debugflag = "`debug'"~=""
local weightflag = ("`weight'"~="")
local fweightflag = ("`weight'"=="fweight")
// by default _lassologit internally uses lambda that incorporates 1/n
// but reports lambda that does not incorporate 1/n
// lambdanflag=0 (default): reported lambdas need to be rescaled by n at the end
// and user=provided lambdas need to be deflated by 1/n before use
// lambdanflag=1 : no rescaling necessary
local lambdanflag = ("`lambdan'"~="")
local stdflyflag = ("`stdfly'"~="")
local stdsmartflag = ("`stdsmart'"~="")
local nodatastruct = ("`structname'"=="")
local cons = ("`noconstant'"=="")
local xstd = ("`nostd'"=="")
local stdcoef = ("`stdcoef'"!="")
local plogit = ("`postlogit'"!="")
local srule = ("`noseqrule'"=="")
local verb = ("`verbose'`vverbose'"!="")+("`vverbose'"!="")
local quadprec = ("`quadprecision'"!="")
local progbar = ("`noprogressbar'"=="")
local hdmlambda = ("`hdmlambda'"!="")
**
if (`cons'==0) {
local srule = 0
}
//
** no progress bar if verbose
if (`verb'>0) {
local progbar = 0
}
//
*** set default loss measure
if ("`lossmeasure'"=="") {
local lossmeasure deviance
}
//
*** initialize preserved flag to 0
local preserved = 0
*** syntax checks
// touse, toest and wvar allowed only with setting up data struct
if "`touse'`toest'`wvar'"~="" & "`setupstruct'"=="" {
di as err "error: touse(.) toest(.) wvar(.) can be used only with setupstruct option"
exit 198
}
if "`psi'"~="" & "`epsi'"~="" {
di as err "error: incompatible options psi(.) and epsi(.)"
exit 198
}
local stdoptcount : word count `stdfly' `stdsmart' `nostd'
if `stdoptcount'>1 {
di as err "error: incompatible options `stdfly' `stdsmart' `nostd'"
exit 198
}
// execute code for setting up data struct if none provided
if `nodatastruct' {
if "`varx_o'"=="" {
tokenize `varlist'
local varY_o `1'
macro shift
local varX_o `*'
}
else {
// if varlists provided, macro varlist has just y in it
local varY_o `varlist'
local varX_o `varx_o'
}
*** sample markers
*** mark full sample
if ("`touse'"=="") {
// marksample sets=0 if any vars in varlist are missing etc.
marksample touse
}
if ("`holdout'"=="") {
tempvar holdout
qui gen byte `holdout'=0 if `touse'
}
if ("`toest'"=="") {
tempvar toest
qui gen byte `toest' = 1-`holdout' if `touse'
}
// check
assert `holdout'==0 | `holdout'==1 if `touse'
assert `toest'==0 | `toest'==1 if `touse'
assert `toest'+`holdout'==1 if `touse'
*** check dependent variable
if "`vary_t'"=="" {
tempvar varY_t
gen byte `varY_t' = `varY_o'~=0
qui replace `varY_t' = . if `varY_o'==.
// varies within estimation sample?
sum `varY_t' if `toest', meanonly
cap assert r(mean)>0 & r(mean)<1
if _rc==9 {
di as err "error: outcome does not vary in estimation sample"
exit 2000
}
}
else {
local varY_t `vary_t'
}
//
*** weights
// `exp' includes the =
if `fweightflag' {
// fweights
if "`wvar'"=="" {
tempvar wvar
qui gen long `wvar' = .
}
qui replace `wvar' `exp'
}
else if `weightflag' {
// aweights and pweights
if "`weight'"=="aweight" {
// Stata's logit won't accept aweights
local weight pweight
}
if "`wvar'"=="" {
tempvar wvar
qui gen double `wvar' = .
}
qui replace `wvar' `exp'
sum `wvar' if `touse' `wtexp', meanonly
// Weight statement
di as text "(sum of wgt is " %14.4e `r(sum)' ")"
// normalize to have unit mean
qui replace `wvar' = `wvar' * r(N)/r(sum)
}
else {
// unweighted
if "`wvar'"=="" {
tempvar wvar
qui gen byte `wvar' = .
}
qui replace `wvar' = 1
}
**** settings (in this order)
**** precision, max iterations, logit (1) or linear (0), verbose
tempname settings
mata: `settings' = (`tolopt',`maxiter',1,`verb',`tolzero',`srule',`quadprec',`subsetratio',`progbar',`ebicxi',`hdmlambda')
// add to list of mata globals created
local mnamelist `mnamelist' `settings'
*** preserve
// preserve not needed if standardizing-on-the-fly
// if (("`nostd'"=="") | (`cons')) & ("`nopreserve'"=="") & (`stdflyflag'==0) {
if (`xstd') & ("`nopreserve'"=="") & (`stdflyflag'==0) {
preserve
local preserved = 1
}
//
*** ereturn clear
ereturn clear
//
*** duplicates, factor and time-series variables, temp vars
if "`varx_o'"=="" {
// expand and replace macro
fvexpand `varX_o' if `touse'
local varX_o `r(varlist)'
// check for duplicates has to follow expand
local dups : list dups varX_o
if "`dups'"~="" {
di as text "Dropping duplicates: `dups'"
}
local varX_o : list uniq varX_o
// make X temp doubles unless using stdsmart
if `stdsmartflag' {
foreach var of local varX_o {
// determine whether variable exists
_ms_parse_parts `var'
if "`r(op)'`r(op1)'"=="" {
// no fv or ts operator, variable exists
// determine variable type
local stype : type `var'
if "`stype'"=="byte" {
// create byte temp var
tempvar v
qui gen byte `v' = `var'
local varX_t `varX_t' `v'
local bytelist `bytelist' 1
}
else {
// create double temp var
tempvar v
qui gen double `v' = `var'
local varX_t `varX_t' `v'
local bytelist `bytelist' 0
}
}
else {
// fv or ts operator, use fvrevar
fvrevar `var'
local rv `r(varlist)'
local stype : type `rv'
if "`stype'"=="byte" {
local varX_t `varX_t' `rv'
local bytelist `bytelist' 1
}
else {
tempvar v
qui gen double `v' = `rv'
local varX_t `varX_t' `v'
local bytelist `bytelist' 0
}
}
}
}
else {
// default - all temps are doubles
foreach var of local varX_o {
tempvar v
qui gen double `v' = `var'
local varX_t `varX_t' `v'
local bytelist `bytelist' 0
}
}
}
else {
local varX_o `varx_o'
local varX_t `varx_t'
// bytelist already provided
}
*** notpen list
// expand and check if all notpen() vars are in varX_o list
if ("`notpen'"!="") {
fvexpand `notpen' if `touse'
local notpen_o `r(varlist)'
local NotpNotVarX : list notpen_o - varX_o
if ("`NotpNotVarX'"!="") {
di as err "Error in notpen(): `NotpNotVarX' not in list of predictors"
exit 198
}
}
//
} // end code that is required for setting up the data struct
else {
// if populated data struct is provided, preserve Stata data in case of standardization etc.
// preserve not needed if standardizing-on-the-fly
// if (("`nostd'"=="") | (`cons')) & ("`nopreserve'"=="") & (`stdflyflag'==0) {
if (`xstd') & ("`nopreserve'"=="") & (`stdflyflag'==0) {
preserve
local preserved = 1
}
// and restore saved locals from data struct
mata: st_local("wvar",dataStructSelect(`structname',"Wname"))
mata: st_local("touse",dataStructSelect(`structname',"tousename"))
mata: st_local("toest",dataStructSelect(`structname',"toestname"))
mata: st_local("holdout",dataStructSelect(`structname',"holdoutname"))
}
*** prepare data, store in structure
*** MakeData() creates views of full dataset etc.
*** SelectData() creates subviews of estimation and holdout samples etc.
*** StandardizeData() standardizes the estimation sample.
if "`setupstruct'"~="" {
// setupstruct sets up data struct and lambdas; no estimation
mata: `setupstruct'=MakeData("`varX_o'","`varX_t'","`bytelist'","`wvar'","`weight'","`exp'","`varY_t'","`touse'","`toest'","`holdout'","`notpen_o'",`cons',`xstd',`stdflyflag',`stdsmartflag',`plogit',`settings')
mata: SelectData(`setupstruct')
// StandardizeData also sets up ploadings
mata: StandardizeData(`setupstruct',"`psi'","`spsi'")
tempname lambdas
// _lassologit internal lambdas already incorporate factor of 1/n
mata: `lambdas' = calcDefLambdas(`setupstruct',`lmax',`lcount',`lminratio')
// add to list of mata globals created
local mnamelist `mnamelist' `lambdas'
mata: st_matrix("e(lambdas)",`lambdas')
mata: st_numscalar("e(lcount)",cols(`lambdas'))
mata: st_numscalar("e(N)",dataStructSelect(`setupstruct',"total_trials"))
ereturn local structname `setupstruct'
if (`preserved') {
restore
}
}
else {
// estimate
if "`structname'"=="" {
// if data struct not provided, create it
tempname data
mata: `data'=MakeData("`varX_o'","`varX_t'","`bytelist'","`wvar'","`weight'","`exp'","`varY_t'","`touse'","`toest'","`holdout'","`notpen_o'",`cons',`xstd',`stdflyflag',`stdsmartflag',`plogit',`settings')
// and since created here, add to list of mata objects to clear at the end
local mnamelist `mnamelist' `data'
}
else {
// data struct provided
local data `structname'
}
mata: SelectData(`data')
// StandardizeData also sets up ploadings
mata: StandardizeData(`data',"`psi'","`spsi'")
*** lambda
if ("`newlambda'"!="") {
local lambda = `newlambda'
}
// list of lambdas (can be length=1)
tempname lambdas
// add to list of mata globals created
local mnamelist `mnamelist' `lambdas'
if ("`rigorous'"!="") & ("`lambda'"=="") {
// calculate "rigorous" lambda
tempname lam_params
mata: `lam_params' = (`c',`gamma')
// add to list of mata globals created
local mnamelist `mnamelist' `lam_params'
// _lassologit internal lambdas already incorporate factor of 1/n
mata: `lambdas' = calcRigorousLambda(`data',`lam_params')
local lcount = 1
}
else if ("`rigorous'"=="") & ("`lambda'"=="") {
// calculate default lambda
// _lassologit internal lambdas already incorporate factor of 1/n
mata: `lambdas' = calcDefLambdas(`data',`lmax',`lcount',`lminratio')
}
else if ("`rigorous'"=="") & ("`lambda'"!="") {
// take user-specified lambda
local lcount : word count `lambda'
mata: `lambdas' = strtoreal(tokens("`lambda'"))
// by default _lassologit internally uses lambda that incorporates 1/n
// but reports lambda that does not incorporate 1/n
// if user provides lambda that does not incorporate 1/n, need to rescale it
if `lambdanflag'==0 {
mata: `lambdas' = `lambdas' * 1/dataStructSelect(`data',"total_trials")
}
}
else {
di as err "Options rigorous and lambda() not allowed as the same time."
}
//
*** estimation & output
// fit model
tempname fitResults
mata: `fitResults'=fit(`data',`lambdas')
// add to list of mata globals created
local mnamelist `mnamelist' `fitResults'
// prepare output:
// unstandardise beta, post results,
// calculate out-of-sample prediction (if there is a holdout sample)
// etc..
local savepredmat = ("`savepred'"!="")
// note Stata logit uses toest marker
// use "if `toest'==1" (rather than "if `touse'") in case of missings
mata: MakeOutput(`data',`fitResults',"`lossmeasure'",`savepredmat',"if `toest'==1")
*** ereturn post
// initialize ereturned results with depname
ereturn post , depname(`varY_o')
// Mata routine to post all results except e(b)
mata: PostResults(`data',`fitResults',"`lossmeasure'",`savepredmat',`debugflag')
// post e(b) only
if (`lcount'==1) {
tempname theb
if ("`postlogit'"=="") {
mat `theb' = e(beta_dense)
}
else {
mat `theb' = e(beta_post_dense)
}
ereturn repost b=`theb', resize rename
}
// finally, post esample(.); do it here to avoid ereturn+esample
// bug in Stata that can corrupt any live Mata views
// first need to restore, otherwise e(sample) will disappear
if (`preserved') {
restore
}
// use a copy of touse so that it stays in memory
tempvar esample
qui gen byte `esample'=`touse'
ereturn repost, esample(`esample')
}
if `lambdanflag'==0 {
// _lassologit internal lambdas incorporate factor of 1/n
// by default rescale lambda here so that factor of 1/n is removed
// unless overridden with lambdan option
rescale_lambda
}
// tidy up mata memory
mata: mata drop `mnamelist'
end
// utility for rescaling lambda
program define rescale_lambda, eclass
version 13
// rescale scalars
foreach s in aiclambda aicclambda biclambda ebiclambda lambda {
if e(`s')<. {
ereturn scalar `s' = e(`s')*e(N)
}
}
// rescale lambdas
tempname lambdas
mat `lambdas' = e(lambdas)
if `lambdas'[1,1] ~= . {
mat `lambdas' = `lambdas' * e(N)
ereturn matrix lambdas = `lambdas'
}
end
program define plotpath2
syntax [anything] [, plotvar(string) ///
plotpath(string) ///
plotopt(string) ///
plotlabel ///
wnorm ///
LOGistic ///
]
version 12
if (("`plotpath'"!="lambda") & ("`plotpath'"!="norm") & ("`plotpath'"!="lnlambda")) {
di as err "Plotpath() allows 'lambda', `lnlambda' or 'norm'."
error 198
}
//
****************************************************************************
*** Contents of b matrix and lambda vector made into Stata variables for plotting.
tempname b lambdas l1norm
mat `b' = e(betas)
if ("`logistic'"!="") {
mat `lambdas' = e(lambdas)'
if "`wnorm'"=="" {
mat `l1norm' = e(l1norm)'
}
else {
mat `l1norm' = e(wl1norm)
}
}
else {
mat `lambdas' = e(lambdamat)
if "`wnorm'"=="" {
mat `l1norm' = e(l1norm)
}
else {
mat `l1norm' = e(wl1norm)
}
}
tempvar touse
gen `touse'=e(sample)
local lcount = e(lcount)
****************************************************************************
*** Strip out constant (if it's there) since creating a variable called _cons not alllowed.
local cons = e(cons)
if `cons' {
local rb1 = colsof(`b') - 1 // constant is in the last column
mat `b' = `b'[1...,1..`rb1']
}
//
****************************************************************************
*** Varnames taken from colnames of b matrix.
local bnames : colnames `b'
fvstrip `bnames' // annoying - Stata inserts b/n etc. in first factor variable etc.
local bnames `r(varlist)'
// process pv names
if "`plotvar'"=="" {
local pvnames `bnames' // plot all
}
else { // plot user-provided
fvstrip `plotvar' if `touse', expand dropomit
local pvnames `r(varlist)'
}
foreach pvn in `pvnames' { // unab one-by-one to standardise, get i prefix etc.
fvunab pvn_unab : `pvn'
local pvnames_unab `pvnames_unab' `pvn_unab'
}
// process b names
foreach bn in `bnames' { // unab one-by-one to standardise, get i prefix etc.
fvunab bn_unab : `bn'
local bnames_unab `bnames_unab' `bn_unab'
}
//
****************************************************************************
*** now that unabbreviated varlists are prepared
*** check that plotvars are in regressors
*** If `plotvar' macro is empty, graph all regressors.
if "`plotvar'"~="" {
local nplotvarcheck : list pvnames_unab - bnames_unab
if ("`nplotvarcheck'"!="") {
di as error "Variable(s) `nplotvarcheck' of plotvar() not listed as regressor(s)."
exit 198
}
}
// in case there are any . operators included, change to "_"
local bnames : subinstr local bnames_unab "." "_", all count(local numsubs)
local pvnames : subinstr local pvnames_unab "." "_", all count(local numsubs)
// check for max number of variables to plot
local npv : word count `pvnames'
if `npv' >= 100 {
di as err "Error: lassopath can graph at most 99 regressors"
di as err " use plotvar(.) option to specify subset of regressors"
exit 103
}
//
****************************************************************************
*** create graphing data and then plot
preserve // do preserve here so that above vars exist
clear
qui svmat `b'
foreach var of varlist * {
tokenize `bnames'
rename `var' `1'
mac shift
local bnames `*'
}
//
if "`plotpath'"=="lnlambda" {
qui svmat `lambdas', names("lambda")
replace lambda = ln(lambda)
if ("`plotlabel'"!="") {
local txt
local xcoord = lambda[1]-abs(lambda[_N]-lambda[1])*1.03
local xcoordminus = lambda[1]-abs(lambda[_N]-lambda[1])*1.1
foreach var of varlist `pvnames' {
local ycoord = `var'[_N]
local vn = abbrev("`var'",8)
local txt `txt' text(`ycoord' `xcoord' `"`vn'"', place(w) just(left) size(small))
}
local yscalealt yscale(alt)
local xscale xscale(range(`xcoordminus')) // extend plot area on left to allow room for varnames
}
twoway line `pvnames' lambda, `plotopt' `txt' `yscalealt' xtit("ln(Lambda)") `graphr' `xscale'
}
else if "`plotpath'"=="lambda" {
qui svmat `lambdas', names("lambda")
if ("`plotlabel'"!="") {
local txt
local xcoord = -abs(lambda[1])*0.03
local xcoordminus = -abs(lambda[1])*0.15
foreach var of varlist `pvnames' {
local ycoord = `var'[_N]
local vn = abbrev("`var'",8)
local txt `txt' text(`ycoord' `xcoord' `"`vn'"', place(w) just(left) size(small))
}
local yscalealt yscale(alt)
local xscale xscale(range(`xcoordminus')) // extend plot area on left to allow room for varnames
}
twoway line `pvnames' lambda, `plotopt' `txt' `yscalealt' xtit("Lambda") `graphr' `xscale'
}
else {
qui svmat `l1norm', names("l1norm")
sort l1norm1
if ("`plotlabel'"!="") {
local txt
local xcoord = l1norm1[_N]*1.02 // extend plot area on right to allow room for varnames
local xcoordplus = l1norm1[_N]*1.1
foreach var of varlist `pvnames' {
local ycoord = `var'[_N]
local vn = abbrev("`var'",8)
local txt `txt' text(`ycoord' `xcoord' `"`vn'"', place(e) just(left) size(small))
}
local xscale xscale(range(`xcoordplus'))
}
if "`wnorm'"=="" {
local xtitle L1 Norm
}
else {
local xtitle Weighted L1 Norm
}
line `pvnames' l1norm, `plotopt' `txt' xtit("`xtitle'") `graphr' `xscale'
}
//
restore
end
// Used in rlasso and lasso2 rlasso.
// adapted for lassologits
prog DisplayCoefs
syntax , ///
[ ///
displayall /// full coef vector in display (default=selected only)
varwidth(int 17) ///
NORecover ///
]
local cons =e(cons)
if ("`norecover'"=="") {
local partial `e(partial)'
local partial_ct =e(partial_ct)
}
else {
local partial
local partial_ct =0
}
// varlists
local selected `e(selected)'
fvstrip `selected'
local selected `r(varlist)'
local notpen `e(notpen)'
fvstrip `notpen'
local notpen `r(varlist)'
local selected0 `e(selected0)'
fvstrip `selected0'
local selected0 `r(varlist)'
// coef vectors
tempname beta betaOLS
// if "`displayall'"~="" { // there must be some vars specified even if nothing selected
// mat `beta' =e(beta) //e(betaAll)
// mat `betaOLS' =e(beta_post) //betaAllOLS)
// local col_ct =colsof(`beta')
// local vlist : colnames `beta'
// local vlistOLS : colnames `betaOLS'
// local baselevels baselevels
// }
//else if 1 { // display only selected, but only if there are any
mat `beta' =e(beta_dense)
mat `betaOLS' =e(beta_post_dense)
local col_ct =colsof(`beta')
local vlist : colnames `beta'
local vlistOLS : colnames `betaOLS'
//}
// else { // nothing selected, zero columns in beta
// local col_ct =0
// }
// if e(k)>0 {
// _ms_build_info `beta' if e(sample)
// _ms_build_info `betaOLS' if e(sample)
// }
*** (Re-)display coefficients including constant/partial
local varwidth1 =`varwidth'+1
local varwidth3 =`varwidth'+3
local varwidth4 =`varwidth'+4
local varwidthm7 =`varwidth'-7
local varwidthm13 =`varwidth'-13
di
di as text "{hline `varwidth1'}{c TT}{hline 32}"
//if "`e(method)'"=="sqrt-lasso" {
di as text _col(`varwidthm7') "Selected {c |} Logistic Post"
di as text _col(`varwidthm7') " {c |} Lasso logit"
//}
/*else if "`e(method)'"=="ridge" {
di as text _col(`varwidthm7') "Selected {c |} Ridge Post-est OLS"
}
else if "`e(method)'"=="elastic net" {
di as text _col(`varwidthm7') "Selected {c |} Elastic net Post-est OLS"
di as text _col(`varwidthm7') " {c |}" _c
di as text " (alpha=" _c
di as text %4.3f `e(alpha)' _c
di as text ")"
}
else if "`e(method)'"=="lasso" {
di as text _col(`varwidthm7') "Selected {c |} Lasso Post-est OLS"
}
else {
di as err "internal DisplayCoefs error. unknown method."
exit 1
}*/
di as text "{hline `varwidth1'}{c +}{hline 32}"
local anynotpen = 0
local i 1
local lastcol = `col_ct' //- `partial_ct'
tokenize `vlist' // put elements of coef vector into macros 1, 2, ...
while `i' <= `lastcol' {
local vn ``i''
fvstrip `vn' // get rid of o/b/n prefix for display purposes