-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregression.py
More file actions
1664 lines (1306 loc) · 51.5 KB
/
regression.py
File metadata and controls
1664 lines (1306 loc) · 51.5 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
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
#!/usr/bin/env python
import os
import sys
import numpy as np
from tools import sorted_eigh
# TODO: Remove auxiliary phi centering in sparse methods
# TODO: CovR scaling consistent with paper? Should probably include auto-scaling and auto-centering, so make different scale types an option, and make sure sparse is done correctly. Also try per-property Y (and X) scaling, which will propagate to the loss functions
# TODO: check loss functions
# TODO: make abstract base class with fit, transform, losses
# TODO: clean up the inverse_transform functions
class LR(object):
"""
Performs linear regression
---Attributes---
W: regression weights
regularization: regularization parameter
regularization_type: type of regularization.
Choices are 'scalar' (constant regularization),
or 'max_eig' (regularization based on maximum eigenvalue)
---Methods---
fit: fit the linear regression model by computing regression weights
predict: compute predicted Y values
---References---
1. https://en.wikipedia.org/wiki/Linear_regression
"""
def __init__(self, regularization=1.0E-12,
regularization_type='scalar', rcond=None):
self.regularization = regularization
self.regularization_type = regularization_type
self.rcond = rcond
self.W = None
def fit(self, X, Y):
"""
Fits the linear regression model
---Arguments---
X: centered independent (predictor) variable
Y: centered dependent (response) variable
"""
XTX = np.matmul(X.T, X)
# Regularize the model
if self.regularization_type == 'max_eig':
scale = np.amax(np.linalg.eigvalsh(XTX))
elif self.regularization_type == 'scalar':
scale = 1.0
else:
print("Error: invalid regularization_type. Use 'scalar' or 'max_eig'")
return
XTX += np.eye(XTX.shape[0])*scale*self.regularization
XY = np.matmul(X.T, Y)
# Compute LR solution
self.W = np.linalg.lstsq(XTX, XY, rcond=self.rcond)[0]
# The below is another valid formulation for numpy lstsq;
# we use the above so we can add the regularization
# and for consistency with the kernel methods
#self.W = np.linalg.lstsq(X, Y, rcond=self.rcond)[0]
def predict(self, X):
"""
Computes predicted Y values
---Arguments---
X: centered independent (predictor) variable
---Returns---
Yp: centered predicted Y values
"""
if self.W is None:
print("Must fit the LR model before transforming")
else:
# Compute predicted Y
Yp = np.matmul(X, self.W)
return Yp
class KRR(object):
"""
Performs kernel ridge regression
---Attributes---
regularization: regularization parameter
regularization_type: type of regularization.
Choices are 'scalar' (constant regularization),
or 'max_eig' (regularization based on maximum eigenvalue)
W: regression weights
---Methods---
fit: fit the KRR model by computing regression weights
predict: compute predicted Y values
---References---
1. M. Ceriotti, M. J. Willatt, G. Csanyi,
'Machine Learning of Atomic-Scale Properties
Based on Physical Principles', Handbook of Materials Modeling,
Springer, 2018
"""
def __init__(self, regularization=1.0E-12,
regularization_type='scalar', rcond=None):
self.regularization = regularization
self.regularization_type = regularization_type
self.rcond = rcond
self.W = None
def fit(self, K, Y):
"""
Fits the KRR model by computing the regression weights
---Arguments---
K: centered kernel between training data
Y: centered property values
"""
# Regularize the model
if self.regularization_type == 'max_eig':
scale = np.amax(np.linalg.eigvalsh(K))
elif self.regularization_type == 'scalar':
scale = 1.0
else:
print("Error: invalid regularization_type. Use 'scalar' or 'max_eig'")
return
KX = K + np.eye(K.shape[0])*scale*self.regularization
# Solve the model
self.W = np.linalg.lstsq(KX, Y, rcond=self.rcond)[0]
def predict(self, K):
"""
Computes predicted Y values
---Arguments---
K: centered kernel matrix between training and testing data
---Returns---
Yp: centered predicted Y values
"""
if self.W is None:
print("Error: must fit the KRR model before transforming")
else:
# Compute predicted Y values
Yp = np.matmul(K, self.W)
return Yp
class SparseKRR(object):
"""
Performs sparsified kernel ridge regression
---Attributes---
sigma: regularization parameter
regularization: additional regularization
regularization_type: type of regularization.
Choices are 'scalar' (constant regularization),
or 'max_eig' (regularization based on maximum eigenvalue)
W: regression weights
---Methods---
fit: fit the sparse KRR model by computing regression weights
predict: compute predicted Y values
---References---
1. M. Ceriotti, M. J. Willatt, G. Csanyi,
'Machine Learning of Atomic-Scale Properties
Based on Physical Principles', Handbook of Materials Modeling,
Springer, 2018
2. A. J. Smola, B. Scholkopf, 'Sparse Greedy Matrix Approximation
for Machine Learning', Proceedings of the 17th International
Conference on Machine Learning, 911-918, 2000
"""
def __init__(self, sigma=1.0, regularization=1.0E-12,
regularization_type='scalar', rcond=None):
self.sigma = sigma
self.regularization = regularization
self.regularization_type = regularization_type
self.rcond = rcond
self.W = None
def fit(self, KNM, KMM, Y):
"""
Fits the KRR model by computing the regression weights
---Arguments---
KNM: centered kernel between the whole dataset
and the representative points
KMM: centered kernel between the representative points
Y: centered property values
"""
KX = self.sigma*KMM + np.matmul(KNM.T, KNM)
# Regularize the sparse kernel model
if self.regularization_type == 'max_eig':
scale = np.amax(np.linalg.eigvalsh(KX))
elif self.regularization_type == 'scalar':
scale = 1.0
else:
print("Error: invalid regularization_type. Use 'scalar' or 'max_eig'")
return
KX += np.eye(KMM.shape[0])*scale*self.regularization
KY = np.matmul(KNM.T, Y)
# Solve KRR model
self.W = np.linalg.lstsq(KX, KY, rcond=self.rcond)[0]
def predict(self, KNM):
"""
Computes predicted Y values
---Arguments---
K: centered kernel matrix between training and testing data
---Returns---
Yp: centered predicted Y values
"""
if self.W is None:
print("Error: must fit the KRR model before transforming")
else:
Yp = np.matmul(KNM, self.W)
return Yp
class IterativeSparseKRR(object):
"""
Performs sparsified kernel ridge regression. Example usage:
KMM = build_kernel(Xm, Xm)
iskrr = IterativeSparseKRR()
iskrr.initialize_fit(KMM)
for i in batches:
KNMi = build_kernel(Xi, Xm)
iskrr.fit_batch(KNMi, Yi)
iskrr.finalize_fit()
for i in batches:
KNMi = build_kernel(Xi, Xm)
iskrr.predict(KNMi)
---Attributes---
sigma: regularization parameter
regularization: additional regularization
regularization_type: type of regularization.
Choices are 'scalar' (constant regularization),
or 'max_eig' (regularization based on maximum eigenvalue)
W: regression weights
KMM: centered kernel between representative points
KY: product of the KNM kernel and the properties Y
---Methods---
initialize_fit: initialize the fit of the sparse KRR
(i.e., store KMM)
fit_batch: fit a batch of training data
finalize_fit: finalize the KRR fitting
(i.e., compute regression weights)
predict: compute predicted Y values
---References---
1. M. Ceriotti, M. J. Willatt, G. Csanyi,
'Machine Learning of Atomic-Scale Properties
Based on Physical Principles', Handbook of Materials Modeling,
Springer, 2018
2. A. J. Smola, B. Scholkopf, 'Sparse Greedy Matrix Approximation
for Machine Learning', Proceedings of the 17th International
Conference on Machine Learning, 911-918, 2000
"""
def __init__(self, sigma=1.0, regularization=1.0E-12,
regularization_type='scalar', rcond=None):
self.sigma = sigma
self.regularization = regularization
self.regularization_type = regularization_type
self.rcond = rcond
self.W = None
self.KX = None
self.KY = None
self.y_dim = None
def initialize_fit(self, KMM, y_dim=1):
"""
Initialize the KRR fitting by computing the
eigendecomposition of KMM
---Arguments---
KMM: centered kernel between the representative points
y_dim: number of properties
"""
# Check for valid Y dimension
if y_dim < 1:
print("Y dimension must be at least 1")
return
# Initialize arrays
self.y_dim = y_dim
self.KX = self.sigma*KMM
self.KY = np.zeros((KMM.shape[0], self.y_dim))
def fit_batch(self, KNM, Y):
"""
Fits the KRR model by computing the regression weights
---Arguments---
KNM: centered kernel between the whole dataset "
"and the representative points
Y: centered property values
"""
if self.KX is None:
print("Error: must initialize the fit before fitting the batch")
return
# Turn scalar into 2D array
if not isinstance(Y, np.ndarray):
Y = np.array([[Y]])
# Reshape 1D kernel
if KNM.ndim < 2:
KNM = np.reshape(KNM, (1, -1))
# Reshape 1D properties
if Y.ndim < 2:
Y = np.reshape(Y, (-1, self.y_dim))
# Increment KX and KY
self.KX += np.matmul(KNM.T, KNM)
self.KY += np.matmul(KNM.T, Y)
def finalize_fit(self):
"""
Finalize the iterative fitting of the sparse KRR model
by computing regression weights
"""
# Regularize the model
if self.regularization_type == 'max_eig':
scale = np.amax(np.linalg.eigvalsh(KX))
elif self.regularization_type == 'scalar':
scale = 1.0
else:
print("Error: invalid regularization_type. Use 'scalar' or 'max_eig'")
return
self.KX += np.eye(self.KX.shape[0])*scale*self.regularization
# Solve KRR model
self.W = np.linalg.lstsq(self.KX, self.KY, rcond=self.rcond)[0]
def predict(self, KNM):
"""
Computes predicted Y values
---Arguments---
KNM: centered kernel matrix between training and testing data
---Returns---
Yp: centered predicted Y values
"""
if self.W is None:
print("Error: must fit the KRR model before transforming")
else:
Yp = np.matmul(KNM, self.W)
return Yp
class PCovR(object):
"""
Performs principal covariates regression
---Attributes---
alpha: tuning parameter between PCA and LR
n_components: number of PCA components to retain
regularization: regularization parameter
regularization_type: type of regularization.
Choices are 'scalar' (constant regularization),
or 'max_eig' (regularization based on maximum eigenvalue)
tiny: cutoff for throwing away small eigenvalues
U: eigenvalues of G
V: eigenvectors of G
Pxt: projection matrix from input space (X) to latent space (T)
Ptx: projection matrix from latent space (T) to input space (X)
Pty: projection matrix from latent space (T) to properties (Y)
P_scale: scaling for projection matrices
Y_norm: scaling for the LR term of G
---Methods---
_YW: computes the LR predicted Y and weights
_fit_structure_space: fits the PCovR model for features > samples
_fit_feature_space: fits the PCovR model for samples > features
fit: fits the PCovR model and automatically chooses
feature space or structure space based on the relative
number of samples and features
transform: computes the projected X
inverse_transform: computes the reconstructed X
predict: computes the projected Y
regression_loss: computes the linear regression loss
projection_loss: computes the projection loss
gram_loss: computes the Gram loss
---References---
1. S. de Jong, H. A. L. Kiers, 'Principal Covariates
Regression: Part I. Theory', Chemometrics and Intelligent
Laboratory Systems 14(1): 155-164, 1992
2. M. Vervolet, H. A. L. Kiers, W. Noortgate, E. Ceulemans,
'PCovR: An R Package for Principal Covariates Regression',
Journal of Statistical Software 65(1):1-14, 2015
"""
def __init__(self, alpha=0.0, n_components=None, regularization=1.0E-12,
regularization_type='scalar', tiny=1.0E-15, rcond=None):
self.alpha = alpha
self.n_components = n_components
self.regularization = regularization
self.regularization_type = regularization_type
self.tiny = tiny
self.rcond = rcond
self.U = None
self.V = None
self.Pxt = None
self.Ptx = None
self.Pty = None
self.P_scale = None
self.Y_norm = None
def _YW(self, X, Y):
"""
Compute the linear regression prediction of Y
---Arguments---
X: centered independent (predictor) variable data
Y: centered dependent (response) variable data
---Returns---
Y_hat: centered linear regression prediction of Y
W: linear regression weights
"""
# Compute predicted Y with LR
lr = LR(regularization=self.regularization,
regularization_type=self.regularization_type, rcond=self.rcond)
lr.fit(X, Y)
Y_hat = lr.predict(X)
W = lr.W
return Y_hat, W
def _fit_structure_space(self, X, Y):
"""
Fit the PCovR model for features > samples
---Arguments---
X: centered independent (predictor) variable data
Y: centered dependent (response) variable data
"""
if len(Y.shape) == 1:
Y = Y.reshape((-1, 1))
# Compute LR approximation of Y
Y_hat, W = self._YW(X, Y)
# Set scaling and norms
self.Y_norm = np.linalg.norm(Y)
self.P_scale = np.linalg.norm(X)
# Compute G matrix
G_pca = np.matmul(X, X.T)/self.P_scale**2
G_lr = np.matmul(Y_hat, Y_hat.T)/self.Y_norm**2
G = self.alpha*G_pca + (1.0 - self.alpha)*G_lr
# Compute eigendecomposition of G
self.U, self.V = sorted_eigh(G, tiny=self.tiny)
# Truncate the projections
self.V = self.V[:, 0:self.n_components]
self.U = self.U[0:self.n_components]
# Compute projection matrix Pxt
Pxt_pca = X.T/self.P_scale**2
Pxt_lr = np.matmul(W, Y_hat.T)/self.Y_norm**2
self.Pxt = self.alpha*Pxt_pca + (1.0 - self.alpha)*Pxt_lr
self.Pxt = np.matmul(self.Pxt, self.V)
self.Pxt = np.matmul(self.Pxt, np.diagflat(1.0/np.sqrt(self.U)))
self.Pxt *= self.P_scale
P = np.matmul(np.diagflat(1.0/np.sqrt(self.U)), self.V.T)
# Compute projection matrix Pty
self.Pty = np.matmul(P, Y)
self.Pty /= self.P_scale
# Compute projection matrix Ptx
self.Ptx = np.matmul(P, X)
self.Ptx /= self.P_scale
def _fit_feature_space(self, X, Y):
"""
Fit the PCovR model for samples > features
---Arguments---
X: centered independent (predictor) variable data
Y: centered dependent (response) variable data
"""
if len(Y.shape) == 1:
Y = Y.reshape((-1, 1))
# Compute LR approximation of Y
Y_hat, W = self._YW(X, Y)
# Compute covariance matrix
C = np.matmul(X.T, X)
# Compute eigendecomposition of the covariance
Uc, Vc = sorted_eigh(C, tiny=self.tiny)
# Set scaling and norms
self.P_scale = np.linalg.norm(X)
self.Y_norm = np.linalg.norm(Y)
# Compute inverse square root of the covariance
C_inv_sqrt = np.matmul(Vc, np.diagflat(1.0/np.sqrt(Uc)))
C_inv_sqrt = np.matmul(C_inv_sqrt, Vc.T)
# Compute square root of the covariance
C_sqrt = np.matmul(Vc, np.diagflat(np.sqrt(Uc)))
C_sqrt = np.matmul(C_sqrt, Vc.T)
# Compute the S matrix
S_pca = C/self.P_scale**2
S_lr = np.matmul(C_sqrt, W)
S_lr = np.matmul(S_lr, S_lr.T)/self.Y_norm**2
S = self.alpha*S_pca + (1.0-self.alpha)*S_lr
# Compute the eigendecomposition of the S matrix
self.U, self.V = sorted_eigh(S, tiny=self.tiny)
# Truncate the projections
self.V = self.V[:, 0:self.n_components]
self.U = self.U[0:self.n_components]
# Compute projection matrix Pxt
self.Pxt = np.matmul(C_inv_sqrt, self.V)
self.Pxt = np.matmul(self.Pxt, np.diagflat(np.sqrt(self.U)))
self.Pxt *= self.P_scale
P = np.matmul(np.diagflat(1.0/np.sqrt(self.U)), self.V.T)
# Compute projection matrix Pty
self.Pty = np.matmul(P, C_inv_sqrt)
self.Pty = np.matmul(self.Pty, X.T)
self.Pty = np.matmul(self.Pty, Y)
self.Pty /= self.P_scale
# Compute projection matrix Ptx
self.Ptx = np.matmul(P, C_sqrt)
self.Ptx /= self.P_scale
def fit(self, X, Y):
"""
Fit the PCovR model and automatically select
feature or structure space based on
the relative number of samples and features
---Arguments---
X: centered independent (predictor) variable data
Y: centered dependent (response) variable data
"""
if X.shape[0] > X.shape[1]:
self._fit_feature_space(X, Y)
else:
self._fit_structure_space(X, Y)
def transform(self, X):
"""
Compute the projection of X
---Arguments---
X: centered data to project
---Returns---
T: centered projection of X
"""
if self.Pxt is None:
print("Error: must fit the PCovR model before transforming")
else:
T = np.matmul(X, self.Pxt)
return T
def inverse_transform(self, X):
"""
Compute the reconstruction of X
---Arguments---
X: centered data to reconstruct
---Returns---
Xr: centered reconstruction of X
"""
if self.Ptx is None:
print("Error: must fit the PCovR model before transforming")
else:
T = self.transform(X)
Xr = np.matmul(T, self.Ptx)
return Xr
def predict(self, X):
"""
Compute the projection (prediction) of Y
---Arguments---
X: centered predictor data for Y
---Returns---
Yp: centered predicted Y values
"""
if self.Pty is None:
print("Error: must fit the PCovR model before transforming")
else:
# Compute predicted Y
T = self.transform(X)
Yp = np.matmul(T, self.Pty)
return Yp
def regression_loss(self, X, Y):
"""
Compute the (linear) regression loss
---Arguments---
X: centered independent (predictor) data
Y: centered dependent (response) data
---Returns---
regression_loss: regression loss
"""
# Compute loss
Yp = self.predict(X)
regression_loss = np.linalg.norm(Y - Yp)**2/self.Y_norm**2
return regression_loss
def projection_loss(self, X):
"""
Compute the projection loss
---Arguments---
X: centered independent (predictor) data
---Returns---
projection_loss: projection loss
"""
# Compute loss
Xr = self.inverse_transform(X)
projection_loss = np.linalg.norm(X - Xr)**2/self.P_scale**2
return projection_loss
def gram_loss(self, X):
"""
Compute the Gram loss
---Arguments---
X: centered independent (predictor) data
---Returns---
gram_loss: gram loss
"""
# Compute loss
T = self.transform(X)
gram_loss = np.linalg.norm(np.matmul(X, X.T) \
- np.matmul(T, T.T))**2 / self.P_scale**4
return gram_loss
class KPCovR(object):
"""
Performs kernel principal covariates regression
---Attributes---
alpha: tuning parameter between KPCA and KRR
n_components: number of KPCA components to retain in the latent
space projection
regularization: regularization parameter
regularization_type: type of regularization.
Choices are 'scalar' (constant regularization),
or 'max_eig' (regularization based on maximum eigenvalue)
tiny: threshold for discarding small eigenvalues
U: eigenvalues of G
V: eigenvectors of G
Pkt: projection matrix from the kernel matrix (K) to
the latent space (T)
Pty: projection matrix from the latent space (T) to
the properties (Y)
Ptk: projection matrix from the latent space (T) to
the kernel matrix (K)
P_scale: scaling for the projection matrices
Y_norm: scaling for the LR term of G
---Methods---
_YW: computes the KRR prediction of Y and weights
fit: fits the KPCovR model
transform: transforms the kernel data into the latent space
inverse_transform: computes the reconstructed
kernel or the original X data (if provided during the fit)
predict: yields predicted Y values based on KRR
regression_loss: compute the kernel ridge regression loss
projection_loss: compute the projection loss
gram_loss: compute the Gram loss
"""
def __init__(self, alpha=0.0, n_components=None, regularization=1.0E-12,
regularization_type='scalar', tiny=1.0E-15, rcond=None):
self.alpha = alpha
self.n_components = n_components
self.regularization = regularization
self.regularization_type = regularization_type
self.tiny = tiny
self.rcond = rcond
self.U = None
self.V = None
self.Pkt = None
self.Pty = None
self.Ptk = None
self.Ptx = None
self.P_scale = None
self.Y_norm = None
def _YW(self, K, Y):
"""
Computes the KRR prediction of Y
---Arguments---
K: centered kernel matrix
Y: centered dependent (response) data
---Returns---
Y_hat: centered KRR prediction of Y
W: regression weights
"""
# Compute predicted Y with KRR
krr = KRR(regularization=self.regularization,
regularization_type=self.regularization_type, rcond=self.rcond)
krr.fit(K, Y)
Y_hat = krr.predict(K)
W = krr.W
return Y_hat, W
def fit(self, K, Y, X=None):
"""
Fits the KPCovR model
---Arguments---
K: centered kernel matrix
Y: centered dependent (response) data
X: centered original independent (predictor) data
"""
if len(Y.shape) == 1:
Y = Y.reshape((-1, 1))
# Compute predicted Y with KRR
Y_hat, W = self._YW(K, Y)
# Set scaling and norms
self.P_scale = np.sqrt(np.trace(K))
self.Y_norm = np.linalg.norm(Y)
# Compute G
G_kpca = K/self.P_scale**2
G_krr = np.matmul(Y_hat, Y_hat.T)/self.Y_norm**2
G = self.alpha*G_kpca + (1.0 - self.alpha)*G_krr
# Compute eigendecomposition of G
self.U, self.V = sorted_eigh(G, tiny=self.tiny)
# Truncate the projections
self.V = self.V[:, 0:self.n_components]
self.U = self.U[0:self.n_components]
# Compute projection matrix Pkt
Pkt_kpca = np.eye(K.shape[0])/self.P_scale**2
Pkt_krr = np.matmul(W, Y_hat.T)/self.Y_norm**2
self.Pkt = self.alpha*Pkt_kpca + (1.0 - self.alpha)*Pkt_krr
self.Pkt = np.matmul(self.Pkt, self.V)
self.Pkt = np.matmul(self.Pkt, np.diagflat(1.0/np.sqrt(self.U)))
self.Pkt *= self.P_scale
P = np.matmul(np.diagflat(1.0/np.sqrt(self.U)), self.V.T)
# Compute projection matrix Pty
self.Pty = np.matmul(P, Y)
self.Pty /= self.P_scale
# Compute projection matrix Ptk
self.Ptk = np.matmul(P, K)
self.Ptk /= self.P_scale
# Compute the projection matrix Ptx
if X is not None:
self.Ptx = np.matmul(P, X)
self.Ptx /= self.P_scale
def transform(self, K):
"""
Transform the data into KPCA space
---Arguments---
K: centered kernel matrix
---Returns---
T: centered KPCA-like projection
"""
if self.Pkt is None:
print("Error: must fit the PCovR model before transforming")
else:
T = np.matmul(K, self.Pkt)
return T
def inverse_transform(self, K, mode='K'):
"""
Compute the reconstruction of the kernel
---Arguments---
K: centered kernel matrix
mode: whether to do a reconstruction of the kernel ('K')
or a reconstruction of X ('X')
---Returns---
R: the centered reconstructed quantity
"""
if mode == 'K':
if self.Ptk is None:
print("Error: must fit the PCovR model before transforming")
return
else:
T = self.transform(K)
R = np.matmul(T, self.Ptk)
elif mode == 'X':
if self.Ptx is None:
print("Error: must provide X data during the PCovR fit "
"before transforming")
return
else:
T = self.transform(K)
R = np.matmul(T, self.Ptx)
else:
print("Error: invalid transformation mode; "
"use 'K' or 'X'")
return
return R
def predict(self, K):
"""
Compute the predicted Y values
---Arguments---
K: centered kernel matrix
---Returns---
Yp: centered predicted Y values
"""
if self.Pty is None:
print("Error: must fit the PCovR model before transforming")
else:
# Compute predicted Y
T = self.transform(K)
Yp = np.matmul(T, self.Pty)
return Yp
def regression_loss(self, K, Y):
"""
Compute the (kernel) regression loss
---Arguments---
K: centered kernel
Y: centered dependent (response) data
---Returns---
regression_loss: regression loss
"""
# Compute loss
Yp = self.predict(K)
regression_loss = np.linalg.norm(Y - Yp)**2/self.Y_norm**2
return regression_loss
def projection_loss(self, K, K_bridge=None, K_ref=None):
"""
Compute the projection loss
---Arguments---
X: centered independent (predictor) data
---Returns---
projection_loss: projection loss
"""
# TODO: special formulation
# Compute loss
T = self.transform(K)
if K_bridge is not None and K_ref is not None:
T_ref = self.transform(K_ref)
else:
projection_loss = np.trace(K - np.matmul(T, self.PTK)) \
/ self.P_scale**2
projection_loss = None
return projection_loss
def gram_loss(self, K):
"""
Compute the Gram loss
---Arguments---
K: centered kernel
---Returns---
gram_loss: Gram loss
"""
# Compute loss
T = self.transform(K)
gram_loss = np.linalg.norm(K - np.matmul(T, T.T))**2 / self.P_scale**4
return gram_loss
class SparseKPCovR(object):
"""
Performs sparsified kernel principal covariates regression
---Attributes---
alpha: tuning parameter
n_components: number of kernel principal components to retain
regularization: regularization parameter
regularization_type: type of regularization.
Choices are 'scalar' (constant regularization),
or 'max_eig' (regularization based on maximum eigenvalue)
tiny: threshold for discarding small eigenvalues
T_mean: auxiliary centering for the kernel matrix
because the centering must be done based on the
feature space, which is approximated
Um: eigenvalues of KMM
Vm: eigenvectors of KMM
Uc: eigenvalues of Phi.T x Phi
Vc: eigenvectors of Phi.T x Phi
U: eigenvalues of S
V: eigenvectors of S
Pkt: projection matrix from the kernel matrix (K) to