forked from andrewssobral/nway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ncrossdecompn.m
552 lines (476 loc) · 16.3 KB
/
ncrossdecompn.m
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
function XvalResult = ncrossdecomp(Method,X,FacMin,FacMax,Segments,Cent,Show);
%NCROSSDECOMP crossvalidation of PARAFAC/Tucker/PCA
%
% See also:
% 'ncrossreg'
%
% This file performs cross-validation of decomposition models
% PARAFAC, PCA, and Tucker. The cross-validation is performed
% such that part of the data are set to missing, the model is
% fitted to the remaining data, and the residuals between fitted
% and true left-out elements is calculated. This is performed
% 'Segments' times such that all elements are left out once.
% The segments are chosen by taking every 'Segments' element of
% X(:), i.e. from the vectorized array. If X is of size 5 x 7,
% and three segemnts are chosen ('Segments' = 3), then in the
% first of three models, the model is fitted to the matrix
%
% |x 0 0 x 0 0 x|
% |0 x 0 0 x 0 0|
% |0 0 x 0 0 x 0|
% |x 0 0 x 0 0 x|
% |0 x 0 0 x 0 0|
%
% where x's indicate missing elements. After fitting the residuals
% in the locations of missing values are calculated. After fitting
% all three models, all residuals have been calculated.
%
% Note that the number of segments must be chosen such that no columns
% or rows contain only missing elements (the algorithm will check this).
% Using 'Segments' = 7, 9, or 13 will usually achieve that.
%
% I/O
% XvalResult = ncrossdecomp(Method,X,FacMin,FacMax,Segments,Cent,Show);
%
% INPUT
% Method : 'parafac', 'tucker', 'pca', or 'nipals'
% For Tucker only Tucker3 models with equal
% number of components is currently available.
% For PCA the least squares model is calculated.
% Thus, offsets and parameters are calculated in
% a least squares sense unlike the method NIPALS,
% which calculates the PCA model using an ad hoc
% approach for handling missing data (as in
% standard chemometric software).
% X : Multi-way array of data
% FacMin : Lowest number of factors to use
% FacMax : Highest number of factors (note that for Tucker only models
% with the same number of components in each mode are
% calculated currently
% Segments : The number of segments to use. Try many!
% Cent : If set of one, the data are centered across samples,
% i.e. ordinary centering. Note, however, that the centering
% is not performed in a least squares sense but as preprocessing.
% This is not optimal because the data have missing data because
% of the way the elements are left out. This can give
% significantly lower fit than reasonable if you have few samples
% or use few segments. Alternatively, you can center the data
% beforehand and perform cross-validation on the centered data
% Show : If set to 0, no plot is given
%
% OUTPUT
% Structure XvalResult holding:
% Fit: The fitted percentage of variation explaind (as a
% function of component number)
% Xval: The cross-validated percentage of variation explaind
% (as a function of component number)
% FittedModel: The fitted model (as a function of component number)
% XvalModel: The cross-validated model (as a function of component number)
% $ Version 1.0301 $ Date 28. June 1999 $ Not compiled $
% $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $
% Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson
% Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected]
%
% uses NANSUM,
%GT
Perm = [1:ndims(X)];
DimX = size(X);
ord = ndims(X);
delta = zeros(1,ndims(X));
for i = 1:ndims(X)
c(i) = isempty(intersect(factor(DimX(i)),factor(Segments)));
index{i} = 1:DimX(i);
end
delta = zeros(1,ndims(X));
for i = 1:ndims(X)
c(i) = isempty(intersect(factor(DimX(i)),factor(Segments)));
index{i} = 1:DimX(i);
end
P = find(~c);
if sum(c) < length(DimX) - 1
for i = 1:sum(~c)
while ~c(P(i)) & delta(P(i)) < (abs(DimX(P(i))- Segments) - 1)
if ~rem(DimX(P(i)),2) & ~rem(Segments,2) & delta(P(i)) > 0
Off = 2;
else
Off = 1;
end
delta(P(i)) = delta(P(i)) + Off;
c(P(i)) = isempty(intersect(factor(DimX(P(i)) + delta(P(i))),factor(Segments)));
end
if sum(c) == length(DimX) - 1
return
end
end
if sum(~c) > 1
error('The chosen segmentation leads to tubes of only missing values')
end
end
if sum(c) == length(DimX) - 1
[c,Perm] = sort(~c);
end
[nil,PermI] = sort(Perm);
X = reshape(X,DimX(1),prod(DimX(2:end)));
%GT end
[I,J] = size(X);
if exist('Show')~=1
Show = 1;
end
if lower(Method(1:3)=='tuc')
if length(FacMin)==1
FacMin = ones(1,ord)*FacMin;
elseif length(FacMin)~=ord
error('Error in FacMin: When fitting Tucker models, the number of factors should be given for each mode')
end
if length(FacMax)==1
FacMax = ones(1,ord)*FacMax;
elseif length(FacMax)~=ord
error('Error in FacMax: When fitting Tucker models, the number of factors should be given for each mode')
end
end
%RB
% Check if the selected segmentation works (does not produce rows/columns of only missing)
%out = ones(I,J);
%out(1:Segments:end)=NaN;
%out(find(isnan(X))) = NaN;
%if any(sum(isnan(out))==I)
% error(' The chosen segmentation leads to columns of only missing elements')
%elseif any(sum(isnan(out'))==J)
% error(' The chosen segmentation leads to rows of only missing elements')
%end
%RB end
if lower(Method(1:3)~='tuc')
XvalResult.Fit = zeros(FacMax,2)*NaN;
XvalResult.Xval = zeros(FacMax,2)*NaN;
for f = 1:FacMin-1
XvalResult.XvalModel{f} = 'Not fitted';
XvalResult.FittedModel{f} = 'Not fitted';
end
for f = FacMin:FacMax
% Fitted model
disp([' Total model - Comp. ',num2str(f),'/',num2str(FacMax)])
[M,Mean,Param] = decomp(Method,X,DimX,f,1,Segments,Cent,I,J);
Model = M + ones(I,1)*Mean';
id = find(~isnan(X));
OffsetCorrectedData = X - ones(I,1)*Mean';
XvalResult.Fit(f,:) = [100*(1 - sum( (X(id) - Model(id)).^2)/sum(OffsetCorrectedData(id).^2)) f];
XvalResult.FittedModel{f} = Model;
% Xvalidated Model of data
ModelXval = zeros(I,J)*NaN;
for s = 1:Segments
disp([' Segment ',num2str(s),'/',num2str(Segments),' - Comp. ',num2str(f),'/',num2str(FacMax)])
%GT
Xnow = permute(zeros(DimX),Perm);
dimsadd = size(Xnow);
for j = 1:length(DimX)
dimsadd(j) = delta(Perm(j));
Xnow = cat(j,Xnow,zeros(dimsadd));
index2{j} = 1:DimX(Perm(j));
dimsadd = size(Xnow);
end
Xnow(s:Segments:end) = NaN;
Xnow = reshape(permute(Xnow(index2{:}),PermI),DimX(1),prod(DimX(2:end)));
Pos = isnan(Xnow);
[M,Mean] = decomp(Method,Xnow + X,DimX,f,s,Segments,Cent,I,J,Param);
model = M + ones(I,1)*Mean';
ModelXval(Pos) = model(Pos);
%GT end
end
XvalResult.Xval(f,:) = [100*(1 - sum( (X(id) - ModelXval(id)).^2)/sum(OffsetCorrectedData(id).^2)) f];
XvalResult.XvalModel{f} = ModelXval;
end
else % Do Tucker model
%GT
if length(FacMin) ~= ord
FacMin = ones(1,ord)*min(FacMin);
end
if length(FacMax) ~= ord
FacMax = ones(1,ord)*min(FacMax);
end
for i=1:length(FacMin)
ind{i} = [FacMin(i):FacMax(i)]';
ind2{i} = ones(length(ind{i}),1);
end
NCombs = cellfun('length',ind);
for i=1:length(FacMin)
o = [1:i-1,i+1:length(FacMin)];
t = ipermute(ind{i}(:,ind2{o}),[i,o]);
possibleCombs(1:prod(NCombs),i) = t(:);
end
FeasCombs = sort(possibleCombs');
f2 = prod(FeasCombs(1:size(FeasCombs,1)-1,:))<FeasCombs(end,:);
possibleCombs(f2,:) = [];
possibleCombs(:,end+1) = find(~f2(:));
%GTend
%RB
% Find all
%PossibleNumber = [min(FacMin):max(FacMax)]'*ones(1,ord);
%possibleCombs = unique(nchoosek(PossibleNumber(:),ord),'rows');
%remove useless
%f2 = [];
%for f1 = 1:size(possibleCombs,1)
% if (prod(possibleCombs(f1,:))/max(possibleCombs(f1,:)))<max(possibleCombs(f1,:)) % Check that the largest mode is larger than the product of the other
% f2 = [f2;f1];
% elseif any(possibleCombs(f1,:)>FacMax) % Chk the model is desired,
% f2 = [f2;f1];
% end
%end
%possibleCombs(f2,:)=[];
%[f1,f2]=sort(sum(possibleCombs'));
%possibleCombs = [possibleCombs(f2,:) f1'];
%RBend
XvalResult.Fit = zeros(size(possibleCombs,1),ord+1)*NaN;
XvalResult.Xval = zeros(size(possibleCombs,1),ord+1)*NaN;
for f = 1:size(possibleCombs,1)
XvalResult.XvalModel{f} = 'Not fitted';
XvalResult.FittedModel{f} = 'Not fitted';
end
for f1 = 1:size(possibleCombs,1)
% Fitted model
%GT
disp([' Total model - Comp. ',num2str(possibleCombs(f1,:)),'/',num2str(FacMax)])
[M,Mean,Param] = decomp(Method,X,DimX,possibleCombs(f1,:),1,Segments,Cent,I,J);
%GTend
%RB
%disp([' Total model - Comp. ',num2str(possibleCombs(f1,1:end-1)),'/',num2str(FacMax)])
%[M,Mean,Param] = decomp(Method,X,DimX,possibleCombs(f1,1:end-1),1,Segments,Cent,I,J);
%RBend
Model = M + ones(I,1)*Mean';
id = find(~isnan(X));
OffsetCorrectedData = X - ones(I,1)*Mean';
XvalResult.Fit(f1,:) = [100*(1 - sum( (X(id) - Model(id)).^2)/sum(OffsetCorrectedData(id).^2)) possibleCombs(f1,1:end-1)];
XvalResult.FittedModel{f1} = Model;
% Xvalidated Model of data
ModelXval = zeros(I,J)*NaN;
for s = 1:Segments
disp([' Segment ',num2str(s),'/',num2str(Segments),' - Comp. ',num2str(possibleCombs(f1,1:end-1)),'/',num2str(FacMax)])
%GT
Xnow = permute(zeros(DimX),Perm);
dimsadd = DimX;
for j = 1:length(DimX)
dimsadd(j) = delta(j);
Xnow = cat(j,Xnow,zeros(dimsadd));
index2{j} = 1:DimX(j);
dimsadd(j) = dimsadd(j) + DimX(j);
end
Xnow(s:Segments:end) = NaN;
Xnow = reshape(permute(Xnow(index2{:}),PermI),DimX(1),prod(DimX(2:end)));
Pos = isnan(Xnow);
[M,Mean] = decomp(Method,Xnow + X,DimX,possibleCombs(f1,1:end-1),s,Segments,Cent,I,J,Param);
model = M + ones(I,1)*Mean';
ModelXval(Pos) = model(Pos);
%GT end
end
XvalResult.Xval(f1,:) = [100*(1 - sum( (X(id) - ModelXval(id)).^2)/sum(OffsetCorrectedData(id).^2)) possibleCombs(f1,1:end-1)];
XvalResult.XvalModel{f1} = ModelXval;
end
end
if Show&FacMin-FacMax~=0
if Method(1:3) == 'pca'
Nam = 'PCA';
elseif Method(1:3) == 'tuc'
Nam = 'Tucker';
elseif Method(1:3) == 'par'
Nam = 'PARAFAC';
elseif Method(1:3) == 'nip'
Nam = 'NIPALS';
end
figure
save jjj
if lower(Method(1:3))~='tuc'
bar(FacMin:FacMax,[XvalResult.Fit(FacMin:FacMax,1) XvalResult.Xval(FacMin:FacMax,1)],.76,'grouped')
else
% extract the ones with lowest Xval fit (for each # total comp) for plotting
fx = [];
f5 =[];
for f1 = 1:max(possibleCombs(:,end))
f2 = find(possibleCombs(:,end)==f1);
if length(f2)
[f3,f4] = max(XvalResult.Xval(f2));
f5 = [f5,f2(f4)];
end
end
fx = [possibleCombs(f5,end) XvalResult.Fit(f5,1) XvalResult.Xval(f5,1)];
bar(fx(:,1),fx(:,2:3),.76,'grouped')
for f1 = 1:size(fx,1)
f6=text(fx(f1,1),95,['[',num2str(possibleCombs(f5(f1),1:end-1)),']']);
set(f6,'Rotation',270)
end
end
g=get(gca,'YLim');
set(gca,'YLim',[max(-20,g(1)) 100])
legend('Fitted','Xvalidated',0)
titl = ['Xvalidation results (',Nam,')'];
if Cent
titl = [titl ,' - centering'];
else
titl = [titl ,' - no centering'];
end
title(titl,'FontWeight','Bold')
xlabel('Total number of components')
ylabel('Percent variance explained')
end
function [M,Mean,parameters] = decomp(Method,X,DimX,f,s,Segments,Cent,I,J,parameters);
Conv = 0;
it = 0;
maxit = 500;
% Initialize
if Cent
Mean = nanmean(X)';
else
Mean = zeros(J,1);
end
if lower(Method(1:3)) == 'par'
Xc = reshape(X- ones(I,1)*Mean',DimX);
if exist('parameters')==1
fact = parafac(Xc,f,[1e-5 10 0 0 NaN maxit],[],parameters.fact);
else
fact = parafac(Xc,f,[1e-5 10 0 0 NaN maxit]);
end
M = reshape(nmodel(fact),DimX(1),prod(DimX(2:end)));
parameters.fact=fact;
elseif lower(Method(1:3)) == 'tuc'
Xc = reshape(X- ones(I,1)*Mean',DimX);
if exist('parameters')==1
[fact,G] = tucker(Xc,f,[1e-2 0 0 0 NaN maxit],[],[],parameters.fact,parameters.G);
else
[fact,G] = tucker(Xc,f,[1e-2 0 0 0 NaN maxit]);
end
parameters.fact=fact;
parameters.G=G;
M = reshape(nmodel(fact,G),DimX(1),prod(DimX(2:end))) ;
elseif lower(Method) == 'pca'|lower(Method) == 'nip'
Xc = reshape(X- ones(I,1)*Mean',DimX(1),prod(DimX(2:end)));
[t,p] = pcanipals(X- ones(I,1)*Mean',f,0);
parameters.t=t;
parameters.p=p;
M = t*p';
else
error(' Name of method not recognized')
end
Fit = X - M - ones(I,1)*Mean';
Fit = sum(Fit(find(~isnan(X))).^2);
% Iterate
while ~Conv
it = it+1;
FitOld = Fit;
% Fit multilinear part
Xcent = X - ones(I,1)*Mean';
if Method(1:3) == 'par'
fact = parafac(reshape(Xcent,DimX),f,[1e-2 0 0 0 NaN maxit],[],fact);
M = reshape(nmodel(fact),DimX(1),prod(DimX(2:end)));
elseif Method(1:3) == 'tuc'
[fact,G] = tucker(reshape(Xcent,DimX),f,[1e-2 0 0 0 NaN maxit],[0 0 0],zeros(size(G)),fact,G);
M = reshape(nmodel(fact,G),DimX(1),prod(DimX(2:end)));
elseif Method == 'pca'
[t,p] = pcals(Xcent,f,0,t,p,0);
M = t*p';
elseif Method == 'nip'
[t,p] = pcanipals(Xcent,f,0);
M = t*p';
end
% Find offsets
if Cent
x = X;
mm=M+ones(I,1)*Mean';
x(find(isnan(X)))=mm(find(isnan(X)));
Mean = mean(x)';
end
%Find fit
Fit = X - M - ones(I,1)*Mean';
Fit = sum(Fit(find(~isnan(X))).^2);
if abs(Fit-FitOld)/FitOld<1e-8 | it > 1500
Conv = 1;
end
end
disp([' Fit ',num2str(Fit),' using ',num2str(it),' it.'])
function [t,p] = pcals(X,F,cent,t,p,show);
% LEAST SQUARES PCA WITH MISSING ELEMENTS
% 20-6-1999
%
% Calculates a least squares PCA model. Missing elements
% are denoted NaN. The solution is NOT nested, so one has
% to calculate a new model for each number of components.
ShowMeFitEvery = 20;
MaxIterations = 5;
[I,J]=size(X);
Xorig = X;
Miss = find(isnan(X));
NotMiss = find(~isnan(X));
m = t*p';
X(Miss) = m(Miss);
ssX = sum(X(NotMiss).^2);
Fit = 3;
OldFit = 6;
it = 0;
while abs(Fit-OldFit)/OldFit>1e-3 & it < MaxIterations;
it = it +1;
OldFit = Fit;
[t,s,p] = svds(X,F);
t = t*s;
Model = t*p';
X(Miss) = Model(Miss);
Fit = sum(sum( (Xorig(NotMiss) - Model(NotMiss)).^2));
if ~rem(it,ShowMeFitEvery)&show
disp([' Fit after ',num2str(it),' it. :',num2str(RelFit),'%'])
end
end
function [t,p,Mean] = pcanipals(X,F,cent);
% NIPALS-PCA WITH MISSING ELEMENTS
% cent: One if centering is to be included, else zero
[I,J]=size(X);
rand('state',sum(100*clock))
Xorig = X;
Miss = isnan(X);
NotMiss = ~isnan(X);
ssX = sum(X(find(NotMiss)).^2);
Mean = zeros(1,J);
if cent
Mean = nanmean(X);
end
X = X - ones(I,1)*Mean;
t=[];
p=[];
for f=1:F
Fit = 3;
OldFit = 6;
it = 0;
T = rand(I,1);
P = rand(J,1);
Fit = 2;
FitOld = 3;
while abs(Fit-FitOld)/FitOld>1e-7 & it < 100;
FitOld = Fit;
it = it +1;
for j = 1:J
id=find(NotMiss(:,j));
if length(id)==0
id,end
P(j) = T(id)'*X(id,j)/(T(id)'*T(id));
end
P = P/norm(P);
for i = 1:I
id=find(NotMiss(i,:));
T(i) = P(id)'*X(i,id)'/(P(id)'*P(id));
end
Fit = X-T*P';
Fit = sum(Fit(find(NotMiss)).^2);
end
t = [t T];
p = [p P];
X = X - T*P';
end
function Xc = nanmean(X)
if isempty(X)
Xc = NaN;
return
end
i = isnan(X);
j = find(i);
i = sum(i);
X(j) = 0;
Num = size(X,1)-i;
Xc = sum(X);
i = find(Num);
Xc(i) = Xc(i)./Num(i);
Xc(find(~Num))=NaN;