-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathALVEN.py
More file actions
829 lines (609 loc) · 30.4 KB
/
ALVEN.py
File metadata and controls
829 lines (609 loc) · 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 20:51:44 2020
@author: Weike (Vicky) Sun vickysun@mit.edu/weike.sun93@gmail.com
(c) 2020 Weike Sun, all rights reserved
"""
import numpy as np
import nonlinear_regression as nr
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import f_regression
import math
import numpy.matlib as matlib
from sklearn.feature_selection import VarianceThreshold
from sklearn.linear_model import ElasticNet
def ALVEN_fitting(X, y, X_test, y_test, alpha, l1_ratio, degree, alpha_num = None, cv= False, max_iter = 10000,
tol = 1e-4, selection = 'p_value', select_value = 0.15, trans_type = 'auto'):
'''Algebric learning via elastic net
Input:
X: independent variables of size N x m, has to be non-zscored!
y: dependent variable of size N x 1, has to be non-zscored!
X_test: independent variables of size N_test x m
y_test: dependent variable of size N_test x 1
alpha: int, represents the index of the alpha in the list
l1_ratio: float, scaling between l1 and l2 penalties, from 0(Ridge) to 1(Lasso)
degree: int, order of nonlinearity you want to consider, can be chosen from 1 - 3
cv: whether it is cross-validation or final fitting
selection & select_value:selection ceriteria for the pre-processing step, default: according to 'p-value' with 10% significance
'percentage' and the percentatge of variables want to contain
'elbow' and use the point with the greatest orthogonal distace from the line linking the first and the last points
All the values are calculated based on f-regression (F statistic of univariate linear correlation)
trans_type: can choose either automatic transformation used in ALVEN ('auto'), or only polynomial transformation ('poly')
Output:
tuple (trained_model, model_params, mse_train, mse_test, yhat_train, yhat_test)
trained_model: EN model type
model_params: np_array m x 1
'''
#feature transformation
if trans_type == 'auto':
X, X_test = nr.feature_trans(X, X_test, degree = degree, interaction = 'later')
else:
X, X_test = nr.poly_feature(X, X_test, degree = degree, interaction = True, power = True)
#remove feature with 0 variance
sel = VarianceThreshold(threshold=tol).fit(X)
X=sel.transform(X)
X_test = sel.transform(X_test)
#zscore data
scaler_x = StandardScaler(with_mean=True, with_std=True)
scaler_x.fit(X)
X = scaler_x.transform(X)
X_test = scaler_x.transform(X_test)
scaler_y = StandardScaler(with_mean=True, with_std=True)
scaler_y.fit(y)
y = scaler_y.transform(y)
y_test = scaler_y.transform(y_test)
#eliminate feature
# if cv:
# X_e = np.concatenate((X,X_test),axis = 0)
# y_e = np.concatenate((y,y_test), axis = 0)
# f_test, p_values = f_regression(X_e, y_e.flatten())
# else:
# f_test, p_values = f_regression(X, y.flatten())
#eliminate feature
f_test, p_values = f_regression(X, y.flatten())
if selection == 'p_value':
X_fit = X[:,p_values<select_value]
X_test_fit = X_test[:,p_values<select_value]
retain_index = p_values<select_value
elif selection == 'percentage':
number = int(math.ceil(select_value * X.shape[1]))
f_test.sort()
value = f_test[-number]
X_fit = X[:,f_test>=value]
X_test_fit = X_test[:,f_test>=value]
retain_index = f_test>=value
else:
f = np.copy(f_test)
f.sort() #descending order
f = f[::-1]
axis = np.linspace(0,len(f)-1, len(f))
AllCord = np.concatenate((axis.reshape(-1,1),f.reshape(-1,1)),axis=1)
lineVec = AllCord[-1] - AllCord[0]
lineVec = lineVec/ np.sqrt(np.sum(lineVec**2))
#find the distance from each point to the line
vecFromFirst = AllCord- AllCord[0]
#and calculate the distance of each point to the line
scalarProduct = np.sum(vecFromFirst * matlib.repmat(lineVec, len(f), 1), axis=1)
vecFromFirstParallel = np.outer(scalarProduct, lineVec)
vecToLine = vecFromFirst - vecFromFirstParallel
distToLine = np.sqrt(np.sum(vecToLine ** 2, axis=1))
BestPoint = np.argmax(distToLine)
value = f[BestPoint]
X_fit = X[:,f_test>=value]
X_test_fit = X_test[:,f_test>=value]
retain_index = f_test>=value
#choose the appropriate alpha in cross_Validation: cv= Ture
if X_fit.shape[1] == 0:
print('no variable selected by ALVEN')
ALVEN_model = None
ALVEN_params = None
mse_train = np.var(y)
mse_test = np.var(y_test)
yhat_train = np.zeros(y.shape)
yhat_test = np.zeros(y_test.shape)
alpha = 0
else:
if alpha_num is not None and cv:
X_max = np.concatenate((X_fit,X_test_fit),axis = 0)
y_max = np.concatenate((y, y_test), axis = 0)
alpha_max = (np.sqrt(np.sum(np.dot(X_max.T,y_max) ** 2, axis=1)).max())/X_max.shape[0]/l1_ratio
alpha_list = np.logspace(np.log10(alpha_max * tol), np.log10(alpha_max), alpha_num)[::-1]
alpha = alpha_list[alpha]
if alpha_num is not None and not cv:
alpha_max = (np.sqrt(np.sum(np.dot(X_fit.T,y) ** 2, axis=1)).max())/X_fit.shape[0]/l1_ratio
alpha_list = np.logspace(np.log10(alpha_max * tol), np.log10(alpha_max), alpha_num)[::-1]
alpha = alpha_list[alpha]
#EN for model fitting
ALVEN_model, ALVEN_params, mse_train, mse_test, yhat_train, yhat_test = EN_fitting(X_fit, y, X_test_fit, y_test, alpha, l1_ratio, max_iter = max_iter, tol = tol)
return (ALVEN_model, ALVEN_params, mse_train, mse_test, yhat_train, yhat_test, alpha, retain_index)
def DALVEN_fitting(X, y, X_test, y_test, alpha, l1_ratio, degree, lag, alpha_num = None, cv= False, max_iter = 10000,
tol = 1e-4, selection = 'p_value', select_value = 0.15, trans_type = 'auto'):
'''Dyanmic Algebric learning via elastic net
Input:
X: independent variables of size N x m, has to be non-zscored!
y: dependent variable of size N x 1, has to be non-zscored!
X_test: independent variables of size N_test x m
y_test: dependent variable of size N_test x 1
alpha: int, represents the index of the alpha in the list
alpha_num: number of alpha want to be tested in the cross-validaiton list
l1_ratio: float, scaling between l1 and l2 penalties, from 0(Ridge) to 1(Lasso)
degree: int, order of nonlinearity you want to consider, can be chosen from 1 - 3
lag: int, lag of variables you want to consider, xt,xt-1,...xt-l,yt-1,...,yt-l
cv: whether it is cross-validation or final fitting
selection & select_value:selection ceriteria for the pre-processing step, default: according to 'p-value' with 10% significance
'percentage' and the percentatge of variables want to contain
'elbow' and use the point with the greatest orthogonal distace from the line linking the first and the last points
All the values are calculated based on f-regression (F statistic of univariate linear correlation)
trans_type: can choose either automatic transformation used in ALVEN ('auto'), or only polynomial transformation ('poly')
Output:
tuple (trained_model, model_params, mse_train, mse_test, yhat_train, yhat_test)
trained_model: EN model type
model_params: np_array m x 1
'''
#feature transformation
if trans_type == 'auto':
X, X_test = nr.feature_trans(X, X_test, degree = degree, interaction = 'later')
else:
X, X_test = nr.poly_feature(X, X_test, degree = degree, interaction = True, power = True)
#lag padding for X
XD = X[lag:]
XD_test = X_test[lag:]
for i in range(lag):
XD = np.hstack((XD,X[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,X_test[lag-1-i:-i-1]))
#lag padding for y in design matrix
for i in range(lag):
XD = np.hstack((XD,y[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,y_test[lag-1-i:-i-1]))
#shorterning y
y = y[lag:]
y_test = y_test[lag:]
#remove feature with 0 variance
sel = VarianceThreshold(threshold=tol).fit(XD)
XD=sel.transform(XD)
XD_test = sel.transform(XD_test)
#zscore data
scaler_x = StandardScaler(with_mean=True, with_std=True)
scaler_x.fit(XD)
XD = scaler_x.transform(XD)
XD_test = scaler_x.transform(XD_test)
scaler_y = StandardScaler(with_mean=True, with_std=True)
scaler_y.fit(y)
y = scaler_y.transform(y)
y_test = scaler_y.transform(y_test)
#eliminate feature
f_test, p_values = f_regression(XD, y.flatten())
if selection == 'p_value':
XD_fit = XD[:,p_values<select_value]
XD_test_fit = XD_test[:,p_values<select_value]
retain_index = p_values<select_value
elif selection == 'percentage':
number = int(math.ceil(select_value * XD.shape[1]))
f_test.sort()
value = f_test[-number]
XD_fit = XD[:,f_test>=value]
XD_test_fit = XD_test[:,f_test>=value]
retain_index = f_test>=value
else:
f = np.copy(f_test)
f.sort() #descending order
f = f[::-1]
axis = np.linspace(0,len(f)-1, len(f))
AllCord = np.concatenate((axis.reshape(-1,1),f.reshape(-1,1)),axis=1)
lineVec = AllCord[-1] - AllCord[0]
lineVec = lineVec/ np.sqrt(np.sum(lineVec**2))
#find the distance from each point to the line
vecFromFirst = AllCord- AllCord[0]
#and calculate the distance of each point to the line
scalarProduct = np.sum(vecFromFirst * matlib.repmat(lineVec, len(f), 1), axis=1)
vecFromFirstParallel = np.outer(scalarProduct, lineVec)
vecToLine = vecFromFirst - vecFromFirstParallel
distToLine = np.sqrt(np.sum(vecToLine ** 2, axis=1))
BestPoint = np.argmax(distToLine)
value = f[BestPoint]
XD_fit = XD[:,f_test>=value]
XD_test_fit = XD_test[:,f_test>=value]
retain_index = f_test>=value
#choose the appropriate alpha in cross_Validation: cv= Ture
if XD_fit.shape[1] == 0:
print('no variable selected by ALVEN')
DALVEN_model = None
DALVEN_params = None
mse_train = np.var(y)
mse_test = np.var(y_test)
yhat_train = np.zeros(y.shape)
yhat_test = np.zeros(y_test.shape)
alpha = 0
else:
if alpha_num is not None and cv:
XD_max = np.concatenate((XD_fit,XD_test_fit),axis = 0)
y_max = np.concatenate((y, y_test), axis = 0)
alpha_max = (np.sqrt(np.sum(np.dot(XD_max.T,y_max) ** 2, axis=1)).max())/XD_max.shape[0]/l1_ratio
alpha_list = np.logspace(np.log10(alpha_max * tol), np.log10(alpha_max), alpha_num)[::-1]
alpha = alpha_list[alpha]
if alpha_num is not None and not cv:
alpha_max = (np.sqrt(np.sum(np.dot(XD_fit.T,y) ** 2, axis=1)).max())/XD_fit.shape[0]/l1_ratio
alpha_list = np.logspace(np.log10(alpha_max * tol), np.log10(alpha_max), alpha_num)[::-1]
alpha = alpha_list[alpha]
#EN for model fitting
DALVEN_model, DALVEN_params, mse_train, mse_test, yhat_train, yhat_test = EN_fitting(XD_fit, y, XD_test_fit, y_test, alpha, l1_ratio, max_iter = max_iter, tol = tol)
num_train = XD_fit.shape[0]
num_parameter = sum(DALVEN_params!=0)[0]
AIC = num_train*np.log(mse_train) + 2*num_parameter
AICc = num_train*np.log(mse_train) + (num_parameter+num_train)/(1-(num_parameter+2)/num_train)
BIC = num_train*np.log(mse_train) + num_parameter*np.log(num_train)
return (DALVEN_model, DALVEN_params, mse_train, mse_test, yhat_train, yhat_test, alpha, retain_index,(AIC,AICc,BIC))
def DALVEN_testing_kstep(X, y, X_test, y_test, ALVEN_model, retain_index, degree, lag, k_step =1, tol = 1e-4, trans_type = 'auto', plot = False, round_number = ''):
'''Dyanmic Algebric learning via elastic net for k_step ahead prediction (pre-request: trained DALVEN model)
Input:
X: independent variables of size N x m, has to be non-zscored!
y: dependent variable of size N x 1, has to be non-zscored!
X_test: independent variables of size N_test x m
y_test: dependent variable of size N_test x 1
ALVEN_model: trained DALVEN model from DALVEN_fitting
retain_index: return from DALVEN_fitting in DALVEN_hyper by CV or AIC
degree: selected degree of nonlinearity in DALVEN_fitting
lag: selected lag number in DALVEN_fitting
k_step: positive integer, default =1, number of steps want to predict in to the future
tol: tolerance for 0-variance feature selection, should be the same as in DALVEN_fitting
trans_type: transformation type, default = 'auto' is the one include lag, sqrt, 1/x and interactions
Output:
tuple (trained_model, model_params, mse_train, mse_test, yhat_train, yhat_test)
trained_model: EN model type
model_params: np_array m x 1
'''
#feature transformation
if trans_type == 'auto':
X, X_test = nr.feature_trans(X, X_test, degree = degree, interaction = 'later')
else:
X, X_test = nr.poly_feature(X, X_test, degree = degree, interaction = True, power = True)
#lag padding for X
XD = X[lag:]
XD_test = X_test[lag:]
for i in range(lag):
XD = np.hstack((XD,X[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,X_test[lag-1-i:-i-1]))
#lag padding for y in design matrix
for i in range(lag):
XD = np.hstack((XD,y[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,y_test[lag-1-i:-i-1]))
#shorterning y
y = y[lag:]
y_test = y_test[lag:]
#remove feature with 0 variance
sel = VarianceThreshold(threshold=tol).fit(XD)
XD=sel.transform(XD)
XD_test = sel.transform(XD_test)
position = XD.shape[1]-lag
#zscore data
scaler_x = StandardScaler(with_mean=True, with_std=True)
scaler_x.fit(XD)
XD = scaler_x.transform(XD)
XD_test = scaler_x.transform(XD_test)
scaler_y = StandardScaler(with_mean=True, with_std=True)
scaler_y.fit(y)
y = scaler_y.transform(y)
y_test = scaler_y.transform(y_test)
#eliminate feature
XD_test_fit = XD_test[:,retain_index]
#0-step results
yhat_test_multi = {}
mse_test_multi = np.zeros((k_step,1))
yhat_test_multi[0] = ALVEN_model.predict(XD_test_fit).reshape((-1,1))
mse_test_multi[0] = mse(y_test, yhat_test_multi[0])
k_step = k_step -1
#multi-step prediction
for k in range(k_step):
#lag padding for y in design matrix
XD_test = XD_test[1:]
for l in range(min(lag,k+1)):
XD_test[:,position+l] = yhat_test_multi[k-l][:-1-l].flatten()
XD_test_fit = XD_test[:,retain_index]
yhat_test_multi[k+1] = ALVEN_model.predict(XD_test_fit).reshape((-1,1))
mse_test_multi[k+1] = mse(y_test[k+1:], yhat_test_multi[k+1])
##plot results
if plot:
if X.shape[0] == X_test.shape[0]:
if abs(np.sum(X-X_test))<tol:
my_data = 'train'
else:
my_data = 'test'
else:
my_data = 'test'
print('=============Plot Results==============')
import matplotlib.pyplot as plt
s=12
plt.figure(figsize=(3,2))
plt.plot(mse_test_multi, 'd-')
plt.title('MSE for y ' + my_data + ' prediction', fontsize = s)
plt.xlabel('k-step ahead', fontsize = s)
plt.ylabel('MSE', fontsize = s)
plt.savefig('MSE_'+my_data+round_number+'_DALVEN.png', dpi=600,bbox_inches='tight')
import matplotlib
cmap = matplotlib.cm.get_cmap('Paired')
#plot the prediction vs real
for i in range(k_step+1):
plt.figure(figsize=(5,3))
plt.plot(y_test[i+1:], color= cmap(1), label= 'real')
plt.plot(yhat_test_multi[i][1:], '--',color= 'xkcd:coral', label = 'prediction')
plt.title(my_data + ' data ' + str(i+1) +'-step prediction',fontsize=s)
plt.xlabel('Time index',fontsize=s)
plt.ylabel('y',fontsize=s)
plt.legend(fontsize=s)
plt.tight_layout()
plt.savefig('DALVEN_'+my_data+'_step_'+str(i+1)+ round_number+'.png', dpi = 600,bbox_inches='tight')
return (mse_test_multi, yhat_test_multi)
##########################################################################################
def DALVEN_fitting_full_nonlinear(X, y, X_test, y_test, alpha, l1_ratio, degree, lag, alpha_num = None, cv= False, max_iter = 10000,
tol = 1e-4, selection = 'p_value', select_value = 0.05, trans_type = 'auto'):
'''Dyanmic Algebric learning via elastic net with fully nonlienar mapping fo both x and y and interactions
Input:
X: independent variables of size N x m, has to be non-zscored!
y: dependent variable of size N x 1, has to be non-zscored!
X_test: independent variables of size N_test x m
y_test: dependent variable of size N_test x 1
alpha: float, regularization parameter/ int, used when cross-validation, the ith one to use
l1_ratio: float, scaling between l1 and l2 penalties, from 0(Ridge) to 1(Lasso)
degree: int, order of nonlinearity you want to consider, can be chosen from 1 - 3
lag: int, lag of variables you want to consider, xt,xt-1,...xt-l,yt-1,...,yt-l
cv: whether it is cross-validation or final fitting
selection & select_value:selection ceriteria for the pre-processing step, default: according to 'p-value' with 10% significance
'percentage' and the percentatge of variables want to contain
'elbow' and use the point with the greatest orthogonal distace from the line linking the first and the last points
All the values are calculated based on f-regression (F statistic of univariate linear correlation)
trans_type: can choose either automatic transformation used in ALVEN ('auto'), or only polynomial transformation ('poly')
Output:
tuple (trained_model, model_params, mse_train, mse_test, yhat_train, yhat_test)
trained_model: EN model type
model_params: np_array m x 1
'''
#lag design matrix first
#lag padding for X
XD = X[lag:]
XD_test = X_test[lag:]
for i in range(lag):
XD = np.hstack((XD,X[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,X_test[lag-1-i:-i-1]))
#lag padding for y in design matrix
for i in range(lag):
XD = np.hstack((XD,y[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,y_test[lag-1-i:-i-1]))
#nonliner mapping
#feature transformation
if trans_type == 'auto':
XD, XD_test = nr.feature_trans(XD, XD_test, degree = degree, interaction = 'later')
else:
XD, XD_test = nr.poly_feature(XD, XD_test, degree = degree, interaction = True, power = True)
#remove feature with 0 variance
sel = VarianceThreshold(threshold=tol).fit(XD)
XD=sel.transform(XD)
XD_test = sel.transform(XD_test)
#shorterning y
y = y[lag:]
y_test = y_test[lag:]
#zscore data
scaler_x = StandardScaler(with_mean=True, with_std=True)
scaler_x.fit(XD)
XD = scaler_x.transform(XD)
XD_test = scaler_x.transform(XD_test)
scaler_y = StandardScaler(with_mean=True, with_std=True)
scaler_y.fit(y)
y = scaler_y.transform(y)
y_test = scaler_y.transform(y_test)
#eliminate feature
f_test, p_values = f_regression(XD, y.flatten())
if selection == 'p_value':
XD_fit = XD[:,p_values<select_value]
XD_test_fit = XD_test[:,p_values<select_value]
retain_index = p_values<select_value
elif selection == 'percentage':
number = int(math.ceil(select_value * XD.shape[1]))
f_test.sort()
value = f_test[-number]
XD_fit = XD[:,f_test>=value]
XD_test_fit = XD_test[:,f_test>=value]
retain_index = f_test>=value
else:
f = np.copy(f_test)
f.sort() #descending order
f = f[::-1]
axis = np.linspace(0,len(f)-1, len(f))
AllCord = np.concatenate((axis.reshape(-1,1),f.reshape(-1,1)),axis=1)
lineVec = AllCord[-1] - AllCord[0]
lineVec = lineVec/ np.sqrt(np.sum(lineVec**2))
#find the distance from each point to the line
vecFromFirst = AllCord- AllCord[0]
#and calculate the distance of each point to the line
scalarProduct = np.sum(vecFromFirst * matlib.repmat(lineVec, len(f), 1), axis=1)
vecFromFirstParallel = np.outer(scalarProduct, lineVec)
vecToLine = vecFromFirst - vecFromFirstParallel
distToLine = np.sqrt(np.sum(vecToLine ** 2, axis=1))
BestPoint = np.argmax(distToLine)
value = f[BestPoint]
XD_fit = XD[:,f_test>=value]
XD_test_fit = XD_test[:,f_test>=value]
retain_index = f_test>=value
#choose the appropriate alpha in cross_Validation: cv= Ture
if XD_fit.shape[1] == 0:
print('no variable selected by ALVEN')
DALVEN_model = None
DALVEN_params = None
mse_train = np.var(y)
mse_test = np.var(y_test)
yhat_train = np.zeros(y.shape)
yhat_test = np.zeros(y_test.shape)
alpha = 0
else:
if alpha_num is not None and cv:
XD_max = np.concatenate((XD_fit,XD_test_fit),axis = 0)
y_max = np.concatenate((y, y_test), axis = 0)
alpha_max = (np.sqrt(np.sum(np.dot(XD_max.T,y_max) ** 2, axis=1)).max())/XD_max.shape[0]/l1_ratio
alpha_list = np.logspace(np.log10(alpha_max * tol), np.log10(alpha_max), alpha_num)[::-1]
alpha = alpha_list[alpha]
if alpha_num is not None and not cv:
alpha_max = (np.sqrt(np.sum(np.dot(XD_fit.T,y) ** 2, axis=1)).max())/XD_fit.shape[0]/l1_ratio
alpha_list = np.logspace(np.log10(alpha_max * tol), np.log10(alpha_max), alpha_num)[::-1]
alpha = alpha_list[alpha]
#EN for model fitting
DALVEN_model, DALVEN_params, mse_train, mse_test, yhat_train, yhat_test = EN_fitting(XD_fit, y, XD_test_fit, y_test, alpha, l1_ratio, max_iter = max_iter, tol = tol)
num_train = XD_fit.shape[0]
num_parameter = sum(DALVEN_params!=0)[0]
AIC = num_train*np.log(mse_train) + 2*num_parameter
AICc = num_train*np.log(mse_train) + (num_parameter+num_train)/(1-(num_parameter+2)/num_train)
BIC = num_train*np.log(mse_train) + num_parameter*np.log(num_train)
return (DALVEN_model, DALVEN_params, mse_train, mse_test, yhat_train, yhat_test, alpha, retain_index,(AIC,AICc,BIC))
def DALVEN_testing_kstep_full_nonlinear(X, y, X_test, y_test, ALVEN_model, retain_index, degree, lag, k_step =1, tol = 1e-4, trans_type = 'auto', plot = False, round_number = ''):
'''Dyanmic Algebric learning via elastic net for k_step ahead prediction (pre-request: trained DALVEN model with full nonlinearity)
Input:
X: independent variables of size N x m, has to be non-zscored!
y: dependent variable of size N x 1, has to be non-zscored!
X_test: independent variables of size N_test x m
y_test: dependent variable of size N_test x 1
ALVEN_model: trained DALVEN model from DALVEN_fitting
retain_index: return from DALVEN_fitting in DALVEN_hyper by CV or AIC
degree: selected degree of nonlinearity in DALVEN_fitting
lag: selected lag number in DALVEN_fitting
k_step: positive integer, default =1, number of steps want to predict in to the future
tol: tolerance for 0-variance feature selection, should be the same as in DALVEN_fitting
trans_type: transformation type, default = 'auto' is the one include lag, sqrt, 1/x and interactions
Output:
tuple (trained_model, model_params, mse_train, mse_test, yhat_train, yhat_test)
trained_model: EN model type
model_params: np_array m x 1
'''
#lag design matrix first
#lag padding for X
XD = X[lag:]
XD_test = X_test[lag:]
for i in range(lag):
XD = np.hstack((XD,X[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,X_test[lag-1-i:-i-1]))
#lag padding for y in design matrix
for i in range(lag):
XD = np.hstack((XD,y[lag-1-i:-i-1]))
XD_test = np.hstack((XD_test,y_test[lag-1-i:-i-1]))
#nonliner mapping
#feature transformation
if trans_type == 'auto':
XD, XD_test = nr.feature_trans(XD, XD_test, degree = degree, interaction = 'later')
else:
XD, XD_test = nr.poly_feature(XD, XD_test, degree = degree, interaction = True, power = True)
#remove feature with 0 variance
sel = VarianceThreshold(threshold=tol).fit(XD)
XD=sel.transform(XD)
XD_test = sel.transform(XD_test)
#shorterning y
y = y[lag:]
y_test_ori = y_test[:]
y_test = y_test[lag:]
#zscore data
scaler_x = StandardScaler(with_mean=True, with_std=True)
scaler_x.fit(XD)
XD = scaler_x.transform(XD)
XD_test = scaler_x.transform(XD_test)
scaler_y = StandardScaler(with_mean=True, with_std=True)
scaler_y.fit(y)
y_test = scaler_y.transform(y_test)
# y_test_ori = scaler_y.transform(y_test_ori)
#eliminate feature
XD_test_fit = XD_test[:,retain_index]
#0-step results
yhat_test_multi = {}
mse_test_multi = np.zeros((k_step,1))
yhat_test_multi[0] = ALVEN_model.predict(XD_test_fit).reshape((-1,1))
mse_test_multi[0] = mse(y_test, yhat_test_multi[0])
# print('starting k step prediction')
k_step = k_step -1
#multi-step prediction######################
for k in range(k_step):
# print(k+2)
#################mapping
XD_test = X_test[lag+k+1:]
for i in range(lag):
XD_test = np.hstack((XD_test,X_test[lag+k-i:-i-1]))
position = XD_test.shape[1]
#lag padding for y in design matrix
for i in range(lag):
XD_test = np.hstack((XD_test,y_test_ori[lag+k-i:-i-1]))
for l in range(min(lag,k+1)):
y_feed= yhat_test_multi[k-l]
y_feed=scaler_y.inverse_transform(y_feed)
XD_test[:,position+l] = y_feed[:-1-l].flatten()
#nonliner mapping
#feature transformation
if trans_type == 'auto':
XD_test,_ = nr.feature_trans(XD_test, degree = degree, interaction = 'later')
else:
XD_test ,_= nr.poly_feature(XD_test, degree = degree, interaction = True, power = True)
#remove feature with 0 variance
XD_test = sel.transform(XD_test)
XD_test = scaler_x.transform(XD_test)
XD_test_fit = XD_test[:,retain_index]
yhat_test_multi[k+1] = ALVEN_model.predict(XD_test_fit).reshape((-1,1))
mse_test_multi[k+1] = mse(y_test[k+1:], yhat_test_multi[k+1])
##plot results
if plot:
if X.shape[0] == X_test.shape[0]:
if abs(np.sum(X-X_test))<tol:
my_data = 'train'
else:
my_data = 'test'
else:
my_data = 'test'
print('=============Plot Results==============')
import matplotlib.pyplot as plt
s=12
plt.figure(figsize=(3,2))
plt.plot(mse_test_multi, 'd-')
plt.title('MSE for y ' + my_data + ' prediction', fontsize = s)
plt.xlabel('k-step ahead', fontsize = s)
plt.ylabel('MSE', fontsize = s)
plt.savefig('MSE_'+my_data+ round_number+'_DALVEN.png', dpi=600,bbox_inches='tight')
import matplotlib
cmap = matplotlib.cm.get_cmap('Paired')
#plot the prediction vs real
for i in range(k_step+1):
plt.figure(figsize=(5,3))
plt.plot(y_test[i+1:], color= cmap(1), label= 'real')
plt.plot(yhat_test_multi[i][1:], '--',color= 'xkcd:coral', label = 'prediction')
plt.title(my_data + ' data ' + str(i+1) +'-step prediction',fontsize=s)
plt.xlabel('Time index',fontsize=s)
plt.ylabel('y',fontsize=s)
plt.legend(fontsize=s)
plt.tight_layout()
plt.savefig('DALVEN_'+my_data+'_step_'+str(i+1)+ round_number+'.png', dpi = 600,bbox_inches='tight')
return (mse_test_multi, yhat_test_multi)
def EN_fitting(X, y, X_test, y_test, alpha, l1_ratio, max_iter = 10000, tol = 1e-4):
'''Elastic Net https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html
Input:
X: independent variables of size N x m
y: dependent variable of size N x 1
X_test: independent variables of size N_test x m
y_test: dependent variable of size N_test x 1
alpha: float, regularization parameter
l1_ratio: float, scaling between l1 and l2 penalties, from 0(Ridge) to 1(Lasso)
Output:
tuple (trained_model, model_params, mse_train, mse_test, yhat_train, yhat_test)
trained_model: EN model type
model_params: np_array m x 1
'''
#build model
EN_model = ElasticNet(random_state = 0, alpha = alpha, l1_ratio = l1_ratio, fit_intercept = False, max_iter=max_iter, tol = tol)
EN_model.fit(X, y)
#get paramsters
EN_params = EN_model.coef_.reshape((-1,1))
#get prediction
yhat_train = EN_model.predict(X).reshape((-1,1))
mse_train = mse(y, yhat_train)
#get prediction for testing
yhat_test = EN_model.predict(X_test).reshape((-1,1))
mse_test = mse(y_test, yhat_test)
return (EN_model, EN_params, mse_train, mse_test, yhat_train, yhat_test)
def mse(y, yhat):
"""
This function calculate the goodness of fit mse
Input: y: N x 1 real response
yhat: N x 1 predited by the model
Output: mse
"""
return np.sum((yhat-y)**2)/y.shape[0]