| 5 | class PCA(Function): |
| 6 | @staticmethod |
| 7 | def forward(ctx, sv): #sv corresponds to the slices values, it has dimensions nr_positions x val_full_dim |
| 8 | |
| 9 | # http://agnesmustar.com/2017/11/01/principal-component-analysis-pca-implemented-pytorch/ |
| 10 | |
| 11 | |
| 12 | X=sv.detach().cpu()#we switch to cpu of memory issues when doing svd on really big imaes |
| 13 | k=3 |
| 14 | # print("x is ", X.shape) |
| 15 | X_mean = torch.mean(X,0) |
| 16 | # print("x_mean is ", X_mean.shape) |
| 17 | X = X - X_mean.expand_as(X) |
| 18 | |
| 19 | # U,S,V = torch.svd(torch.t(X)) |
| 20 | U,S,V = torch.pca_lowrank( torch.t(X) ) |
| 21 | C = torch.mm(X,U[:,:k]) |
| 22 | # print("C has shape ", C.shape) |
| 23 | # print("C min and max is ", C.min(), " ", C.max() ) |
| 24 | C-=C.min() |
| 25 | C/=C.max() |
| 26 | # print("after normalization C min and max is ", C.min(), " ", C.max() ) |
| 27 | |
| 28 | return C |
| 29 | |
| 30 | |
| 31 | #img supposed to be N,C,H,W |