forked from mikerabat/mrmath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIncrementalPCA.pas
1273 lines (1081 loc) · 42 KB
/
IncrementalPCA.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 IncrementalPCA;
// ###############################################
// #### Incremental version of the PCA algorithm
// ###############################################
interface
uses SysUtils, PCA, Matrix, BaseMathPersistence, Types;
type
TIncrPCAData = record
Props : TPCAData;
Weights : TDoubleDynArray;
NumEigenVecs : integer;
A : TDoubleMatrix;
end;
// ###############################################
// #### incremental version of the base pca algorithm
// based on: Danijel Skocaj
// Robust Subspace Approaches to Visual Learning and Recognition
type
TIncrementalPCA = class(TMatrixPCA)
private
fNumEigenvectorsToKeep: integer;
fA : TDoubleMatrix;
fWeights : TDoubleDynArray;
fNumWeights : integer;
procedure AddWeight(const weight : double);
function GetA: 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 OnLoadIntProperty(const Name : String; Value : integer); override;
procedure OnLoadDoubleArr(const Name : String; const Value : TDoubleDynArray); override;
public
property NumEigenvectorsToKeep : integer read fNumEigenvectorsToKeep write fNumEigenvectorsToKeep;
property A : TDoubleMatrix read GetA;
function UpdateEigenspace(mtx : TDoubleMatrix) : boolean; overload;
// this function is an extension to the base incremental pca algorithm -> it uses the same blending algorithm
// as the weighted incremental version (this is works since it is only a special case of the weighted version!)
function UpdateEigenspace(mtx : TDoubleMatrix; const spacialWeights : Array of double) : boolean; overload;
// note the spacial weights MUST have values between 0 and 1. 1 means no weighting and 0 means that pixel is not taken into account.
// implementation of Daniejl S. weighted incremental PCA function (p 69ff):
// this function supports spacial weights as well as temporal weights. If the function without spacial weights is called
// all weights are set to 1 (no blending with the original image)
function UpdateEigenspaceWeighted(mtx : TDoubleMatrix; const weight : double) : boolean; overload;
function UpdateEigenspaceWeighted(mtx : TDoubleMatrix; const weight : double; const spacialWeights : Array of double) : boolean; overload;
function PCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : boolean) : boolean; override;
function TemporalWeightPCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : boolean; const Weights : Array of Double) : boolean; override;
constructor Create(const Data : TIncrPCAData); overload;
constructor Create(KeepFlags : TPCASaveDataSet); overload;
destructor Destroy; override;
end;
type
TFastRobustPCADataEx = record
RData : TFastRobustPCAData;
A : TDoubleMatrix;
Weights : TDoubleDynArray;
NumEigenVecs : integer;
SubA : TDoubleMatrixDynArr;
SubWeights : Array of TDoubleDynArray;
end;
// ###############################################
// #### incremental version of the fast robust pca algorithm
// a combination of the base fast robust pca method and the incremental pca algorithm
type
TFastRobustIncrementalPCA = class(TFastRobustPCA)
private
fNumEigenvectorsToKeep : integer;
fA : TDoubleMatrix;
fSubA : TDoubleMatrixDynArr;
fWeights : Array of TDoubleDynArray;
fNumWeights : TIntegerDynArray;
fSubEigVals : TDoubleMatrixDynArr;
procedure AddWeight(idx : integer; const weight : double);
procedure BuildSubspaces(Examples : TDoubleMatrix; origKeepFlags : TPCASaveDataSet);
protected
type
TListLoadType = (llNone, llSubA, llWeights, llSubEigVals);
private
fIdx : integer;
fListType : TListLoadType;
protected
procedure DefineProps; override;
function PropTypeOfName(const Name : string) : TPropType; override;
class function ClassIdentifier : String; override;
procedure OnLoadBeginList(const Name : String; count : integer); override;
procedure OnLoadEndList; override;
function OnLoadObject(Obj : TBaseMathPersistence) : boolean; overload; override;
function OnLoadObject(const Name : String; obj : TBaseMathPersistence) : boolean; overload; override;
procedure OnLoadListDoubleArr(const Value : TDoubleDynArray); override;
procedure OnLoadIntArr(const Name : String; const Value : TIntegerDynArray); override;
procedure OnLoadIntProperty(const Name : String; Value : integer); overload; override;
protected
procedure Clear; override;
public
property NumEigenvectorsToKeep : integer read fNumEigenvectorsToKeep write fNumEigenvectorsToKeep;
property A : TDoubleMatrix read fA;
function UpdateEigenspace(mtx : TDoubleMatrix) : boolean; overload;
// this function is an extension to the base incremental pca algorithm -> it uses the same blending algorithm
// as the weighted incremental version (this is works since it is only a special case of the weighted version!)
function UpdateEigenspace(mtx : TDoubleMatrix; const spacialWeights : Array of double) : boolean; overload;
// note the spacial weights MUST have values between 0 and 1. 1 means no weighting and 0 means that pixel is not taken into account.
// implementation of Daniejl S. weighted incremental PCA function (p 69ff):
// this function supports spacial weights as well as temporal weights. If the function without spacial weights is called
// all weights are set to 1 (no blending with the original image)
function UpdateEigenspaceWeighted(mtx : TDoubleMatrix; const weight : double) : boolean; overload;
function UpdateEigenspaceWeighted(mtx : TDoubleMatrix; const weight : double; const spacialWeights : Array of double) : boolean; overload;
function PCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : boolean) : boolean; override;
function TemporalWeightPCA(Examples : TDoubleMatrix; CutEps : double; IsRelativeValue : boolean; const Weights : Array of Double) : boolean; override;
constructor Create(const Props : TFastRobustPCADataEx); overload;
constructor Create(KeepFlags : TPCASaveDataSet); overload;
destructor Destroy; override;
end;
implementation
uses Math, MatrixConst, MathUtilFunc;
// ####################################################################
// #### Local functions - used to update the eigenspaces
// ####################################################################
// implements the update Eigenspace functions and holds references to all necessary data structures
type
TSubspaceUpdater = class(TObject)
private
fNumEigenvectorsToKeep : integer;
fEigVecs : TDoubleMatrix;
fEigVals : TDoubleMatrix;
fMeanElem : TDoubleMatrix;
fA : TDoubleMatrix;
fWeights : TDoubleDynArray;
fNumWeights : integer;
function InternalUpdateEigenspace(mtx : TDoubleMatrix; weighted : boolean) : boolean;
function PrepareBlendExample(mtx : TDoubleMatrix; const spacialWeights : Array of double) : TDoubleMatrix;
public
function UpdateEigenspace(mtx : TDoubleMatrix; var EigVecs, EigVals, MeanElem, A : TDoubleMatrix) : boolean; overload;
// this function is an extension to the base incremental pca algorithm -> it uses the same blending algorithm
// as the weighted incremental version (this is works since it is only a special case of the weighted version!)
function UpdateEigenspace(mtx : TDoubleMatrix; const spacialWeights : Array of double; var EigVecs, EigVals, MeanElem, A : TDoubleMatrix) : boolean; overload;
// note the spacial weights MUST have values between 0 and 1. 1 means no weighting and 0 means that pixel is not taken into account.
// implementation of Daniejl S. weighted incremental PCA function (p 69ff):
// this function supports spacial weights as well as temporal weights. If the function without spacial weights is called
// all weights are set to 1 (no blending with the original image)
function UpdateEigenspaceWeighted(mtx : TDoubleMatrix; var weights : TDoubleDynArray; var numWeights : integer; var EigVecs, EigVals, MeanElem, A : TDoubleMatrix) : boolean; overload;
function UpdateEigenspaceWeighted(mtx : TDoubleMatrix; var weights : TDoubleDynArray; var numWeights : integer; const spacialWeights : Array of double; var EigVecs, EigVals, MeanElem, A : TDoubleMatrix) : boolean; overload;
constructor Create(NumVectorsToKeep : integer);
end;
{ TSubspaceUpdater }
constructor TSubspaceUpdater.Create(NumVectorsToKeep: integer);
begin
inherited Create;
fNumEigenvectorsToKeep := NumVectorsToKeep;
end;
function TSubspaceUpdater.InternalUpdateEigenspace(mtx: TDoubleMatrix; weighted: boolean): boolean;
var normExample : TDoubleMatrix;
a : TDoubleMatrix;
r : TDoubleMatrix;
a1 : TDoubleMatrix;
u1 : TDoubleMatrix;
normR : double;
y : Integer;
x : Integer;
pca : TMatrixPCA;
temp : TDoubleMatrix;
eigVecsT : TDoubleMatrix;
begin
Result := False;
normExample := nil;
a := nil;
r := nil;
a1 := nil;
u1 := nil;
temp := nil;
eigVecsT := nil;
try
// project current example to the current feature space
normExample := mtx.Sub(fMeanElem);
eigVecsT := fEigVecs.Transpose;
a := EigVecsT.Mult(normExample);
FreeAndNil(eigVecsT);
// reconstruct example
FreeAndNil(normExample);
normExample := fEigVecs.Mult(a);
normExample.AddInplace(fMeanElem);
// compute residual vector and normalize
r := mtx.Sub(normExample);
normR := 0;
for y := 0 to r.Height - 1 do
normR := normR + sqr(r[0, y]);
normR := sqrt(normR);
// check error -> todo: better Boundary check
FreeAndNil(normExample);
if normR < 100*MinDouble then
begin
FreeAndNil(r);
FreeAndNil(a);
exit;
end;
// normalize vector
r.ScaleInPlace(1/normR);
// append new basis vector to u
u1 := TDoubleMatrix.Create(fEigVecs.Width + 1, fEigVecs.Height);
for x := 0 to fEigVecs.Width - 1 do
u1.SetColumn(x, fEigVecs, x);
u1.SetColumn(u1.Width - 1, r);
FreeAndNil(r);
// append new value in feature space
a1 := TDoubleMatrix.Create(fA.Width + 1, fA.Height + 1);
a1.SetSubMatrix(0, 0, a1.Width, a1.Height - 1);
for x := 0 to fA.Width - 1 do
a1.SetColumn(x, fA, x);
a1.SetColumn(a1.Width - 1, a);
a1.UseFullMatrix;
a1[a1.width - 1, a1.Height - 1] := normR;
FreeAndNil(a);
// perform full PCA on the new matrix a1
pca := TMatrixPCA.Create([pcaEigVals]);
try
if not weighted
then
Result := pca.PCA(a1, 1, True)
else
Result := pca.TemporalWeightPCA(a1, 1, True, Copy(fWeights, 0, fNumWeights));
if not Result then
exit;
// project the coefficient vectors to the new basis
FreeAndNil(fA);
for x := 0 to a1.Width - 1 do
begin
a1.SetSubMatrix(x, 0, 1, a1.Height);
a1.SubInPlace(pca.Mean);
end;
a1.UseFullMatrix;
fA := pca.EigVecsT.Mult(a1);
FreeAndNil(a1);
// update the mean
temp := u1.Mult(pca.Mean);
fMeanElem.AddInplace(temp);
FreeAndNil(temp);
// rotate the subspace
u1.MultInPlace(pca.EigVecs);
FreeAndNil(fEigVecs);
fEigVecs := u1;
u1 := nil;
// discard the last eigenvector -> keep the basis constant
if (fNumEigenvectorsToKeep > 0) and (fEigVecs.Width > fNumEigenvectorsToKeep) then
begin
temp := TDoubleMatrix.Create;
fEigVecs.SetSubMatrix(0, 0, fEigVecs.Width - 1, fEigVecs.Height);
temp.Assign(fEigVecs, True);
FreeAndNil(fEigVecs);
fEigVecs := temp;
// remove the last row -> it contains the values of the least significant
// elements
fA.SetSubMatrix(0, 0, fA.Width, fA.Height - 1);
end;
if Assigned(fEigVals) then
fEigVals.Assign(pca.EigVals);
finally
pca.Free;
end;
except
a.Free;
a1.Free;
u1.Free;
normExample.Free;
r.Free;
temp.Free;
eigVecsT.Free;
raise;
end;
end;
function TSubspaceUpdater.PrepareBlendExample(mtx: TDoubleMatrix;
const spacialWeights: array of double): TDoubleMatrix;
var uPinv : TDoubleMatrix;
x, y : integer;
rootWeights : TDoubleMatrix;
residual : TDoubleMatrix;
a : TDoubleMatrix;
begin
uPinv := nil;
rootWeights := nil;
Result := nil;
residual := nil;
a := nil;
try
// #########################################################
// #### Calculate the coefficients considering the spacial weights
rootWeights := TDoubleMatrix.Create(1, Length(spacialWeights));
for y := 0 to rootWeights.Height - 1 do
rootWeights[0, y] := sqrt(spacialWeights[y]);
uPinv := TDoubleMatrix.Create;
uPinv.Assign(fEigVecs);
// elementwise multiply the elements of U with the spacial weights
for x := 0 to uPinv.Width - 1 do
begin
uPinv.SetSubMatrix(x, 0, 1, uPinv.Height);
uPinv.ElementWiseMult(rootWeights);
end;
uPinv.UseFullMatrix;
if uPinv.PseudoInversionInPlace <> srOk then
begin
FreeAndNil(uPinv);
FreeAndNil(rootWeights);
exit;
end;
// calculated weighted residual
residual := mtx.Sub(fMeanElem);
residual.ElementWiseMult(rootWeights);
FreeAndNil(rootWeights);
// now calculate the projected elements in feature space
a := uPinv.Mult(residual);
FreeAndNil(uPinv);
// reconstruct example
FreeAndNil(residual);
residual := fEigVecs.Mult(a);
residual.AddInplace(fMeanElem);
FreeAndNil(a);
// ############################################################
// #### Blend the input and the reconstructed image considering the spatial weights
Result := TDoubleMatrix.Create(1, mtx.Height);
for y := 0 to Result.Height - 1 do
Result[0, y] := mtx[0, y]*spacialWeights[y] + residual[0, y]*(1 - spacialWeights[y]);
FreeAndNil(residual);
except
FreeAndNil(uPinv);
FreeAndNil(rootWeights);
FreeAndNil(residual);
FreeAndNil(a);
FreeAndNil(Result);
end;
end;
function TSubspaceUpdater.UpdateEigenspace(mtx: TDoubleMatrix;
const spacialWeights: array of double; var EigVecs, EigVals, MeanElem,
A: TDoubleMatrix): boolean;
var blendMtx : TDoubleMatrix;
begin
// #######################################################
// #### Execute the generic eigenspace update
fEigVecs := EigVecs;
fEigVals := EigVals;
fMeanElem := MeanElem;
fA := A;
blendMtx := PrepareBlendExample(mtx, spacialWeights);
try
Result := InternalUpdateEigenspace(blendMtx, False);
finally
blendMtx.Free;
end;
EigVecs := fEigVecs;
EigVals := fEigVals;
MeanElem := fMeanElem;
A := fA;
end;
function TSubspaceUpdater.UpdateEigenspace(mtx: TDoubleMatrix; var EigVecs,
EigVals, MeanElem, A: TDoubleMatrix): boolean;
begin
// #######################################################
// #### Execute the generic eigenspace update
assert(Assigned(mtx), 'Error missing data');
fEigVecs := EigVecs;
fEigVals := EigVals;
fMeanElem := MeanElem;
fA := A;
Result := InternalUpdateEigenspace(mtx, False);
EigVecs := fEigVecs;
EigVals := fEigVals;
MeanElem := fMeanElem;
A := fA;
end;
function TSubspaceUpdater.UpdateEigenspaceWeighted(mtx: TDoubleMatrix;
var weights: TDoubleDynArray; var NumWeights : integer; var EigVecs, EigVals, MeanElem,
A: TDoubleMatrix): boolean;
begin
// #######################################################
// #### Execute the generic eigenspace update
fEigVecs := EigVecs;
fEigVals := EigVals;
fMeanElem := MeanElem;
fWeights := Weights;
fNumWeights := numWeights;
fA := A;
Result := InternalUpdateEigenspace(mtx, True);
EigVecs := fEigVecs;
EigVals := fEigVals;
MeanElem := fMeanElem;
A := fA;
weights := fWeights;
numWeights := fNumWeights;
end;
function TSubspaceUpdater.UpdateEigenspaceWeighted(mtx: TDoubleMatrix;
var weights : TDoubleDynArray; var numWeights : integer; const spacialWeights: array of double; var EigVecs, EigVals, MeanElem,
A: TDoubleMatrix): boolean;
var blendMtx : TDoubleMatrix;
begin
// #######################################################
// #### Execute the generic eigenspace update
fEigVecs := EigVecs;
fEigVals := EigVals;
fMeanElem := MeanElem;
fWeights := weights;
fNumWeights := numWeights;
fA := A;
blendMtx := PrepareBlendExample(mtx, spacialWeights);
try
Result := InternalUpdateEigenspace(blendMtx, True);
finally
blendMtx.Free;
end;
EigVecs := fEigVecs;
EigVals := fEigVals;
MeanElem := fMeanElem;
A := fA;
numWeights := fNumWeights;
weights := fWeights;
end;
// ####################################################################
// #### Object Implementations
// ####################################################################
{ TIncrementalPCA }
procedure TIncrementalPCA.AddWeight(const weight: double);
begin
if Length(fWeights) <= fNumWeights + 1 then
SetLength(fWeights, Max(10, Min(Length(fWeights) + 1000, 2*fNumWeights)));
fWeights[fNumWeights] := weight;
inc(fNumWeights);
end;
constructor TIncrementalPCA.Create(const Data: TIncrPCAData);
begin
inherited Create(Data.Props);
fA := Data.A;
fWeights := Data.Weights;
fNumWeights := Length(fWeights);
fNumEigenvectorsToKeep := Data.NumEigenVecs;
end;
constructor TIncrementalPCA.Create(KeepFlags: TPCASaveDataSet);
begin
inherited Create(KeepFlags);
fNumEigenvectorsToKeep := -1;
fNumWeights := 0;
end;
destructor TIncrementalPCA.Destroy;
begin
fA.Free;
inherited;
end;
function TIncrementalPCA.GetA: TDoubleMatrix;
begin
if not Assigned(fA) then
fA := TDoubleMatrix.Create;
Result := fA;
end;
// ###############################################
// #### Persistence functions
class function TIncrementalPCA.ClassIdentifier: String;
begin
Result := 'IPCA';
end;
procedure TIncrementalPCA.DefineProps;
begin
inherited;
if Assigned(fA) then
AddObject('A', fA);
AddIntProperty('NumEigenvectorsToKeep', fNumEigenvectorsToKeep);
AddDoubleArr('IncrWeights', fWeights);
end;
function TIncrementalPCA.PropTypeOfName(const Name: string): TPropType;
begin
if CompareText(Name, 'A') = 0
then
Result := ptObject
else if CompareText(Name, 'NumEigenvectorsToKeep') = 0
then
Result := ptInteger
else if CompareText(Name, 'IncrWeights') = 0
then
Result := ptDouble
else
Result := inherited PropTypeOfName(Name);
end;
procedure TIncrementalPCA.OnLoadDoubleArr(const Name: String;
const Value: TDoubleDynArray);
begin
if CompareText(Name, 'IncrWeights') = 0 then
begin
fNumWeights := Length(value);
fWeights := Value;
end
else
inherited;
end;
function TIncrementalPCA.OnLoadObject(const Name: String;
obj: TBaseMathPersistence): boolean;
begin
Result := True;
if CompareText(Name, 'A') = 0
then
fA := obj as TDoubleMatrix
else
Result := inherited OnLoadObject(Name, Obj);
end;
procedure TIncrementalPCA.OnLoadIntProperty(const Name: String;
Value: integer);
begin
if CompareText(Name, 'NumEigenvectorsToKeep') = 0
then
fNumEigenvectorsToKeep := Value
else
inherited;
end;
function TIncrementalPCA.PCA(Examples: TDoubleMatrix; CutEps: double;
IsRelativeValue: boolean): boolean;
var origKeepFlags : TPCASaveDataSet;
begin
fNumWeights := 0;
fWeights := nil;
origKeepFlags := fKeepFlags;
include(fKeepFlags, pcaMeanNormalizedData);
Result := inherited PCA(Examples, CutEps, IsRelativeValue);
if Result then
begin
fA := EigVecT.Mult(fMeanNormExamples);
if not (pcaMeanNormalizedData in origKeepFlags) then
FreeAndNil(fMeanNormExamples);
if not (pcaTransposedEigVec in origKeepFlags) then
FreeAndNil(fEigVecsT);
fKeepFlags := origKeepFlags;
end;
end;
function TIncrementalPCA.TemporalWeightPCA(Examples: TDoubleMatrix;
CutEps: double; IsRelativeValue: boolean;
const Weights: array of Double): boolean;
var origKeepFlags : TPCASaveDataSet;
begin
SetLength(fWeights, Length(Weights));
fNumWeights := Length(fWeights);
SetLength(fWeights, Length(Weights));
if Length(Weights) > 0 then
Move(Weights[0], fWeights[0], sizeof(double)*Length(Weights));
origKeepFlags := fKeepFlags;
include(fKeepFlags, pcaMeanNormalizedData);
Result := inherited TemporalWeightPCA(Examples, CutEps, IsRelativeValue, Weights);
if Result then
begin
fA := EigVecT.Mult(fMeanNormExamples);
if not (pcaMeanNormalizedData in origKeepFlags) then
FreeAndNil(fMeanNormExamples);
if not (pcaTransposedEigVec in origKeepFlags) then
FreeAndNil(fEigVecsT);
fKeepFlags := origKeepFlags;
end;
end;
function TIncrementalPCA.UpdateEigenspace(mtx: TDoubleMatrix) : boolean;
var updater : TSubspaceUpdater;
begin
Result := True;
assert(mtx.Width = 1, 'Error only one example allowed');
if not Assigned(fMeanElem) then
begin
fMeanElem := TDoubleMatrix.Create;
fMeanElem.Assign(mtx, True);
fEigVecs := TDoubleMatrix.Create(1, mtx.Height);
fA := TDoubleMatrix.Create(1, 1);
if pcaEigVals in fKeepFlags then
fEigVals := TDoubleMatrix.Create(1, 1);
exit;
end;
// #######################################################
// #### Execute the generic eigenspace update
updater := TSubspaceUpdater.Create(fNumEigenvectorsToKeep);
try
Result := updater.UpdateEigenspace(mtx, fEigVecs, fEigVals, fMeanElem, fA);
finally
updater.Free;
end;
end;
function TIncrementalPCA.UpdateEigenspace(mtx: TDoubleMatrix;
const spacialWeights: array of double): boolean;
var updater : TSubspaceUpdater;
begin
Result := True;
assert(mtx.Width = 1, 'Error only one example allowed');
assert(mtx.Height = length(spacialWeights), 'Dimension error, spatial weights lenght differs from matrix height');
if not Assigned(fMeanElem) then
begin
fMeanElem := TDoubleMatrix.Create;
fMeanElem.Assign(mtx, True);
fEigVecs := TDoubleMatrix.Create(1, mtx.Height);
fA := TDoubleMatrix.Create(1, 1);
if pcaEigVals in fKeepFlags then
fEigVals := TDoubleMatrix.Create(1, 1);
exit;
end;
// ########################################################
// #### Use the subspace updater:
updater := TSubspaceUpdater.Create(fNumEigenvectorsToKeep);
try
Result := updater.UpdateEigenspace(mtx, spacialWeights, fEigVecs, fEigVals, fMeanElem, fA);
finally
updater.Free;
end;
end;
function TIncrementalPCA.UpdateEigenspaceWeighted(mtx: TDoubleMatrix;
const weight: double; const spacialWeights: array of double): boolean;
var updater : TSubspaceUpdater;
begin
Result := True;
assert(mtx.Width = 1, 'Error only one example allowed');
assert(mtx.Height = length(spacialWeights), 'Dimension error, spatial weights lenght differs from matrix height');
AddWeight(weight);
if not Assigned(fMeanElem) then
begin
fMeanElem := TDoubleMatrix.Create;
fMeanElem.Assign(mtx, True);
fEigVecs := TDoubleMatrix.Create(1, mtx.Height);
fA := TDoubleMatrix.Create(1, 1);
if pcaEigVals in fKeepFlags then
fEigVals := TDoubleMatrix.Create(1, 1);
exit;
end;
// ########################################################
// #### Use the subspace updater:
updater := TSubspaceUpdater.Create(fNumEigenvectorsToKeep);
try
Result := updater.UpdateEigenspaceWeighted(mtx, fWeights, fNumWeights, spacialWeights, fEigVecs, fEigVals, fMeanElem, fA);
finally
updater.Free;
end;
end;
function TIncrementalPCA.UpdateEigenspaceWeighted(mtx: TDoubleMatrix;
const weight: double): boolean;
var updater : TSubspaceUpdater;
begin
Result := True;
assert(mtx.Width = 1, 'Error only one example allowed');
AddWeight(weight);
if not Assigned(fMeanElem) then
begin
fMeanElem := TDoubleMatrix.Create;
fMeanElem.Assign(mtx, True);
fEigVecs := TDoubleMatrix.Create(1, mtx.Height);
fA := TDoubleMatrix.Create(1, 1);
if pcaEigVals in fKeepFlags then
fEigVals := TDoubleMatrix.Create(1, 1);
exit;
end;
// ########################################################
// #### Use the subspace updater:
updater := TSubspaceUpdater.Create(fNumEigenvectorsToKeep);
try
Result := updater.UpdateEigenspaceWeighted(mtx, fWeights, fNumWeights, fEigVecs, fEigVals, fMeanElem, fA);
finally
updater.Free;
end;
end;
{ TFastRobustIncrementalPCA }
procedure TFastRobustIncrementalPCA.AddWeight(idx : integer; const weight: double);
begin
if Length(fWeights[idx]) <= fNumWeights[idx] + 1 then
SetLength(fWeights[idx], Max(10, Min(Length(fWeights[idx]) + 1000, 2*fNumWeights[idx])));
fWeights[idx][fNumWeights[idx]] := weight;
inc(fNumWeights[idx]);
end;
procedure TFastRobustIncrementalPCA.BuildSubspaces(Examples: TDoubleMatrix; origKeepFlags : TPCASaveDataSet);
var i, idx : integer;
j : integer;
x : TDoubleMatrix;
subT : TDoubleMatrix;
begin
// main subspace
fA := EigVecT.Mult(fMeanNormExamples);
if not (pcaMeanNormalizedData in origKeepFlags) then
FreeAndNil(fMeanNormExamples);
if not (pcaTransposedEigVec in origKeepFlags) then
FreeAndNil(fEigVecsT);
// subsubspaces
SetLength(fSubA, fProps.NumSubSubSpaces);
for idx := 0 to Length(fSubEigVecs) - 1 do
begin
x := TDoubleMatrix.Create(Examples.Width, fSubMeanElem[idx].Height);
try
// project to feature space
for j := 0 to Examples.Width - 1 do
begin
for i := 0 to x.Height - 1 do
x[j, i] := Examples[j, fSubItemIdx[idx][i]];
x.SetSubMatrix(j, 0, 1, x.Height);
x.SubInPlace(fSubMeanElem[idx]);
x.UseFullMatrix;
end;
subT := fSubEigVecs[idx].Transpose;
try
fSubA[idx] := subT.Mult(x);
finally
subT.Free;
end;
finally
x.Free;
end;
end;
end;
procedure TFastRobustIncrementalPCA.Clear;
var i : integer;
begin
inherited;
if not fIsLearning then
begin
FreeAndNil(fA);
for i := 0 to Length(fSubA) - 1 do
fSubA[i].Free;
for i := 0 to Length(fSubEigVals) - 1 do
fSubEigVals[i].Free;
fSubA := nil;
fWeights := nil;
fNumWeights := nil;
fSubEigVals := nil;
fSubEigVecsT := nil;
end;
end;
constructor TFastRobustIncrementalPCA.Create(KeepFlags: TPCASaveDataSet);
begin
inherited Create(KeepFlags);
end;
constructor TFastRobustIncrementalPCA.Create(const Props: TFastRobustPCADataEx);
var i : integer;
begin
inherited Create(props.RData);
fA := props.A;
fNumEigenvectorsToKeep := Props.NumEigenVecs;
fSubA := Props.SubA;
SetLength(fWeights, 1 + Length(Props.SubWeights));
fWeights[0] := Props.Weights;
SetLength(fNumWeights, Length(fWeights));
for i := 0 to Length(fNumWeights) - 1 do
fNumWeights[i] := Length(fWeights[i]);
fSubA := Props.SubA;
for i := 0 to Length(Props.SubWeights) - 1 do
fWeights[1 + i] := Props.SubWeights[i];
end;
destructor TFastRobustIncrementalPCA.Destroy;
begin
// inherited calls Clear!
inherited;
end;
procedure TFastRobustIncrementalPCA.DefineProps;
var i : Integer;
begin
inherited;
if Assigned(fA) then
AddObject('A', fA);
AddIntProperty('NumEigenvectorsToKeep', fNumEigenvectorsToKeep);
if Length(fWeights) > 0 then
begin
BeginList('IPCAWeights', Length(fWeights));
for i := 0 to Length(fWeights) - 1 do
AddListDoubleArr(fWeights[i]);
EndList;
end;
if Length(fNumWeights) > 0 then
AddIntArr('IPCANumWeights', fNumWeights);
if Length(fSubA) > 0 then
begin
BeginList('IPCASUBA', Length(fSubA));
for i := 0 to Length(fSubA) - 1 do
AddObject(fSubA[i]);
EndList;
end;
if Length(fSubEigVals) > 0 then
begin
BeginList('IPCASUBEIGVALS', Length(fSubEigVals));
for i := 0 to Length(fSubEigVals) - 1 do
AddObject(fSubEigVals[i]);
EndList;
end;
end;
function TFastRobustIncrementalPCA.PropTypeOfName(
const Name: string): TPropType;
begin
if (CompareText(Name, 'IPCASUBEIGVALS') = 0) or (CompareText(Name, 'IPCASUBA') = 0) or
(CompareText(Name, 'A') = 0)
then
Result := ptObject
else if CompareText(Name, 'IPCAWeights') = 0
then
Result := ptObject
else if CompareText(Name, 'NumEigenvectorsToKeep') = 0
then
Result := ptInteger
else
Result := inherited PropTypeOfName(Name);
end;
class function TFastRobustIncrementalPCA.ClassIdentifier: String;
begin
Result := 'FRIPCA';
end;
procedure TFastRobustIncrementalPCA.OnLoadBeginList(const Name: String;
count: integer);
begin
fIdx := 0;
if CompareText(Name, 'IPCAWeights') = 0 then
begin
fListType := llWeights;
SetLength(fWeights, Count);
end
else if CompareText(Name, 'IPCASUBA') = 0 then
begin
fListType := llSubA;
SetLength(fSubA, Count);
end
else if CompareText(Name, 'IPCASUBEIGVALS') = 0 then
begin
fListType := llSubEigVals;
SetLength(fSubEigVals, Count);
end
else
inherited;
end;
procedure TFastRobustIncrementalPCA.OnLoadEndList;
begin
inherited;
fListType := llNone;
end;
procedure TFastRobustIncrementalPCA.OnLoadIntArr(const Name: String;
const Value: TIntegerDynArray);
begin
if CompareText(Name, 'IPCANumWeights') = 0
then
fNumWeights := Value
else
inherited;
end;
procedure TFastRobustIncrementalPCA.OnLoadListDoubleArr(
const Value: TDoubleDynArray);
begin
if fListType = llWeights then
begin
fWeights[fIdx] := Value;