-
Notifications
You must be signed in to change notification settings - Fork 0
/
conquer.py
2361 lines (1937 loc) · 99.5 KB
/
conquer.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 code file is a modified version of the original code file from the following repository: https://github.com/WenxinZhou/conquer
Reference:
1. High-dimensional quantile regression: Convolution smoothing and concave regularization. Tan, Wang, and Zhou, 2022, Journal of the Royal Statistical Society Series B: Statistical Methodology.
2. High-dimensional composite quantile regression: Optimal statistical guarantees and fast algorithms. Moon and Zhou, 2023, Electronic Journal of Statistics
"""
import numpy as np
import numpy.random as rgt
from scipy.stats import norm
from scipy.special import logsumexp
from scipy.optimize import minimize
import warnings
class low_dim():
'''
Convolution Smoothed Quantile Regression
'''
kernels = ["Laplacian", "Gaussian", "Logistic", "Uniform", "Epanechnikov"]
weights = ["Exponential", "Multinomial", "Rademacher",
"Gaussian", "Uniform", "Folded-normal"]
opt = {'max_iter': 1e3, 'max_lr': 50, 'tol': 1e-5,
'warm_start': True, 'nboot': 200}
def __init__(self, X, Y, intercept=True, options=dict()):
'''
Args:
X: n by p matrix of covariates; each row is an observation vector.
Y: an ndarray of response variables.
intercept: logical flag for adding an intercept to the model.
options: a dictionary of internal statistical and optimization parameters.
max_iter: maximum numder of iterations in the GD-BB algorithm;
default is 500.
max_lr: maximum step size/learning rate.
If set to False, there is no contraint on the maximum step size.
tol: the iteration will stop when max{|g_j|: j = 1, ..., p} <= tol
where g_j is the j-th component of the (smoothed) gradient;
default is 1e-4.
warm_start: logical flag for using a robust expectile
regression estimate as an initial value.
nboot: number of bootstrap samples for inference.
'''
self.n = X.shape[0]
if X.shape[1] >= self.n:
raise ValueError("covariate dimension exceeds sample size")
self.Y = Y.reshape(self.n)
self.mX, self.sdX = np.mean(X, axis=0), np.std(X, axis=0)
self.itcp = intercept
if intercept:
self.X = np.c_[np.ones(self.n), X]
self.X1 = np.c_[np.ones(self.n), (X - self.mX)/self.sdX]
else:
self.X, self.X1 = X, X/self.sdX
self.opt.update(options)
def mad(self, x):
return np.median(abs(x - np.median(x))) * 1.4826
def bandwidth(self, tau):
h0 = min((self.X.shape[1] + np.log(self.n))/self.n, 0.5) ** 0.4
return max(0.01, h0 * (tau-tau**2) ** 0.5)
def smooth_check(self, x, tau=0.5, h=None, kernel='Laplacian', w=np.array([])):
if h is None:
h = self.bandwidth(tau)
if kernel == 'Laplacian':
loss = lambda x: np.where(x >= 0, tau*x, (tau-1)*x) \
+ (h/2) * np.exp(-abs(x)/h)
elif kernel == 'Gaussian':
loss = lambda x: (tau - norm.cdf(-x/h)) * x \
+ (h/2) * np.sqrt(2 / np.pi) * np.exp(-(x/h) ** 2 / 2)
elif kernel == 'Logistic':
loss = lambda x: tau * x + h * np.log(1 + np.exp(-x/h))
elif kernel == 'Uniform':
loss = lambda x: (tau - .5) * x + h * (.25 * (x/h)**2 + .25) * (abs(x) < h) \
+ .5 * abs(x) * (abs(x) >= h)
elif kernel == 'Epanechnikov':
loss = lambda x: (tau - .5) * x + .5 * h * (.75 * (x/h) ** 2 \
- .125 * (x/h) ** 4 + .375) * (abs(x) < h) \
+ .5 * abs(x) * (abs(x) >= h)
if not w.any():
return np.mean(loss(x))
else:
return np.mean(loss(x) * w)
def boot_weight(self, weight):
boot = {'Multinomial': lambda n : np.random.multinomial(n, pvals=np.ones(n)/n),
'Exponential': lambda n : np.random.exponential(size=n),
'Rademacher': lambda n : 2*np.random.binomial(1, 1/2, n),
'Gaussian': lambda n : np.random.normal(1, 1, n),
'Uniform': lambda n : np.random.uniform(0, 2, n),
'Folded-normal': lambda n : abs(np.random.normal(size=n)) * np.sqrt(.5 * np.pi)}
return boot[weight](self.n)
def retire_weight(self, x, tau, c):
pos = x > 0
tmp = np.minimum(abs(x), c)
tmp[pos] *= tau
tmp[~pos] *= tau - 1
return -tmp
def conquer_weight(self, x, tau, kernel="Laplacian", w=np.array([])):
if kernel=='Laplacian':
Ker = lambda x : 0.5 + 0.5 * np.sign(x) * (1 - np.exp(-abs(x)))
elif kernel=='Gaussian':
Ker = lambda x : norm.cdf(x)
elif kernel=='Logistic':
Ker = lambda x : 1 / (1 + np.exp(-x))
elif kernel=='Uniform':
Ker = lambda x : np.where(x > 1, 1, 0) + np.where(abs(x) <= 1, 0.5 * (1 + x), 0)
elif kernel=='Epanechnikov':
Ker = lambda x : 0.25 * (2 + 3 * x / 5 ** 0.5 \
- (x / 5 ** 0.5)**3 ) * (abs(x) <= 5 ** 0.5) \
+ (x > 5 ** 0.5)
if not w.any():
return (Ker(x) - tau)
else:
return w * (Ker(x) - tau)
def retire(self, tau=0.5, robust=5,
standardize=True, adjust=True, scale=False):
'''
Robust/Huberized Expectile Regression
'''
X = self.X1 if standardize else self.X
asym = lambda x : 2 * np.where(x < 0, (1-tau) * x, tau * x)
beta = np.zeros(X.shape[1])
if self.itcp: beta[0] = np.quantile(self.Y, tau)
res = self.Y - beta[0]
c, c0 = robust, robust * self.mad(asym(self.Y))
if scale:
ares = asym(res)
c = robust * max(self.mad(ares), 0.1 * c0)
grad0 = X.T.dot(self.retire_weight(res, tau, c)) / self.n
diff_beta = -grad0
beta += diff_beta
res, t = self.Y - X.dot(beta), 0
while t < self.opt['max_iter'] and max(abs(grad0)) > self.opt['tol']:
if scale:
ares = asym(res)
c = robust * max(self.mad(ares), 0.1 * c0)
grad1 = X.T.dot(self.retire_weight(res, tau, c)) / self.n
diff_grad = grad1 - grad0
r0, r1 = diff_beta.dot(diff_beta), diff_grad.dot(diff_grad)
if r1 == 0: lr = 1
else:
r01 = diff_grad.dot(diff_beta)
lr = min(logsumexp(abs(r01/r1)), logsumexp(abs(r0/r01)))
if self.opt['max_lr']: lr = min(lr, self.opt['max_lr'])
grad0, diff_beta = grad1, -lr*grad1
beta += diff_beta
res = self.Y - X.dot(beta)
t += 1
if standardize and adjust:
beta[self.itcp:] = beta[self.itcp:]/self.sdX
if self.itcp: beta[0] -= self.mX.dot(beta[1:])
return {'beta': beta, 'res': res, 'niter': t, 'robust': c}
def fit(self, tau=0.5, h=None, kernel="Laplacian",
beta0=np.array([]), res=np.array([]), weight=np.array([]),
standardize=True, adjust=True):
'''
Convolution Smoothed Quantile Regression
Args:
tau: quantile level between 0 and 1; default is 0.5.
h: bandwidth/smoothing parameter; the default value is computed by self.bandwidth(tau).
kernel: a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
beta0: initial estimate; default is np.array([]).
res: an ndarray of fitted residuals; default is np.array([]).
weight: an ndarray of observation weights; default is np.array([]).
standardize: logical flag for x variable standardization prior to fitting the model;
default is TRUE.
adjust: logical flag for returning coefficients on the original scale.
Returns:
'beta': conquer estimate.
'res': an ndarray of fitted residuals.
'niter': number of iterations.
'bw': bandwidth.
'lr_seq': a sequence of learning rates determined by the BB method.
'lval_seq': a sequence of (smoothed check) loss values at the iterations.
'''
bw = self.bandwidth(tau) if h is None else h
if kernel not in self.kernels:
raise ValueError("kernel must be either Laplacian, Gaussian, \
Logistic, Uniform or Epanechnikov")
X = self.X1 if standardize else self.X
if len(beta0) == 0:
if self.opt['warm_start']:
model = self.retire(tau=tau, standardize=standardize, adjust=False)
beta0, res = model['beta'], model['res']
else:
beta0 = rgt.randn(X.shape[1]) / X.shape[1]**0.5
res = self.Y - X.dot(beta0)
elif len(beta0) == X.shape[1]:
res = self.Y - X.dot(beta0)
else:
raise ValueError("dimension of beta0 must match parameter dimension")
lr_seq, lval_seq = [], []
grad0 = X.T.dot(self.conquer_weight(-res/bw, tau, kernel, weight)) / self.n
diff_beta = -grad0
beta = beta0 + diff_beta
res, t = self.Y - X.dot(beta), 0
lval_seq.append(self.smooth_check(res, tau, bw, kernel, weight))
while t < self.opt['max_iter'] and max(abs(diff_beta)) > self.opt['tol']:
grad1 = X.T.dot(self.conquer_weight(-res/bw, tau, kernel, weight)) / self.n
diff_grad = grad1 - grad0
r0, r1 = diff_beta.dot(diff_beta), diff_grad.dot(diff_grad)
if r1 == 0: lr = 1
else:
r01 = diff_grad.dot(diff_beta)
lr = min(logsumexp(abs(r01/r1)), logsumexp(abs(r0/r01)))
if self.opt['max_lr']: lr = min(lr, self.opt['max_lr'])
lr_seq.append(lr)
grad0, diff_beta = grad1, -lr*grad1
beta += diff_beta
res = self.Y - X.dot(beta)
lval_seq.append(self.smooth_check(res, tau, bw, kernel, weight))
t += 1
if standardize and adjust:
beta[self.itcp:] = beta[self.itcp:]/self.sdX
if self.itcp: beta[0] -= self.mX.dot(beta[1:])
return {'beta': beta, 'bw': bw, 'niter': t,
'lval_seq': np.array(lval_seq),
'lr_seq': np.array(lr_seq), 'res': res}
def bfgs_fit(self, tau=0.5, h=None, kernel="Laplacian",
beta0=np.array([]), tol=None, options=None):
'''
Convolution Smoothed Quantile Regression via the BFGS Algorithm
Args:
tau : quantile level between 0 and 1; default is 0.5.
h : bandwidth/smoothing parameter; the default value is computed by self.bandwidth(tau).
kernel : a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
beta0 : initial estimate; default is np.array([]).
tol : tolerance for termination.
options : a dictionary of solver options. Default is
options={'gtol': 1e-05, 'norm': inf, 'maxiter': None,
'disp': False, 'return_all': False}
gtol : gradient norm must be less than gtol(float) before successful termination.
norm : order of norm (Inf is max, -Inf is min).
maxiter : maximum number of iterations to perform.
disp : set to True to print convergence messages.
return_all : set to True to return a list of the best solution
at each of the iterations.
Returns:
'beta' : conquer estimate (computed by the BFGS algorithm).
'res' : a vector of fitted residuals.
'bw' : bandwidth/smoothing parameter.
'niter' : number of iterations.
'loss_val' : value of the smoothed quantile loss at the output.
'grad_val' : value of the gradient (of the smoothed loss) at the output.
'message' : description of the cause of the termination.
'''
y, X = self.Y, self.X
if h is None:
h = self.bandwidth(tau)
if h <= 0:
raise ValueError('the bandwidth h must be strictly positive')
if len(beta0) == 0:
beta0 = np.zeros(X.shape[1])
fun = lambda beta : self.smooth_check(y - X.dot(beta), tau, h, kernel)
grad = lambda beta : X.T.dot(self.conquer_weight((X.dot(beta)-y)/h, tau, kernel)) / self.n
model = minimize(fun, beta0, method='BFGS', jac=grad, tol=tol, options=options)
return {'beta': model['x'], 'bw': h,
'res': y - X.dot(model['x']),
'niter': model['nit'],
'loss_val': model['fun'],
'grad_val': model['jac'],
'message': model['message']}
def bw_path(self, tau=0.5, h_seq=np.array([]), L=20, kernel="Laplacian",
standardize=True, adjust=True):
'''
Solution Path of Conquer at a Sequence of Bandwidths
Args:
h_seq : a sequence of bandwidths.
L : number of bandwdiths; default is 20.
Returns:
'beta_seq' : a sequence of conquer estimates.
'res_seq' : a sequence of residual vectors.
'bw_seq' : a sequence of bandwidths in descending order.
'''
n, dim = self.X.shape
if not np.array(h_seq).any():
h_seq = np.linspace(0.01, min((dim + np.log(n))/n, 0.5)**0.4, num=L)
if standardize: X = self.X1
else: X = self.X
h_seq, L = np.sort(h_seq)[::-1], len(h_seq)
beta_seq = np.empty(shape=(X.shape[1], L))
res_seq = np.empty(shape=(n, L))
model = self.fit(tau, h_seq[0], kernel, standardize=standardize, adjust=False)
beta_seq[:,0], res_seq[:,0] = model['beta'], model['res']
for l in range(1,L):
model = self.fit(tau, h_seq[l], kernel, model['beta'], model['res'],
standardize=standardize, adjust=False)
beta_seq[:,l], res_seq[:,l] = model['beta'], model['res']
if standardize and adjust:
beta_seq[self.itcp:,] = beta_seq[self.itcp:,]/self.sdX[:,None]
if self.itcp:
beta_seq[0,:] -= self.mX.dot(beta_seq[1:,])
return {'beta_seq': beta_seq, 'res_seq': res_seq, 'bw_seq': h_seq}
def norm_ci(self, tau=0.5, h=None, kernel="Laplacian",
method=None, alpha=0.05, standardize=True):
'''
Normal Calibrated Confidence Intervals
Args:
tau : quantile level; default is 0.5.
h : bandwidth. The default is computed by self.bandwidth(tau).
kernel : a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
method : a character string representing the method for computing the estimate;
default is None.
alpha : miscoverage level for each CI; default is 0.05.
standardize : logical flag for x variable standardization prior to fitting the model;
default is TRUE.
Returns:
'beta' : conquer estimate.
'normal_ci' : numpy array. Normal CIs based on estimated asymptotic covariance matrix.
'''
if h is None: h = self.bandwidth(tau)
X = self.X
if method=='BFGS':
model = self.bfgs_fit(tau, h, kernel)
else:
model = self.fit(tau, h, kernel, standardize=standardize)
h = model['bw']
hess_weight = norm.pdf(model['res']/h)
grad_weight = ( norm.cdf(-model['res']/h) - tau)**2
hat_V = (X.T * grad_weight).dot(X)/self.n
inv_J = np.linalg.inv((X.T * hess_weight).dot(X)/(self.n * h))
ACov = inv_J.dot(hat_V).dot(inv_J)
rad = norm.ppf(1-0.5*alpha)*np.sqrt( np.diag(ACov) / self.n )
ci = np.c_[model['beta'] - rad, model['beta'] + rad]
return {'beta': model['beta'], 'normal_ci': ci}
def mb(self, tau=0.5, h=None, kernel="Laplacian",
weight="Exponential", standardize=True):
'''
Multiplier Bootstrap Estimates
Args:
tau : quantile level; default is 0.5.
h : bandwidth. The default is computed by self.bandwidth(tau).
kernel : a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
weight : a character string representing the random weight distribution;
default is "Exponential".
standardize : logical flag for x variable standardization prior to fitting the model;
default is TRUE.
Returns:
'mb_beta' : numpy array.
1st column: conquer estimate;
2nd to last: bootstrap estimates.
'''
if h is None: h = self.bandwidth(tau)
if weight not in self.weights:
raise ValueError("weight distribution must be either Exponential, Rademacher, \
Multinomial, Gaussian, Uniform or Folded-normal")
model = self.fit(tau, h, kernel, standardize=standardize, adjust=False)
mb_beta = np.zeros([len(model['beta']), self.opt['nboot']+1])
mb_beta[:,0], res = np.copy(model['beta']), np.copy(model['res'])
for b in range(self.opt['nboot']):
model = self.fit(tau, h, kernel, beta0=mb_beta[:,0],
res=res, weight=self.boot_weight(weight),
standardize=standardize)
mb_beta[:,b+1] = model['beta']
if standardize:
mb_beta[self.itcp:,0] = mb_beta[self.itcp:,0]/self.sdX
if self.itcp: mb_beta[0,0] -= self.mX.dot(mb_beta[1:,0])
## delete NaN bootstrap estimates (when using Gaussian weights)
mb_beta = mb_beta[:,~np.isnan(mb_beta).any(axis=0)]
return mb_beta
def mb_ci(self, tau=0.5, h=None, kernel="Laplacian",
weight="Exponential", alpha=0.05, standardize=True):
'''
Multiplier Bootstrap Confidence Intervals
Arguments
---------
tau : quantile level; default is 0.5.
h : bandwidth. The default is computed by self.bandwidth(tau).
kernel : a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
weight : a character string representing the random weight distribution;
default is "Exponential".
alpha : miscoverage level for each CI; default is 0.05.
standardize : logical flag for x variable standardization prior to fitting the model;
default is TRUE.
Returns
-------
'boot_beta' : numpy array.
1st column: conquer estimate;
2nd to last: bootstrap estimates.
'percentile_ci' : numpy array. Percentile bootstrap CI.
'pivotal_ci' : numpy array. Pivotal bootstrap CI.
'normal_ci' : numpy array. Normal-based CI using bootstrap variance estimates.
'''
if h==None: h = self.bandwidth(tau)
mb_beta = self.mb(tau, h, kernel, weight, standardize)
if weight in self.weights[:4]:
adj = 1
elif weight == 'Uniform':
adj = np.sqrt(1/3)
elif weight == 'Folded-normal':
adj = np.sqrt(0.5*np.pi - 1)
percentile_ci = np.c_[np.quantile(mb_beta[:,1:], 0.5*alpha, axis=1), \
np.quantile(mb_beta[:,1:], 1-0.5*alpha, axis=1)]
pivotal_ci = np.c_[(1+1/adj)*mb_beta[:,0] - percentile_ci[:,1]/adj, \
(1+1/adj)*mb_beta[:,0] - percentile_ci[:,0]/adj]
radi = norm.ppf(1-0.5*alpha)*np.std(mb_beta[:,1:], axis=1)/adj
normal_ci = np.c_[mb_beta[:,0] - radi, mb_beta[:,0] + radi]
return {'boot_beta': mb_beta,
'percentile_ci': percentile_ci,
'pivotal_ci': pivotal_ci,
'normal_ci': normal_ci}
def qr(self, tau=0.5, beta0=np.array([]), res=np.array([]),
standardize=True, adjust=True, lr=1, max_iter=1000, tol=1e-5):
'''
Quantile Regression via Subgradient Descent
Args:
tau : quantile level; default is 0.5.
beta0 : initial estimate; default is np.array([]).
res : an ndarray of fitted residuals; default is np.array([]).
standardize : logical flag for x variable standardization prior to fitting the model;
default is TRUE.
adjust : logical flag for returning coefficients on the original scale;
default is TRUE.
lr : learning rate (step size); default is 1.
max_iter : maximum number of iterations; default is 1000.
tol : tolerance for termination; default is 1e-5.
Returns:
'beta' : standard quantile regression estimate.
'res' : an ndarray of fitted residuals.
'niter' : number of iterations.
'''
X = self.X1 if standardize else self.X
beta = np.copy(beta0)
if len(beta) == 0:
model = self.fit(tau=tau, standardize=standardize, adjust=False)
beta, res = model['beta'], model['res']
elif len(res) == 0:
res = self.Y - X.dot(beta)
qr_loss = lambda x: np.abs(tau - (x<0)) * abs(x)
lval = np.zeros(np.int64(max_iter))
sub_grad = lambda x : tau - (x<0)
n, dev, t = len(res), 1, 0
while t < max_iter and dev > tol:
diff = -lr * X.T.dot(sub_grad(res))/n
beta -= diff
dev = max(abs(diff))
res = self.Y - X.dot(beta)
lval[t] = np.mean(qr_loss(res))
t += 1
if standardize and adjust:
beta[self.itcp:] = beta[self.itcp:]/self.sdX
if self.itcp:
beta[0] -= self.mX.dot(beta[1:])
return {'beta': beta, 'res': res, 'lval_seq': lval, 'niter': t}
def Huber(self, c=1, beta0=np.array([]), tol=1e-6, options=None):
'''
Huber Regression via BFGS
options = {'gtol': 1e-05, 'norm': inf, 'maxiter': None,
'disp': False, 'return_all': False}
'''
y, X = self.Y, self.X
huber_loss = lambda u : np.where(abs(u)<=c, 0.5 * u**2, c * abs(u) - 0.5 * c**2)
huber_score = lambda u : np.where(abs(u)<=c, u, np.sign(u)*c)
beta0 = np.zeros(X.shape[1]) if len(beta0) == 0 else beta0
fun = lambda beta : np.mean(huber_loss(y - X@beta))
grad = lambda beta : X.T.dot(huber_score(X@beta - y))/X.shape[0]
model = minimize(fun, beta0, method='BFGS', jac=grad, tol=tol, options=options)
return {'beta': model['x'], 'robust': c,
'res': y - X.dot(model['x']),
'niter': model['nit'],
'loss_val': model['fun'],
'grad_val': model['jac'],
'message': model['message']}
def adaHuber(self, dev_prob=None, max_niter=100):
'''
Adaptive Huber Regression
'''
if dev_prob is None:
dev_prob = 1 / self.n
beta_hat = np.linalg.solve(self.X.T.dot(self.X), self.X.T.dot(self.Y))
rel, err, t = (self.X.shape[1] + np.log(1 / dev_prob)) / self.n, 1, 0
while err > self.opt['tol'] and t < max_niter:
res = self.Y - self.X.dot(beta_hat)
f = lambda c: np.mean(np.minimum((res / c) ** 2, 1)) - rel
robust = self._find_root(f, np.min(np.abs(res)) + self.opt['tol'], np.sqrt(res @ res))
model = self.Huber(c=robust)
# self.retire(robust=robust, scale=False)
err = np.max(np.abs(model['beta'] - beta_hat))
beta_hat = model['beta']
t += 1
return {'beta': beta_hat, 'niter': t,
'robust': robust, 'res': res}
def _find_root(self, f, tmin, tmax, tol=1e-5):
while tmax - tmin > tol:
tau = (tmin + tmax) / 2
if f(tau) > 0:
tmin = tau
else:
tmax = tau
return tau
class high_dim(low_dim):
'''
Regularized Convolution Smoothed Quantile Regression via ILAMM
(iterative local adaptive majorize-minimization)
'''
weights = ['Multinomial', 'Exponential', 'Rademacher']
penalties = ["L1", "SCAD", "MCP", "CapppedL1"]
opt = {'phi': 0.1, 'gamma': 1.25, 'max_iter': 1e3, 'tol': 1e-8,
'iter_warning': True, 'warm_start': True, 'max_lr': 50,
'irw_tol': 1e-5, 'nsim': 200, 'nboot': 200}
def __init__(self, X, Y, intercept=True, options={}):
'''
Args:
X: n by p matrix of covariates; each row is an observation vector.
Y: an ndarray of response variables.
intercept: logical flag for adding an intercept to the model.
options: a dictionary of internal statistical and optimization parameters.
phi: initial quadratic coefficient parameter in the ILAMM algorithm;
default is 0.1.
gamma: adaptive search parameter that is larger than 1; default is 1.25.
max_iter: maximum numder of iterations in the ILAMM algorithm; default is 1e3.
tol: the ILAMM iteration terminates when |beta^{k+1} - beta^k|_max <= tol;
default is 1e-8.
iter_warning: logical flag for warning when the maximum number
of iterations is achieved for the l1-penalized fit.
warm_start: logical flag for using a penalized robust expectile regression
estimate as an initial value.
irw_tol: tolerance parameter for stopping iteratively reweighted L1-penalization;
default is 1e-5.
nsim: number of simulations for computing a data-driven lambda; default is 200.
nboot: number of bootstrap samples for post-selection inference; default is 200.
'''
self.n, self.p = X.shape
self.Y = Y.reshape(self.n)
self.mX, self.sdX = np.mean(X, axis=0), np.std(X, axis=0)
self.itcp = intercept
if intercept:
self.X = np.c_[np.ones(self.n), X]
self.X1 = np.c_[np.ones(self.n), (X - self.mX)/self.sdX]
else:
self.X, self.X1 = X, X/self.sdX
self.opt.update(options)
def bandwidth(self, tau):
h0 = (np.log(self.p) / self.n) ** 0.25
return max(0.01, h0 * (tau-tau**2) ** 0.5)
def soft_thresh(self, x, c):
tmp = abs(x) - c
return np.sign(x)*np.where(tmp<=0, 0, tmp)
def self_tuning(self, tau=0.5, standardize=True):
'''
A Simulation-based Approach for Choosing the Penalty Level (Lambda)
Refs:
l1-Penalized quantile regression in high-dimensinoal sparse models (2011)
by Alexandre Belloni and Victor Chernozhukov
The Annals of Statistics 39(1): 82--130.
Args:
tau: quantile level; default is 0.5.
standardize: logical flag for x variable standardization prior to fitting the model;
default is TRUE.
Returns:
lambda_sim: an ndarray of simulated lambda values.
'''
X = self.X1 if standardize else self.X
lambda_sim = np.array([max(abs(X.T.dot(tau - (rgt.uniform(0,1,self.n) <= tau))))
for b in range(self.opt['nsim'])])
return lambda_sim/self.n
def concave_weight(self, x, penalty="SCAD", a=None):
if penalty == "SCAD":
if a is None:
a = 3.7
tmp = 1 - (abs(x) - 1) / (a - 1)
tmp = np.where(tmp <= 0, 0, tmp)
return np.where(tmp > 1, 1, tmp)
elif penalty == "MCP":
if a is None:
a = 3
tmp = 1 - abs(x) / a
return np.where(tmp <= 0, 0, tmp)
elif penalty == "CappedL1":
if a is None:
a = 3
return abs(x) <= a / 2
def retire_loss(self, x, tau, c):
out = 0.5 * (abs(x) <= c) * x**2 + (c * abs(x) - 0.5 * c ** 2) * (abs(x) > c)
return np.mean(abs(tau - (x<0)) * out)
def l1_retire(self, tau=0.5, Lambda=np.array([]), robust=5,
beta0=np.array([]), res=np.array([]),
standardize=True, adjust=True):
'''
L1-Penalized Robust Expectile Regression (l1-retire)
'''
if not np.array(Lambda).any():
Lambda = np.quantile(self.self_tuning(tau, standardize), 0.9)
X = self.X1 if standardize else self.X
if len(beta0) == 0:
beta0 = np.zeros(X.shape[1])
if self.itcp: beta0[0] = np.quantile(self.Y, tau)
res = self.Y - beta0[0]
phi, dev, count = self.opt['phi'], 1, 0
while dev > self.opt['tol'] and count < self.opt['max_iter']:
c = robust * min(self.mad(res), np.std(res))
if c == 0 or np.log(c) < -10:
c = robust
grad0 = X.T.dot(self.retire_weight(res, tau, c))
loss_eval0 = self.retire_loss(res, tau, c)
beta1 = beta0 - grad0/phi
beta1[self.itcp:] = self.soft_thresh(beta1[self.itcp:], Lambda/phi)
diff_beta = beta1 - beta0
r0 = diff_beta.dot(diff_beta)
res = self.Y - X.dot(beta1)
loss_proxy = loss_eval0 + diff_beta.dot(grad0) + 0.5*phi*r0
loss_eval1 = self.retire_loss(res, tau, c)
while loss_proxy < loss_eval1:
phi *= self.opt['gamma']
beta1 = beta0 - grad0/phi
beta1[self.itcp:] = self.soft_thresh(beta1[self.itcp:], Lambda/phi)
diff_beta = beta1 - beta0
r0 = diff_beta.dot(diff_beta)
res = self.Y - X.dot(beta1)
loss_proxy = loss_eval0 + diff_beta.dot(grad0) + 0.5*phi*r0
loss_eval1 = self.retire_loss(res, tau, c)
dev = max(abs(diff_beta))
beta0, phi = beta1, self.opt['phi']
count += 1
if standardize and adjust:
beta0[self.itcp:] = beta0[self.itcp:]/self.sdX
if self.itcp: beta0[0] -= self.mX.dot(beta0[1:])
return {'beta': beta0, 'res': res, 'niter': count, 'lambda': Lambda}
def l1(self, tau=0.5, Lambda=np.array([]),
h=None, kernel="Gaussian",
beta0=np.array([]), res=np.array([]),
standardize=True, adjust=True, weight=np.array([])):
'''
L1-Penalized Convolution Smoothed Quantile Regression (l1-conquer)
Args:
tau : quantile level; default is 0.5.
Lambda : regularization parameter. This should be either a scalar, or
a vector of length equal to the column dimension of X. If unspecified,
it will be computed by self.self_tuning().
h : bandwidth/smoothing parameter; the default value is computed by self.bandwidth().
kernel : a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
beta0 : initial estimate. If unspecified, it will be set as a vector of zeros.
res : residual vector of the initial estimate.
standardize : logical flag for x variable standardization prior to fitting the model;
default is TRUE.
adjust : logical flag for returning coefficients on the original scale.
weight : an ndarray of observation weights; default is np.array([]) (empty).
Returns:
'beta' : an ndarray of estimated coefficients.
'res' : an ndarray of fitted residuals.
'niter' : number of iterations.
'lambda' : lambda value.
'bw' : bandwidth.
'''
X = self.X1 if standardize else self.X
if not np.array(Lambda).any():
Lambda = 0.75*np.quantile(self.self_tuning(tau,standardize), 0.9)
if h is None: h = self.bandwidth(tau)
if len(beta0) == 0:
if self.opt['warm_start']:
init = self.l1_retire(tau, Lambda, standardize=standardize, adjust=False)
beta0, res = init['beta'], init['res']
else:
beta0 = np.zeros(X.shape[1])
if self.itcp: beta0[0] = np.quantile(self.Y, tau)
res = self.Y - beta0[0]
elif len(beta0) == X.shape[1]:
res = self.Y - X.dot(beta0)
else:
raise ValueError("dimension of beta0 must match parameter dimension")
phi, r0, t = self.opt['phi'], 1, 0
while r0 > self.opt['tol'] and t < self.opt['max_iter']:
grad0 = X.T.dot(self.conquer_weight(-res/h, tau, kernel, weight) / self.n)
loss_eval0 = self.smooth_check(res, tau, h, kernel, weight)
beta1 = beta0 - grad0/phi
beta1[self.itcp:] = self.soft_thresh(beta1[self.itcp:], Lambda/phi)
diff_beta = beta1 - beta0
r0 = diff_beta.dot(diff_beta)
res = self.Y - X.dot(beta1)
loss_proxy = loss_eval0 + diff_beta.dot(grad0) + 0.5*phi*r0
loss_eval1 = self.smooth_check(res, tau, h, kernel, weight)
while loss_proxy < loss_eval1:
phi *= self.opt['gamma']
beta1 = beta0 - grad0/phi
beta1[self.itcp:] = self.soft_thresh(beta1[self.itcp:], Lambda/phi)
diff_beta = beta1 - beta0
r0 = diff_beta.dot(diff_beta)
res = self.Y - X.dot(beta1)
loss_proxy = loss_eval0 + diff_beta.dot(grad0) + 0.5*phi*r0
loss_eval1 = self.smooth_check(res, tau, h, kernel, weight)
beta0, phi = beta1, self.opt['phi']
t += 1
if t == self.opt['max_iter'] and self.opt['iter_warning']:
warnings.warn("Maximum number of iterations achieved when applying l1()\
with Lambda={} and tau={}".format(Lambda, tau))
if standardize and adjust:
beta1[self.itcp:] = beta1[self.itcp:]/self.sdX
if self.itcp: beta1[0] -= self.mX.dot(beta1[1:])
return {'beta': beta1, 'res': res, 'niter': t, 'lambda': Lambda, 'bw': h}
def irw(self, tau=0.5, Lambda=np.array([]),
h=None, kernel="Laplacian",
beta0=np.array([]), res=np.array([]),
penalty="SCAD", a=3.7, nstep=3,
standardize=True, adjust=True, weight=np.array([])):
'''
Iteratively Reweighted L1-Penalized Conquer (irw-l1-conquer)
Args:
tau : quantile level; default is 0.5.
Lambda : regularization parameter. This should be either a scalar, or
a vector of length equal to the column dimension of X. If unspecified,
it will be computed by self.self_tuning().
h : bandwidth/smoothing parameter;
default value is computed by self.bandwidth().
kernel : a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
beta0 : initial estimator. If unspecified, it will be set as zero.
res : residual vector of the initial estiamtor.
penalty : a character string representing one of the built-in concave penalties;
default is "SCAD".
a : the constant (>2) in the concave penality; default is 3.7.
nstep : number of iterations/steps of the IRW algorithm; default is 3.
standardize : logical flag for x variable standardization prior to fitting the model;
default is TRUE.
adjust : logical flag for returning coefficients on the original scale.
weight : an ndarray of observation weights; default is np.array([]) (empty).
Returns:
'beta' : an ndarray of estimated coefficients.
'res' : an ndarray of fitted residuals.
'nstep' : number of reweighted penalization steps.
'lambda' : lambda value.
'niter' : total number of iterations.
'nit_seq' : a sequence of numbers of iterations.
'''
if not Lambda.any():
Lambda = 0.75*np.quantile(self.self_tuning(tau,standardize), 0.9)
if h is None: h = self.bandwidth(tau)
if len(beta0) == 0:
model = self.l1(tau, Lambda, h, kernel, standardize=standardize,
adjust=False, weight=weight)
else:
model = self.l1(tau, Lambda, h, kernel, beta0, res, standardize,
adjust=False, weight=weight)
nit_seq = []
beta0, res = model['beta'], model['res']
nit_seq.append(model['niter'])
if penalty == 'L1': nstep = 0
lam = Lambda * np.ones(len(self.mX))
pos = lam > 0
rw_lam = np.zeros(len(self.mX))
dev, step = 1, 1
while dev > self.opt['irw_tol'] and step <= nstep:
rw_lam[pos] = lam[pos] * \
self.concave_weight(beta0[self.itcp:][pos]/lam[pos], penalty, a)
model = self.l1(tau, rw_lam, h, kernel, beta0, res, standardize, \
adjust=False, weight=weight)
dev = max(abs(model['beta']-beta0))
beta0, res = model['beta'], model['res']
nit_seq.append(model['niter'])
step += 1
if standardize and adjust:
beta0[self.itcp:] = beta0[self.itcp:]/self.sdX
if self.itcp: beta0[0] -= self.mX.dot(beta0[1:])
nit_seq = np.array(nit_seq)
return {'beta': beta0, 'res': res, 'nstep': step, 'lambda': Lambda,
'niter': np.sum(nit_seq), 'nit_seq': nit_seq}
def irw_retire(self, tau=0.5, Lambda=np.array([]), robust=3,
penalty="SCAD", a=3.7, nstep=3,
standardize=True, adjust=True):
'''
Iteratively Reweighted L1-Penalized Retire (irw-l1-retire)
'''
if not Lambda.any():
Lambda = np.quantile(self.self_tuning(tau,standardize), 0.9)
model = self.l1_retire(tau, Lambda, robust, standardize=standardize, adjust=False)
beta0, res = model['beta'], model['res']
lam = Lambda * np.ones(len(self.mX))
pos = lam > 0
rw_lam = np.zeros(len(self.mX))
dev, step = 1, 1
while dev > self.opt['irw_tol'] and step <= nstep:
rw_lam[pos] = lam[pos] * \
self.concave_weight(beta0[self.itcp:][pos]/lam[pos], penalty, a)
model = self.l1_retire(tau, rw_lam, robust, \
beta0, res, standardize, adjust=False)
dev = max(abs(model['beta']-beta0))
beta0, res = model['beta'], model['res']
step += 1
if standardize and adjust:
beta0[self.itcp:] = beta0[self.itcp:]/self.sdX
if self.itcp: beta0[0] -= self.mX.dot(beta0[1:])
return {'beta': beta0, 'res': res, 'nstep': step, 'lambda': Lambda}
def l1_path(self, tau,
lambda_seq=np.array([]), nlambda=50, order="descend",
h=None, kernel="Laplacian",
standardize=True, adjust=True):
'''
Solution Path of L1-Penalized Conquer
Args:
tau : quantile level (float between 0 and 1).
lambda_seq : an ndarray of lambda values.
nlambda : number of lambda values (int).
order : a character string indicating the order of lambda values
along which the solution path is obtained; default is 'descend'.
h : bandwidth/smoothing parameter (float).
kernel : a character string representing one of the built-in smoothing kernels;
default is "Laplacian".
standardize : logical flag for x variable standardization prior to fitting the model;
default is TRUE.
adjust : logical flag for returning coefficients on the original scale.
Returns:
'beta_seq' : a sequence of l1-conquer estimates;
each column corresponds to an estiamte for a lambda value.
'res_seq' : a sequence of residual vectors.
'size_seq' : a sequence of numbers of selected variables.
'lambda_seq' : a sequence of lambda values in ascending/descending order.
'nit_seq' : a sequence of numbers of iterations.
'bw' : bandwidth.
'''
if h is None: h = self.bandwidth(tau)
if len(lambda_seq) == 0:
lam_max = max(self.self_tuning(tau, standardize))
lambda_seq = np.linspace(0.25*lam_max, lam_max, num=nlambda)
if order == 'ascend':
lambda_seq = np.sort(lambda_seq)
elif order == 'descend':
lambda_seq = np.sort(lambda_seq)[::-1]