forked from mikerabat/mrmath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPCA.pas
1493 lines (1263 loc) · 49.1 KB
/
PCA.pas
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 file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2011, Michael R. . All rights reserved.
// ####
// #### Unless required by applicable law or agreed to in writing, software
// #### distributed under the License is distributed on an "AS IS" BASIS,
// #### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// #### See the License for the specific language governing permissions and
// #### limitations under the License.
// ###################################################################
unit PCA;
// ###############################################
// #### PCA related classes
// ###############################################
interface
uses SysUtils, Classes, Matrix, Types, MatrixConst, BaseMathPersistence;
{$MINENUMSIZE 2}
type
TPCASaveData = (pcaEigVals, pcaMeanNormalizedData, pcaTransposedEigVec);
TPCASaveDataSet = set of TPCASaveData;
EPCAException = class(EBaseMatrixException);
TPCAProgress = procedure(Sender : TObject; progress : integer) of Object;
type
TPCAData = record
EigVals : TDoubleMatrix;
EigVecs : TDoubleMatrix;
EigVecsT : TDoubleMatrix;
MeanElem : TDoubleMatrix;
end;
// ##########################################
// #### base PCA algorithm based on Singular Value decomposition
type
TMatrixPCA = class(TBaseMathPersistence)
private
fProgress : TPCAProgress;
procedure OnLineEQProgress(Progress : integer);
function GetEigVals: TDoubleMatrix;
function GetEigVecs: TDoubleMatrix;
function GetMeanElem: TDoubleMatrix;
protected
procedure DefineProps; override;
function PropTypeOfName(const Name: string): TPropType; override;
class function ClassIdentifier : String; override;
function OnLoadObject(const Name : String; obj : TBaseMathPersistence) : boolean; override;
procedure DoProgress(Progress : Integer);
protected
fKeepFlags : TPCASaveDataSet;
fEigVecs : TDoubleMatrix;
fEigVecsT : TDoubleMatrix;
fEigVals : TDoubleMatrix;
fMeanElem : TDoubleMatrix;
fMeanNormExamples : TDoubleMatrix;
function WeightedMean(Examples : TDoubleMatrix; const Weights : Array of double) : TDoubleMatrix;
function EigVecT : TDoubleMatrix;
procedure SortEigValsEigVecs(EigVals : TDoubleMatrix; EigVecs : TDoubleMatrix; L, R : integer);
function GetNumNodes: integer;
procedure Clear; virtual;
public
property EigVals : TDoubleMatrix read GetEigVals;
property EigVecs : TDoubleMatrix read GetEigVecs;
property EigVecsT : TDoubleMatrix read EigVecT;
property Mean : TDoubleMatrix read GetMeanElem;
property NumModes : integer read GetNumNodes;
// calculates the Principal components from the "Examples" matrix. It is assumed that one column
// represents one example in the features space. All eigenvalues (and it's corresponding) eigenvectors
// which values are smaller than CutEps are discarded. If IsRelativeValue is set to true the
// CutEps value is treated as a percentage value between 0 and 1 and represents the threshold used
// to cut of small eigenvalues.
// Input: Examples: matrix of training images, MxN (M values, N examples)
function PCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : boolean) : boolean; virtual;
// Calculates the PCA from a weighted dataset. One whole example is weighted with a constant factor
// (caled temporal weight). The can be found in Danijel Skocaj's PHD:
// "Robust Subspace Approaches to Visual Learning and Recognition", p 58ff.
function TemporalWeightPCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : boolean; const Weights : Array of Double) : boolean; virtual;
function ProjectToFeatureSpace(Example : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure ProjectToFeatureSpace(Example : TDoubleMatrix; ResMatrix : TDoubleMatrix; Column : integer); overload;
function Reconstruct(Features : TDoubleMatrix) : TDoubleMatrix;
property OnProgress : TPCAProgress read fProgress write fProgress;
constructor Create(KeepFlags : TPCASaveDataSet); overload;
constructor Create(const pcaData : TPCAData); overload;
destructor Destroy; override;
end;
TMatrixPCAClass = class of TMatrixPCA;
type
TFastRobustPCAProps = record
NumSubSubSpaces : LongInt; // number of subsubspace which have to be built
SubSpaceSizes : double; // percentage of number of features used for one subspace
SubSpaceExcludeList : Array of TIntegerDynArray; // features which shall be excluded when creating a subspace
SubSpaceCutEPS : double; // same as the cuteps in the normal pca method but for the subspaces
Start : Double; // num Eigenvectors*Start random sampled elements used as initialized pixel set
Stop : Double; // num Eigenvectors*Stop elements used as maximum minimal pixel set
ReductionFactor : double; // used to iterativly reduce the start*nEig set to stop*nEig
end;
type
TFastRobustPCAData = record
Props : TFastRobustPCAProps;
SubItemIndex : Array of TIntegerDynArray;
SubEigVecs : TDoubleMatrixDynArr;
SubEigVecsT : TDoubleMatrixDynArr;
SubMeanElements : TDoubleMatrixDynArr;
PCAData : TPCAData;
end;
// #######################################################################
// #### Fast Robust PCA algorithm:
// Based on paper: Fast Robust PCA,
// Markus Storer, Peter M. Roth, Martin Urschler, and Horst Bischof
type
TFastRobustPCA = class(TMatrixPCA)
protected
fProps : TFastRobustPCAProps;
fSubItemIdx : Array of TIntegerDynArray;
fSubEigVecs : TDoubleMatrixDynArr;
fSubEigVecsT : TDoubleMatrixDynArr;
fSubMeanElem : TDoubleMatrixDynArr;
fIsLearning : boolean;
function GenerateSampleList(len : integer; idx : integer) : TIntegerDynArray;
function SubEigVecT(idx : integer) : TDoubleMatrix;
function ErrorFromSubSpace(idx : integer; Example : TDoubleMatrix) : TDoubleMatrix;
function RobustAlphaTrimmedLinEQSolver(Example : TDoubleMatrix; var Elements : TIntegerDynArray) : TDoubleMatrix;
private
type
TListLoadFlag = (llNone, llSubSpaceExcludeList, llSubItemIdx, llSubEigVecs, llSubEigVecsT, llSubMeanelem);
private
fListFlag : TListLoadFlag;
fIdx : integer;
protected
procedure DefineProps; override;
function PropTypeOfName(const Name : string) : TPropType; override;
class function ClassIdentifier : String; override;
function OnLoadObject(const Name : String; obj : TBaseMathPersistence) : boolean; overload; override;
procedure OnLoadDoubleProperty(const Name : String; const Value : double); override;
procedure OnLoadBeginList(const Name : String; count : integer); override;
procedure OnLoadListIntArr(const Value : TIntegerDynArray); override;
function OnLoadObject(Obj : TBaseMathPersistence) : boolean; overload; override;
procedure OnLoadEndList; override;
protected
procedure Clear; override;
public
procedure SetProperties(const props : TFastRobustPCAProps);
function ProjectToFeatureSpace(Example : TDoubleMatrix) : TDoubleMatrix; override;
function ProjectToFeatureSpaceNonRobust(Example : TDoubleMatrix) : TDoubleMatrix; overload;
procedure ProjectToFeatureSpaceNonRobust(Example : TDoubleMatrix; ResMatrix : TDoubleMatrix; Column : integer); overload;
// Creation of the standard PCA + subspaces as assigned in the properties.
// The procedure first tests the error distribution in many different subsubspaces (gross outlier detection).
// After the features having a small error are used to solve the original subspaces coefficients in a
// robust manner. The robust procedure iteratively solves the overdetermined equation system and removes
// the elements with the highest error in each step.
function PCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : Boolean) : boolean; override;
// Calculates the PCA from a weighted dataset. It uses the same algorithm as PCA but with the weighted
// pca in behind
function TemporalWeightPCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : boolean; const Weights : Array of Double) : boolean; override;
constructor Create(KeepFlags : TPCASaveDataSet); overload;
constructor Create(const PcaData : TFastRobustPCAData); overload;
destructor Destroy; override;
end;
implementation
uses Math, MathUtilFunc;
// ######################################################################
// #### local definitions
// ######################################################################
type
TErrorIdx = record
Error : double;
idx : integer;
end;
PErrorIdx = ^TErrorIdx;
procedure TMatrixPCA.Clear;
begin
FreeAndNil(fEigVecs);
FreeAndNil(fEigVals);
FreeAndNil(fMeanElem);
FreeAndNil(fMeanNormExamples);
FreeAndNil(fEigVecsT);
end;
constructor TMatrixPCA.Create(KeepFlags: TPCASaveDataSet);
begin
inherited Create;
fKeepFlags := KeepFlags;
end;
constructor TMatrixPCA.Create(const pcaData: TPCAData);
begin
inherited Create;
fEigVecs := pcaData.EigVecs;
fEigVecsT := pcaData.EigVecsT;
fEigVals := pcaData.EigVals;
fMeanElem := pcaData.MeanElem;
end;
destructor TMatrixPCA.Destroy;
begin
Clear;
inherited;
end;
procedure TMatrixPCA.DoProgress(Progress: Integer);
begin
if Assigned(fProgress) then
fProgress(self, Progress);
end;
function TMatrixPCA.EigVecT: TDoubleMatrix;
begin
if not Assigned(fEigVecsT) then
fEigVecsT := fEigVecs.Transpose;
Result := fEigVecsT;
end;
function TMatrixPCA.GetEigVals: TDoubleMatrix;
begin
if not Assigned(fEigVals) then
fEigVals := TDoubleMatrix.Create;
Result := fEigVals;
end;
function TMatrixPCA.GetEigVecs: TDoubleMatrix;
begin
if not Assigned(fEigVecs) then
fEigVecs := TDoubleMatrix.Create;
Result := fEigVecs;
end;
function TMatrixPCA.GetMeanElem: TDoubleMatrix;
begin
if not Assigned(fMeanElem) then
fMeanElem := TDoubleMatrix.Create;
Result := fMeanElem;
end;
function TMatrixPCA.GetNumNodes: integer;
begin
Result := 0;
if Assigned(fEigVecs) then
Result := fEigVecs.Width;
end;
procedure TMatrixPCA.SortEigValsEigVecs(EigVals : TDoubleMatrix; EigVecs : TDoubleMatrix; L, R : integer);
var I, J: Integer;
P, T : Double;
y : integer;
begin
// mostly copied from TList implementations
repeat
I := L;
J := R;
P := EigVals[0, (L + R) shr 1];
repeat
while EigVals[0, i] > P do
Inc(I);
while EigVals[0, j] < P do
Dec(J);
if I <= J then
begin
T := EigVals[0, i];
EigVals[0, i] := EigVals[0, j];
EigVals[0, j] := T;
// Exchange Eigenvecs
for y := 0 to EigVecs.Height - 1 do
begin
T := EigVecs[i, y];
EigVecs[i, y] := EigVecs[j, y];
EigVecs[j, y] := T;
end;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then
SortEigValsEigVecs(EigVals, EigVecs, L, J);
L := I;
until I >= R;
end;
// implementation of Daniejl S. weighted batch PCA function:
// Minimization problem here is: e = sum_i=1^M sum_j=1^N w_j * (mean_ij - sum_l=1^k u_il*a_lj)^2
// which means -> minimize the weighted reconstruction error.
//
// Calc mean: mean = (sum_j=1^N w_j)^-1 * sum_j=1^N w_j*x_j
// Rescale input: xs_j = sqrt(w_j)*(x_j - mean)
// if num examples (N) >= num dimensions (M)
// Weighted covariance: C = 1/(sum_j=1^N w_j)*Xs*Xs'
// Perform SVD on C -> Obtain eigenvectors and eigenvalues
// else
// Weighted inner product: C' = 1/(sum_j=1^N w_j)*Xs'*Xs
// Perform SVD on C' -> eigenvectors U' and eigenvalues L'
// Determine principal vectors U: u_i = Xs*u'_i/sqrt(sum_j=1^N w_j*sqrt(l'_i))
// Eigenvalues are L = L'
// end;
// By Mike:
// The function performs the SVD like in the normal pca routine but previously
// scales the mean normalized examples by sqrt(w_i) and the overall matrix by
// sqrt(sum w).
function TMatrixPCA.TemporalWeightPCA(Examples: TDoubleMatrix; CutEps: double;
IsRelativeValue: boolean; const Weights: array of Double): boolean;
var i : integer;
sumEigVals : double;
mv : TDoubleMatrix;
weightSum : double;
begin
DoProgress(0);
weightSum := 0;
for i := 0 to Length(weights) - 1 do
weightSum := weightSum + weights[i];
// calculate weighted mean
fMeanElem := WeightedMean(Examples, Weights);
fMeanNormExamples := TDoubleMatrix.Create;
try
// subtract mean from each column
fMeanNormExamples.Assign(Examples);
fMeanNormExamples.LineEQProgress := {$IFDEF FPC}@{$ENDIF}OnLineEQProgress;
for i := 0 to fMeanNormExamples.Width - 1 do
begin
fMeanNormExamples.SetSubMatrix(i, 0, 1, fMeanNormExamples.Height);
fMeanNormExamples.SubInPlace(fMeanElem);
fMeanNormExamples.ScaleInPlace(sqrt(Weights[i]));
end;
fMeanNormExamples.UseFullMatrix;
fMeanNormExamples.ScaleInPlace(1/sqrt(weightSum));
// calcluated Eigenvectors and eigenvalues using the SVD algorithm
// note: this time the decomposition is performed on the covariance matrix!
mv := nil;
try
if Examples.Height > Examples.Width
then
Result := fMeanNormExamples.SVD(fEigVecs, mv, fEigVals) = srOk
else
begin
fMeanNormExamples.TransposeInPlace;
Result := fMeanNormExamples.SVD(mv, fEigVecs, fEigVals) = srOk;
end;
// calculate real eigenvalues
for i := 0 to fEigVals.Height - 1 do
fEigVals[0, i] := sqr(fEigVals[0, i]);
finally
mv.Free;
end;
if not Result then
begin
Clear;
exit;
end;
if not (pcaMeanNormalizedData in fKeepFlags) then
FreeAndNil(fMeanNormExamples);
// dismiss all eigenvalues smaller the given threshold
if IsRelativeValue then
begin
sumEigVals := 0;
for i := 0 to fEigVals.Height - 1 do
sumEigVals := sumEigVals + fEigVals[0, i];
if (CutEps >= 0) and (CutEps < 1) then
CutEps := sumEigVals*CutEps;
end;
// sort the eigenvectors and eigenvalues
SortEigValsEigVecs(fEigVals, fEigVecs, 0, fEigVals.Height - 1);
// shrink eigenspace according to the given parameter
if not IsRelativeValue or (CutEps < 1) then
begin
sumEigVals := 0;
for i := 0 to fEigVals.Height - 1 do
begin
sumEigVals := sumEigVals + fEigVals[0, i];
if (IsRelativeValue and (sumEigVals >= CutEps)) or
(not IsRelativeValue and (CutEps >= fEigVals[0, i]))
then
begin
if pcaEigVals in fKeepFlags then
begin
// shrink space to 0..i
if IsRelativeValue
then
fEigVals.SetSubMatrix(0, 0, 1, Min(i + 1, fEigVals.Height))
else
fEigVals.SetSubMatrix(0, 0, 1, i);
mv := TDoubleMatrix.Create;
try
mv.Assign(fEigVals, True);
FreeAndNil(fEigVals);
except
FreeAndNil(mv);
raise;
end;
fEigVals := mv;
end
else
FreeAndNil(fEigVals);
if IsRelativeValue
then
fEigVecs.SetSubMatrix(0, 0, Min(i + 1, fEigVecs.Width), fEigVecs.Height)
else
fEigVecs.SetSubMatrix(0, 0, i, fEigVecs.Height);
mv := TDoubleMatrix.Create;
try
mv.Assign(fEigVecs, True);
FreeAndNil(fEigVecs);
fEigVecs := mv;
except
FreeAndNil(mv);
raise;
end;
break;
end;
end;
end;
// create transposed eigenvectors
if pcaTransposedEigVec in fKeepFlags then
EigVecT;
DoProgress(100);
except
Clear;
raise;
end;
end;
function TMatrixPCA.WeightedMean(Examples: TDoubleMatrix; const Weights: array of double): TDoubleMatrix;
var weightSum : double;
x, y : integer;
begin
if Length(Weights) <> Examples.Width then
raise ERangeError.Create('Dimension error: Number of weights does not fit the number of examples' + IntToStr(Length(weights)) + ',' + IntToStr(Examples.Width));
Result := TDoubleMatrix.Create(1, Examples.Height);
try
// assume that one examples is covered by one column
weightSum := 0;
for x := 0 to Examples.Width - 1 do
weightSum := weightSum + weights[x];
for y := 0 to Examples.Height - 1 do
begin
Result[0, y] := 0;
for x := 0 to Examples.Width - 1 do
Result[0, y] := Result[0, y] + Weights[x]*Examples[x, y];
end;
Result.ScaleInPlace(1/weightSum);
except
Result.Free;
raise;
end;
end;
// conversion of ICG's principal component analysis.
// The Principal Components (PC) are the orthonormal eigenvectors of
// cov(A). If A is a mean normalized matrix of random variables,
// cov(A) can be computed as A*A' (without scaling by (n-1)).
//
// If the a matrix A is a set of mean normalized random vectors the
// covariance matrix C can be achieved from the product A*A'. Since for
// each matrix A there exist U, s and V so that A = U*S*V' and
// A' = V*S'*U',
// where [U,S,V] = svd(A), the covariance matrix can be represented as
// C = U*S*S'*U'.
// So it is clear that C and A have a intentical set of orthonormal
// eigenvectors and that the eigenvalues of C are the squared
// eigenvalues of A.
function TMatrixPCA.PCA(Examples: TDoubleMatrix; CutEps: double;
IsRelativeValue: boolean): boolean;
var i : integer;
mv : TDoubleMatrix;
sumEigVals : double;
scale : double;
begin
DoProgress(0);
// free previous pca calculations
Clear;
// calculate mean
fMeanElem := Examples.Mean(True);
fMeanNormExamples := TDoubleMatrix.Create;
try
// subtract mean from each column
fMeanNormExamples.Assign(Examples, True);
fMeanNormExamples.LineEQProgress := {$IFDEF FPC}@{$ENDIF}OnLineEQProgress;
for i := 0 to fMeanNormExamples.Width - 1 do
begin
fMeanNormExamples.SetSubMatrix(i, 0, 1, fMeanNormExamples.Height);
fMeanNormExamples.SubInPlace(fMeanElem);
end;
fMeanNormExamples.UseFullMatrix;
// calcluated Eigenvectors and eigenvalues using the SVD algorithm
mv := nil;
try
if Examples.Height > Examples.Width
then
Result := fMeanNormExamples.SVD(fEigVecs, mv, fEigVals, True) = srOk
else
begin
fMeanNormExamples.TransposeInPlace;
Result := fMeanNormExamples.SVD(mv, fEigVecs, fEigVals, True) = srOk;
end;
// this scaling is apart from the original Matlab implementation but
// I think it's necessary since the Covariance matrix is normaly: 1/N X*X' not
// only X*X' -> thus a scaling of 1/sqrt(N) should by applied to the mean normalized examples
// calculate real eigenvalues (the scale comes from the matlab function princomp function
scale := 1/sqrt(fMeanNormExamples.Width);
for i := 0 to fEigVals.Height - 1 do
fEigVals[0, i] := sqr(fEigVals[0, i]*scale);
finally
mv.Free;
end;
if not Result then
begin
Clear;
exit;
end;
if not (pcaMeanNormalizedData in fKeepFlags) then
FreeAndNil(fMeanNormExamples);
// dismiss all eigenvalues smaller the given threshold
if IsRelativeValue then
begin
sumEigVals := 0;
for i := 0 to fEigVals.Height - 1 do
sumEigVals := sumEigVals + fEigVals[0, i];
if (CutEps >= 0) and (CutEps < 1)
then
CutEps := sumEigVals*CutEps
else
CutEps := sumEigVals;
end;
// sort the eigenvectors and eigenvalues
SortEigValsEigVecs(fEigVals, fEigVecs, 0, fEigVals.Height - 1);
// shrink eigenspace according to the given parameter
// at least one eigenvector shall be kept
sumEigVals := fEigVals[0, 0];
for i := 1 to fEigVals.Height - 1 do
begin
sumEigVals := sumEigVals + fEigVals[0, i];
if CutEps < sumEigVals then
begin
if pcaEigVals in fKeepFlags then
begin
// shrink space to 0..i
fEigVals.SetSubMatrix(0, 0, 1, i);
mv := TDoubleMatrix.Create;
try
mv.Assign(fEigVals, True);
FreeAndNil(fEigVals);
except
FreeAndNil(mv);
raise;
end;
fEigVals := mv;
end
else
FreeAndNil(fEigVals);
fEigVecs.SetSubMatrix(0, 0, i, fEigVecs.Height);
mv := TDoubleMatrix.Create;
try
mv.Assign(fEigVecs, True);
FreeAndNil(fEigVecs);
fEigVecs := mv;
except
FreeAndNil(mv);
raise;
end;
break;
end;
end;
DoProgress(100);
// create transposed eigenvectors
if pcaTransposedEigVec in fKeepFlags then
EigVecT;
except
Clear;
raise;
end;
end;
procedure TMatrixPCA.ProjectToFeatureSpace(Example, ResMatrix: TDoubleMatrix; Column : integer);
var tmp : TDoubleMatrix;
begin
if not Assigned(fEigVecs) then
raise EPCAException.Create('PCA object not initialized');
if (Example.Width <> 1) or (ResMatrix.Height <> fEigVecs.Width) then
raise EPCAException.Create('Resulting dimension of projection matrix is wrong');
tmp := ProjectToFeatureSpace(Example);
try
ResMatrix.SetColumn(column, tmp);
finally
tmp.Free;
end;
end;
function TMatrixPCA.ProjectToFeatureSpace(
Example: TDoubleMatrix): TDoubleMatrix;
var meanMtx : TDoubleMatrix;
begin
Result := nil;
if not Assigned(fEigVecs) then
raise EPCAException.Create('PCA object not initialized');
meanMtx := TDoubleMatrix.Create;
try
meanMtx.Assign(Example, True);
// check dimensions -> transpose if necessary
if (meanMtx.Width = fEigVecs.Height) and (meanMtx.Height = 1) then
meanMtx.TransposeInPlace;
if (meanMtx.Width <> fMeanElem.Width) or (meanMtx.Height <> fMeanElem.Height) then
raise EPCAException.Create('Example dimension do not match');
// ####################################################
// #### features = EigVec'*(Example - meanElem)
meanMtx.SubInPlace(fMeanElem);
Result := EigVecT.Mult(meanMtx);
finally
meanMtx.Free;
end;
end;
function TMatrixPCA.Reconstruct(Features: TDoubleMatrix): TDoubleMatrix;
begin
if not Assigned(fEigVecs) then
raise EPCAException.Create('PCA object not initialized');
if (Features.Width <> 1) or (Features.Height <> fEigVecs.Width) then
raise EPCAException.Create('Dimensions of PCA feature space differs from given example');
// Example := (EigVec*Features) + MeanElem
Result := fEigVecs.Mult(Features);
Result.AddInplace(fMeanElem);
end;
{ TFastRobustPCA }
constructor TFastRobustPCA.Create(KeepFlags: TPCASaveDataSet);
begin
inherited Create(KeepFlags);
// set standard properties
fProps.NumSubSubSpaces := 100;
fProps.SubSpaceSizes := 0.01; // use 1 percent per subspace
fProps.SubSpaceExcludeList := nil; // just use random sampling
fProps.Start := 50; // 50*NumEigenVecs to start the robust method
fProps.Stop := 20; // stop at 20*NumEigenVecs
fProps.ReductionFactor := 0.75; // Reduce the point set by this factor
fProps.SubSpaceCutEPS := 1; // per default use 90% of the energy in subspaces
end;
procedure TFastRobustPCA.Clear;
var i : integer;
begin
inherited;
if not fIsLearning then
begin
for i := 0 to Length(fSubEigVecs) - 1 do
begin
fSubEigVecs[i].Free;
fSubMeanElem[i].Free;
fSubEigVecsT[i].Free;
end;
fSubEigVecs := nil;
fSubMeanElem := nil;
fSubEigVecsT := nil;
end;
end;
constructor TFastRobustPCA.Create(const PCaData: TFastRobustPCAData);
var i : Integer;
begin
inherited Create(PCAData.PCAData);
fProps := PCaData.Props;
SetLength(fSubItemIdx, Length(PCaData.SubItemIndex));
for i := 0 to Length(fSubItemIdx) - 1 do
fSubItemIdx[i] := PCAData.SubItemIndex[i];
fSubEigVecs := PCaData.SubEigVecs;
fSubEigVecsT := PCAData.SubEigVecsT;
fSubMeanElem := PCAData.SubMeanElements;
end;
class function TFastRobustPCA.ClassIdentifier: String;
begin
Result := 'FRPCA';
end;
procedure TFastRobustPCA.DefineProps;
var i : integer;
begin
// write the base properties:
inherited;
// #######################################################
// #### Write out properties
AddIntProperty('NumSubSubSpaces', fProps.NumSubSubSpaces);
AddDoubleProperty('SubspaceSizes', fProps.SubSpaceSizes);
if Length(fProps.SubSpaceExcludeList) > 0 then
begin
BeginList('SubSpaceExclList', Length(fProps.SubSpaceExcludeList));
for i := 0 to Length(fProps.SubSpaceExcludeList) - 1 do
AddListIntArr(fProps.SubSpaceExcludeList[i]);
EndList;
end;
AddDoubleProperty('SubSpaceCutEPS', fProps.SubSpaceCutEPS);
AddDoubleProperty('Start', fProps.Start);
AddDoubleProperty('Stop', fProps.Stop);
AddDoubleProperty('ReductFact', fProps.ReductionFactor);
// #######################################################
// #### Write out objects
if Length(fSubItemIdx) > 0 then
begin
BeginList('SubItemIdx', Length(fSubItemIdx));
for i := 0 to Length(fSubItemIdx) - 1 do
AddListIntArr(fSubItemIdx[i]);
EndList;
end;
if Length(fSubEigVecs) > 0 then
begin
BeginList('SubEigVecs', Length(fSubEigVecs));
for i := 0 to Length(fSubEigVecs) - 1 do
AddObject(fSubEigVecs[i]);
EndList;
end;
if Length(fSubEigVecsT) > 0 then
begin
BeginList('SubEigVecsT', Length(fSubEigVecsT));
for i := 0 to Length(fSubEigVecsT) - 1 do
AddObject(fSubEigVecsT[i]);
EndList;
end;
if Length(fSubMeanElem) > 0 then
begin
BeginList('SubMeanElem', Length(fSubMeanElem));
for i := 0 to Length(fSubMeanElem) - 1 do
AddObject(fSubMeanElem[i]);
EndList;
end;
end;
function TFastRobustPCA.PropTypeOfName(const Name: string): TPropType;
begin
if (CompareText(Name, 'SubMeanElem') = 0) or (CompareText(Name, 'SubEigVecsT') = 0) or
(CompareText(Name, 'SubEigVecs') = 0)
then
Result := ptObject
else if (CompareText(Name, 'SubItemIdx') = 0) or (CompareText(Name, 'NumSubSubSpaces') = 0) or
(CompareText(Name, 'SubSpaceExclList') = 0)
then
Result := ptInteger
else if (CompareText(Name, 'SubspaceSizes') = 0) or (CompareText(Name, 'SubSpaceCutEPS') = 0) or
(CompareText(Name, 'Start') = 0) or (CompareText(Name, 'Stop') = 0) or
(CompareText(Name, 'ReductFact') = 0)
then
Result := ptDouble
else
Result := inherited PropTypeOfName(Name);
end;
procedure TFastRobustPCA.OnLoadBeginList(const Name: String;
count: integer);
begin
fIdx := 0;
if CompareText(Name, 'SubSpaceExclList') = 0 then
begin
SetLength(fProps.SubSpaceExcludeList, Count);
fListFlag := llSubSpaceExcludeList;
end
else if CompareText(Name, 'SubItemIdx') = 0 then
begin
SetLength(fSubItemIdx, Count);
fListFlag := llSubItemIdx;
end
else if CompareText(Name, 'SubEigVecs') = 0 then
begin
SetLength(fSubEigVecs, Count);
fListFlag := llSubEigVecs;
end
else if CompareText(Name, 'SubEigVecsT') = 0 then
begin
SetLength(fSubEigVecsT, Count);
fListFlag := llSubEigVecsT;
end
else if CompareText(Name, 'SubMeanElem') = 0 then
begin
SetLength(fSubMeanElem, Count);
fListFlag := llSubMeanelem;
end;
end;
procedure TFastRobustPCA.OnLoadEndList;
begin
fListFlag := llNone;
end;
procedure TFastRobustPCA.OnLoadListIntArr(const Value: TIntegerDynArray);
begin
case fListFlag of
llSubSpaceExcludeList: fProps.SubSpaceExcludeList[fIdx] := Value;
llSubItemIdx: fSubItemIdx[fIdx] := Value;
end;
inc(fIdx);
end;
function TFastRobustPCA.OnLoadObject(Obj: TBaseMathPersistence): boolean;
begin
Result := True;
case fListFlag of
llSubEigVecs : fSubEigVecs[fIdx] := Obj as TDoubleMatrix;
llSubEigVecsT : fSubEigVecsT[fIdx] := Obj as TDoubleMatrix;
llSubMeanelem : fSubMeanElem[fIdx] := Obj as TDoubleMatrix;
else
Result := inherited OnLoadObject(Obj);
end;
inc(fIdx);
end;
function TFastRobustPCA.OnLoadObject(const Name: String;
obj: TBaseMathPersistence): boolean;
begin
Result := inherited OnLoadObject(Name, obj);
end;
procedure TFastRobustPCA.OnLoadDoubleProperty(const Name: String;
const Value: double);
begin
if CompareText(Name, 'SubspaceSizes') = 0
then
fProps.SubSpaceSizes := value
else if CompareText(Name, 'SubSpaceCutEPS') = 0
then
fProps.SubSpaceCutEPS := Value
else if CompareText(Name, 'Start') = 0
then
fProps.Start := Value
else if CompareText(Name, 'Stop') = 0
then
fProps.Stop := Value
else if CompareText(Name, 'ReductFact') = 0
then
fProps.ReductionFactor := Value
else
inherited;
end;
destructor TFastRobustPCA.Destroy;
begin
Clear;
inherited;
end;
function TFastRobustPCA.ErrorFromSubSpace(idx: integer;
Example: TDoubleMatrix): TDoubleMatrix;
var x : TDoubleMatrix;
a : TDoubleMatrix;
xhat : TDoubleMatrix;
i : integer;
begin
xhat := nil;
a := nil;
x := TDoubleMatrix.Create(1, fSubMeanElem[idx].Height);
try
// project to feature space
for i := 0 to x.Height - 1 do
x[0, i] := Example[0, fSubItemIdx[idx][i]];
x.SubInPlace(fSubMeanElem[idx]);
a := SubEigVecT(idx).Mult(x);
// project back
xhat := fSubEigVecs[idx].Mult(a);
// calculate absolute error
Result := TDoubleMatrix.Create(1, xhat.Height);
for i := 0 to Result.Height - 1 do
Result[0, i] := abs(x[0, i] - xhat[0, i]);
finally
x.Free;
a.Free;
xhat.Free;
end;
end;
function TFastRobustPCA.GenerateSampleList(len : integer;
idx: integer): TIntegerDynArray;
var SetList : array of Boolean;
i : integer;
rndIdx : integer;
rndIdx2 : integer;
swap : integer;
numExcluded : integer;
resLen : integer;
begin
SetLength(SetList, len);
numExcluded := 0;
if Length(fProps.SubSpaceExcludeList) > idx then
begin
for i := 0 to Length(fProps.SubSpaceExcludeList[idx]) - 1 do
begin
SetList[i] := True;
inc(numExcluded);
end;
end;
if fProps.SubSpaceSizes > 0.3 then
begin
// from this point it's better to do switching
SetLength(Result, len - numExcluded);