Repository navigation
Expand file tree
/
Copy pathgp.cpp
More file actions
1209 lines (1177 loc) · 45.3 KB
/
Copy pathgp.cpp
File metadata and controls
1209 lines (1177 loc) · 45.3 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
#include "gp.h"
int main(int argc, char* argv[])
{
CClgp command(argc, argv);
command.setFlags(true);
command.setVerbosity(2);
command.setMode("gp");
try {
while(command.isFlags())
{
string argument = command.getCurrentArgument();
if(argv[command.getCurrentArgumentNo()][0]=='-')
{
if (command.isCurrentArg("-?", "--?"))
{
command.helpInfo();
command.exitNormal();
}
else if(command.isCurrentArg("-h", "--help"))
{
command.helpInfo();
command.exitNormal();
}
else if(command.isCurrentArg("-v", "--verbosity"))
{
command.incrementArgument();
command.setVerbosity(command.getIntFromCurrentArgument());
}
else if(command.isCurrentArg("-s", "--seed"))
{
command.incrementArgument();
command.setSeed(command.getIntFromCurrentArgument());
}
else
command.unrecognisedFlag();
}
else if(argument=="learn") // learning a model.
command.learn();
else if(argument=="relearn") // initialise with an old model.
command.relearn();
//else if(argument=="test") // test with a model.
// command.test();
//else if(argument=="log-likelihood") // compute model log likelihood.
// command.logLikelihood();
//else if(argument=="predict")
// command.predict();
else if(argument=="display")
command.display();
else if(argument=="gnuplot")
command.gnuplot();
else
command.exitError("Invalid gp command provided.");
command.incrementArgument();
}
command.exitError("No gp command provided.");
}
catch(ndlexceptions::CommandLineError err) {
command.exitError(err.getMessage());
}
catch(ndlexceptions::FileFormatError err) {
command.exitError(err.getMessage());
}
catch(ndlexceptions::FileReadError err) {
command.exitError(err.getMessage());
}
catch(ndlexceptions::FileWriteError err) {
command.exitError(err.getMessage());
}
catch(ndlexceptions::FileError err) {
command.exitError(err.getMessage());
}
catch(ndlexceptions::Error err) {
command.exitError(err.getMessage());
}
catch(std::bad_alloc err) {
command.exitError("Out of memory.");
}
catch(std::exception err) {
command.exitError("Unhandled exception.");
}
}
CClgp::CClgp(int arc, char** arv) : CClctrl(arc, arv)
{
}
void CClgp::learn()
{
incrementArgument();
setMode("learn");
enum {
KERNEL_USAGE_BACK,
KERNEL_USAGE_FWD,
KERNEL_USAGE_DYN
};
double tol=1e-6;
string optimiser="scg";
vector<string> kernelTypes;
vector<unsigned int> kernelUsageFlag;
vector<double> ratQuadAlphas;
vector<double> rbfInvWidths;
vector<double> weightVariances;
vector<double> biasVariances;
vector<double> variances;
vector<double> degrees;
vector<int> arccosOrders;
vector<bool> selectInputs;
vector<string> setSpecs;
bool centreData=true;
bool scaleData=false;
bool outputScaleLearnt=false;
int activeSetSize = -1;
int approxType = -1;
string approxTypeStr = "ftc";
string sparseLinalgStr = "lq";
string inducingTypeStr = "points";
double windowWidth = -1.0;
bool allowWhiteAndNoise = false;
bool labelsProvided = true;
double signalVariance = 0.0;
vector<int> labels;
int iters=1000;
string modelFileName="gp_model";
while(isFlags()) {
if(isCurrentArgumentFlag()) {
if (isCurrentArg("-?", "--?")) {
helpInfo();
exitNormal();
}
else if (isCurrentArg("-h", "--help")) {
helpInfo();
exitNormal();
}
else if (isCurrentArg("-C", "--Centre-data")) {
incrementArgument();
centreData=getBoolFromCurrentArgument();
}
else if (isCurrentArg("-L", "--Learn-scales")) {
incrementArgument();
outputScaleLearnt=getBoolFromCurrentArgument();
}
else if (isCurrentArg("-S", "--Scale-data")) {
incrementArgument();
scaleData=getBoolFromCurrentArgument();
}
else if(isCurrentArg("-a", "--active-set-size")) {
incrementArgument();
activeSetSize = getIntFromCurrentArgument();
}
else if (isCurrentArg("-A", "--Approximation-type")) {
incrementArgument();
approxTypeStr = getCurrentArgument();
}
else if (isCurrentArg("-L", "--sparse-linalg")) {
incrementArgument();
sparseLinalgStr = getCurrentArgument();
}
else if (isCurrentArg("--inducing", "--inducing")) {
incrementArgument();
inducingTypeStr = getCurrentArgument();
}
else if (isCurrentArg("--window-width", "--window-width")) {
incrementArgument();
windowWidth = getDoubleFromCurrentArgument();
}
else if (isCurrentArg("--allow-white-and-noise", "--allow-white-and-noise")) {
allowWhiteAndNoise=true;
}
else if (isCurrentArg("-k", "--kernel")) {
incrementArgument();
kernelTypes.push_back(getCurrentArgument());
kernelUsageFlag.push_back(KERNEL_USAGE_FWD);
ratQuadAlphas.push_back(-1.0);
rbfInvWidths.push_back(-1.0);
weightVariances.push_back(-1.0);
biasVariances.push_back(-1.0);
variances.push_back(-1.0);
degrees.push_back(-1.0);
arccosOrders.push_back(-1);
selectInputs.push_back(false);
}
else if (isCurrentArg("--arccos-order", "--arccos-order")) {
incrementArgument();
if(kernelTypes.size()==0)
exitError("Arc-cosine order must come after -k arccos.");
if(kernelTypes[kernelTypes.size()-1]!="arccos"
&& kernelTypes[kernelTypes.size()-1]!="arccosine")
exitError("--arccos-order only valid for arccos / arccosine covariance.");
arccosOrders[arccosOrders.size()-1]=getIntFromCurrentArgument();
}
else if (isCurrentArg("-g", "--gamma")) {
incrementArgument();
if(kernelTypes.size()==0)
exitError("Inverse width specification must come after covariance function type is specified.");
const string& kt = kernelTypes[kernelTypes.size()-1];
if(kt!="rbf" && kt!="rbfard" && kt!="eq" && kt!="exp" && kt!="ratquad" && kt!="ratquadard"
&& kt!="matern32" && kt!="matern52" && kt!="matern32ard" && kt!="matern52ard"
&& kt!="stdperiodic" && kt!="cosine" && kt!="sinc" && kt!="expquadcosine")
exitError("Inverse width / lengthscale (-g) only valid for RBF/EQ/exp/ratquad/Matérn/stdperiodic/cosine/sinc/expquadcosine (and ARD variants).");
rbfInvWidths[rbfInvWidths.size()-1]=2*getDoubleFromCurrentArgument();
}
else if (isCurrentArg("-d", "--degree")) {
incrementArgument();
if(kernelTypes.size()==0)
exitError("Polynomial degree specification must come after covariance function type is specified.");
if(kernelTypes[kernelTypes.size()-1]!="poly")
exitError("Polynomial degree parameter only valid for poly covariance function.");
degrees[degrees.size()-1]=getDoubleFromCurrentArgument();
}
else if (isCurrentArg("-w", "--weight")) {
incrementArgument();
if(kernelTypes.size()==0)
exitError("`Weight variance' parameter specification must come after covariance function type is specified.");
if(kernelTypes[kernelTypes.size()-1]!="poly"
&& kernelTypes[kernelTypes.size()-1]!="mlp")
exitError("`Weight variance' parameter only valid for polynomial and MLP covariance function.");
weightVariances[weightVariances.size()-1]=getDoubleFromCurrentArgument();
}
else if (isCurrentArg("-b", "--bias")) {
incrementArgument();
if(kernelTypes.size()==0)
exitError("`Bias variance' parameter specification must come after covariance function type is specified.");
if(kernelTypes[kernelTypes.size()-1]!="poly"
&& kernelTypes[kernelTypes.size()-1]!="mlp")
exitError("`Bias variance' parameter only valid for polynomial and MLP covariance function.");
biasVariances[biasVariances.size()-1]=getDoubleFromCurrentArgument();
}
else if (isCurrentArg("-v", "--variance")) {
incrementArgument();
if(kernelTypes.size()==0)
exitError("Variance parameter specification must come after covariance function type is specified.");
variances[variances.size()-1]=getDoubleFromCurrentArgument();
}
else if (isCurrentArg("-i", "--input-select")) {
incrementArgument();
if(kernelTypes.size()==0)
exitError("Input selection flag must come after covariance function type is specified.");
selectInputs[selectInputs.size()-1]=getBoolFromCurrentArgument();
}
else if (isCurrentArg("-P", "--set")) {
incrementArgument();
setSpecs.push_back(getCurrentArgument());
}
else if(isCurrentArg("-O", "--optimiser")) {
incrementArgument();
optimiser=getCurrentArgument();
}
else if (isCurrentArg("-#", "--#iterations")) {
incrementArgument();
iters=getIntFromCurrentArgument();
}
else if (isCurrentArg("-f", "--file-format")) {
incrementArgument();
setFileFormat(getIntFromCurrentArgument());
}
else {
unrecognisedFlag();
}
incrementArgument();
}
else
setFlags(false);
}
if(getCurrentArgumentNo()>=argc)
exitError("There are not enough input parameters.");
string trainDataFileName=getCurrentArgument();
if((getCurrentArgumentNo()+1)<argc)
modelFileName=argv[getCurrentArgumentNo()+1];
string dataFile="";
CMatrix X;
CMatrix y;
readData(X, y, trainDataFileName);
int inputDim = X.getCols();
// create covariance function.
CCmpndKern kern(X);
vector<CKern*> kernels;
for(int i=0; i<kernelTypes.size(); i++) {
CMatrix *M = 0;
M = &X;
if(kernelTypes[i]=="lin") {
if(selectInputs[i])
kernels.push_back(new CLinardKern(*M));
else
kernels.push_back(new CLinKern(*M));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="poly") {
if(selectInputs[i]) {
kernels.push_back(new CPolyardKern(*M));
if(degrees[i]!=-1.0)
((CPolyardKern*)kernels[i])->setDegree(degrees[i]);
}
else {
kernels.push_back(new CPolyKern(*M));
if(degrees[i]!=-1.0)
((CPolyKern*)kernels[i])->setDegree(degrees[i]);
}
if(weightVariances[i]!=-1.0)
kernels[i]->setByPath("weight_variance", weightVariances[i]);
if(biasVariances[i]!=-1.0)
kernels[i]->setByPath("bias_variance", biasVariances[i]);
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="rbf" || kernelTypes[i]=="rbfard") {
if(selectInputs[i] || kernelTypes[i]=="rbfard")
kernels.push_back(new CRbfardKern(*M));
else
kernels.push_back(new CRbfKern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("inverseWidth", rbfInvWidths[i]);
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="eq" || kernelTypes[i]=="ExpQuad" || kernelTypes[i]=="expquad") {
if(selectInputs[i])
exitError("EQ/ExpQuad covariance does not map to ARD via -i; use -k rbfard.");
kernels.push_back(new CEqKern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("inverseWidth", rbfInvWidths[i]);
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="exp") {
if(selectInputs[i])
exitError("Exponential covariance function not available with input selection yet.");
else
kernels.push_back(new CExpKern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("inverseWidth", rbfInvWidths[i]);
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="ratquad" || kernelTypes[i]=="ratquadard") {
if(selectInputs[i] || kernelTypes[i]=="ratquadard")
kernels.push_back(new CRatQuadardKern(*M));
else
kernels.push_back(new CRatQuadKern(*M));
if(ratQuadAlphas[i]!=-1.0)
kernels[i]->setByPath("power", ratQuadAlphas[i]);
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("lengthscale", 1/sqrt(rbfInvWidths[i]));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="matern32" || kernelTypes[i]=="matern32ard") {
if(selectInputs[i] || kernelTypes[i]=="matern32ard")
kernels.push_back(new CMatern32ardKern(*M));
else
kernels.push_back(new CMatern32Kern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("lengthscale", 1.0/sqrt(rbfInvWidths[i]));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="matern52" || kernelTypes[i]=="matern52ard") {
if(selectInputs[i] || kernelTypes[i]=="matern52ard")
kernels.push_back(new CMatern52ardKern(*M));
else
kernels.push_back(new CMatern52Kern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("lengthscale", 1.0/sqrt(rbfInvWidths[i]));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="stdperiodic") {
if(selectInputs[i])
exitError("stdperiodic does not map to ARD via -i.");
kernels.push_back(new CStdPeriodicKern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("lengthscale", 1.0/sqrt(rbfInvWidths[i]));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="cosine") {
if(selectInputs[i])
exitError("cosine does not map to ARD via -i.");
kernels.push_back(new CCosineKern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("lengthscale", 1.0/sqrt(rbfInvWidths[i]));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="sinc") {
if(selectInputs[i])
exitError("sinc does not map to ARD via -i.");
kernels.push_back(new CSincKern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("lengthscale", 1.0/sqrt(rbfInvWidths[i]));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="expquadcosine" || kernelTypes[i]=="ExpQuadCosine") {
if(selectInputs[i])
exitError("expquadcosine does not map to ARD via -i.");
kernels.push_back(new CExpQuadCosineKern(*M));
if(rbfInvWidths[i]!=-1.0)
kernels[i]->setByPath("lengthscale", 1.0/sqrt(rbfInvWidths[i]));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="brownian") {
if(selectInputs[i])
exitError("brownian does not map to ARD via -i.");
kernels.push_back(new CBrownianKern(*M));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i]=="ibrownian" || kernelTypes[i]=="integratedbrownian") {
if(selectInputs[i])
exitError("ibrownian does not map to ARD via -i.");
kernels.push_back(new CIntegratedBrownianKern(*M));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i] == "mlp") {
if(selectInputs[i])
kernels.push_back(new CMlpardKern(*M));
else
kernels.push_back(new CMlpKern(*M));
if(weightVariances[i]!=-1.0)
kernels[i]->setByPath("weight_variance", weightVariances[i]);
if(biasVariances[i]!=-1.0)
kernels[i]->setByPath("bias_variance", biasVariances[i]);
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i] == "arccos" || kernelTypes[i] == "arccosine") {
if(selectInputs[i])
exitError("Arc-cosine covariance does not map to ARD via -i yet.");
CArcCosineKern* ak = new CArcCosineKern(*M);
if(arccosOrders[i] >= 0)
ak->setOrder((unsigned int)arccosOrders[i]);
kernels.push_back(ak);
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i] == "bias" && kernelUsageFlag[i]!=KERNEL_USAGE_FWD) {
// Explicit -k bias only (CIP-0027: no longer auto-appended).
kernels.push_back(new CBiasKern(*M));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else if(kernelTypes[i] == "white" && kernelUsageFlag[i]!=KERNEL_USAGE_FWD) {
// Explicit -k white only (CIP-0027: observation noise is likelihood.variance).
kernels.push_back(new CWhiteKern(*M));
if(variances[i]!=-1.0)
kernels[i]->setByPath("variance", variances[i]);
}
else {
exitError("Unknown covariance function type: " + kernelTypes[i]);
}
switch (kernelUsageFlag[i]) {
case KERNEL_USAGE_FWD:
kern.addKern(kernels[i]);
break;
case KERNEL_USAGE_BACK:
break;
case KERNEL_USAGE_DYN:
break;
}
}
// if no covariance function was specified, add an RBF.
// CIP-0027 Phase B: do not auto-append Bias or White; FTC noise is likelihood.variance.
if(kern.getNumKerns()==0)
{
CKern* defaultKern = new CRbfKern(X);
kern.addKern(defaultKern);
}
if(approxTypeStr=="ftc") {
approxType = CGp::FTC;
activeSetSize = -1;
}
else {
if(approxTypeStr=="dtc") {
approxType = CGp::DTC;
}
else if(approxTypeStr=="dtcvar") {
approxType = CGp::DTCVAR;
// DTCVAR matches GPy VarDTC on the spherical Gaussian path (see
// backlog/bugs/2026-11-15_dtcvar-numerical-diagnostic.md). K_uu / A may
// still need jitter under poor conditioning, as with DTC.
}
else if(approxTypeStr=="fitc") {
// FITC works on the spherical Gaussian path (testCGp / StableFactor / LQ).
// Prefer -A dtcvar for tutorials; FITC remains available for parity/bench.
approxType = CGp::FITC;
}
else if(approxTypeStr=="pitc") {
approxType = CGp::PITC;
}
else {
exitError("Unknown sparse approximation type: " + approxTypeStr + ".");
}
if(activeSetSize==-1)
exitError("You must choose an active set size (option -a) for the command learn.");
}
CGaussianNoise noise(&y);
noise.setBias(0.0);
// Remove scales and center if necessary.
CMatrix scale(1, y.getCols(), 1.0);
CMatrix bias(1, y.getCols(), 0.0);
if(centreData)
bias.deepCopy(meanCol(y));
if(scaleData)
scale.deepCopy(stdCol(y));
CGp* pmodel;
CMatrix bK(1,1,0.0);
pmodel = new CGp(&kern, &noise, &X, approxType, activeSetSize, getVerbosity());
if(sparseLinalgStr=="legacy")
pmodel->setSparseLinalgMode(CGp::SparseLinalgLegacy);
else if(sparseLinalgStr=="stable")
pmodel->setSparseLinalgMode(CGp::SparseLinalgStableFactor);
else if(sparseLinalgStr=="lq")
pmodel->setSparseLinalgMode(CGp::SparseLinalgLQ);
else
exitError("Unknown --sparse-linalg mode (use legacy, stable, or lq): " + sparseLinalgStr);
if(pmodel->isSparseApproximation())
{
try
{
pmodel->setInducingType(inducingTypeStr);
}
catch(ndlexceptions::Error& err)
{
exitError(err.getMessage());
}
if((inducingTypeStr == "whitenoise" || inducingTypeStr == "greens"
|| inducingTypeStr == "weightspace")
&& windowWidth > 0.0)
{
try
{
pmodel->getInducing()->setWindowWidth(windowWidth);
}
catch(ndlexceptions::Error& err)
{
exitError(err.getMessage());
}
}
}
if(optimiser=="scg")
pmodel->setDefaultOptimiser(CGp::SCG);
else if(optimiser=="conjgrad")
pmodel->setDefaultOptimiser(CGp::CG);
else if(optimiser=="graddesc")
pmodel->setDefaultOptimiser(CGp::GD);
else if(optimiser=="quasinew" || optimiser=="lbfgs")
pmodel->setDefaultOptimiser(CGp::BFGS);
else
exitError("Unrecognised optimiser type: " + optimiser);
pmodel->setBetaVal(1); // sparse: β=1 ⇒ likelihood.variance=1 (CIP-0027 sync)
if(pmodel->getApproximationType()==CGp::FTC && pmodel->isGaussianNoise())
pmodel->setLikelihoodVariance(1.0); // GPy-like default observation noise
// CIP-0027 Phase C: explicit -k white with free likelihood.variance needs allow,
// otherwise fix likelihood variance (legacy White-owned noise).
if(allowWhiteAndNoise)
pmodel->setAllowWhiteAndLikelihoodNoise(true);
else if(pmodel->getApproximationType()==CGp::FTC && pmodel->isGaussianNoise())
{
try
{
(void)kern.getByPath("white.variance");
pmodel->fixLikelihoodVariance(true);
if(getVerbosity()>0)
cout << "CIP-0027: White present — fixing likelihood.variance "
<< "(use --allow-white-and-noise to train both)." << endl;
}
catch(ndlexceptions::Error&)
{
// no White component
}
}
pmodel->setScale(scale);
pmodel->setBias(bias);
pmodel->updateM();
pmodel->setOutputScaleLearnt(outputScaleLearnt);
for(size_t si=0; si<setSpecs.size(); si++)
{
const string& spec=setSpecs[si];
const size_t eq=spec.find('=');
if(eq==string::npos || eq==0 || eq+1>=spec.size())
exitError("--set expects path=value (e.g. rbf.variance=1.0), got: "+spec);
const string path=spec.substr(0, eq);
const double val=atof(spec.substr(eq+1).c_str());
try
{
pmodel->setByPath(path, val);
}
catch(ndlexceptions::Error& err)
{
exitError(string("--set failed for '")+path+"': "+err.getMessage());
}
}
//writeGpToFile(*pmodel, "c:\\gp_model", "Write for testing of model");
pmodel->optimise(iters);
string comment="";
switch(getFileFormat()) {
case 0: /// GP file format.
comment = "Run as:";
for(int i=0; i<argc; i++) {
comment+=" ";
comment+=argv[i];
}
comment += " with seed " + ndlstrutil::itoa(getSeed()) + ".";
writeGpToFile(*pmodel, modelFileName, comment);
break;
case 1: /// Matlab file format.
#ifdef _NDLMATLAB
// Write matlab output.
pmodel->writeMatlabFile(modelFileName, "gpInfo");
pmodel->getKernel()->updateMatlabFile(modelFileName, "kern");
X.updateMatlabFile(modelFileName, "X");
y.updateMatlabFile(modelFileName, "y");
#else
exitError("Error MATLAB not incorporated at compile time.");
#endif
break;
default:
exitError("Unrecognised file format number.");
}
exitNormal();
}
void CClgp::relearn()
{
incrementArgument();
setMode("relearn");
string optimiser="scg";
int iters=1000;
string modelFileName="gp_model";
string newModelFileName="gp_model";
while(isFlags()) {
if(isCurrentArgumentFlag()) {
if(isCurrentArg("-?", "--?")) {
helpInfo();
exitNormal();
}
else if(isCurrentArg("-h", "--help")) {
helpInfo();
exitNormal();
}
else if(isCurrentArg("-O", "--optimiser")) {
incrementArgument();
optimiser=getCurrentArgument();
}
else if(isCurrentArg("-#", "--#iterations")) {
incrementArgument();
iters=getIntFromCurrentArgument();
}
else {
unrecognisedFlag();
}
incrementArgument();
}
else {
setFlags(false);
}
}
if(getCurrentArgumentNo()>=argc)
exitError("There are not enough input parameters.");
string trainDataFileName=getCurrentArgument();
if((getCurrentArgumentNo()+1)<argc)
modelFileName=argv[getCurrentArgumentNo()+1];
if((getCurrentArgumentNo()+2)<argc)
newModelFileName=argv[getCurrentArgumentNo()+2];
CMatrix X;
CMatrix y;
readData(X, y, trainDataFileName);
CGp* pmodel=readGpFromFile(modelFileName, getVerbosity());
pmodel->py = &y;
pmodel->updateM();
pmodel->pX = &X;
if(optimiser=="scg")
pmodel->setDefaultOptimiser(CGp::SCG);
else if(optimiser=="conjgrad")
pmodel->setDefaultOptimiser(CGp::CG);
else if(optimiser=="graddesc")
pmodel->setDefaultOptimiser(CGp::GD);
else if(optimiser=="quasinew" || optimiser=="lbfgs")
pmodel->setDefaultOptimiser(CGp::BFGS);
else
exitError("Unrecognised optimiser type: " + optimiser);
if(pmodel->getInputDim()!=X.getCols())
throw ndlexceptions::Error(trainDataFileName + ": input data is not of correct dimension");
pmodel->optimise(iters);
string comment="";
switch(getFileFormat()) {
case 0: /// GP file format.
comment = "Run as:";
for(int i=0; i<argc; i++) {
comment+=" ";
comment+=argv[i];
}
comment += " with seed " + ndlstrutil::itoa(getSeed()) + ".";
writeGpToFile(*pmodel, newModelFileName, comment);
break;
case 1: /// Matlab file format.
#ifdef _NDLMATLAB
// Write matlab output.
pmodel->writeMatlabFile(newModelFileName, "gpInfo");
pmodel->getKernel()->updateMatlabFile(newModelFileName, "kern");
X.updateMatlabFile(newModelFileName, "X");
y.updateMatlabFile(newModelFileName, "y");
#else
exitError("Error MATLAB not incorporated at compile time.");
#endif
break;
default:
exitError("Unrecognised file format number.");
}
exitNormal();
}
void CClgp::display()
{
incrementArgument();
setMode("display");
while(isFlags()) {
if(isCurrentArgumentFlag()) {
if(getCurrentArgumentLength()!=2) {
unrecognisedFlag();
}
if (isCurrentArg("-?", "--?") ||isCurrentArg("-h", "--help")) {
helpInfo();
exitNormal();
}
else {
unrecognisedFlag();
}
incrementArgument();
}
else
setFlags(false);
}
string modelFileName = "";
if(getCurrentArgumentNo()>=argc)
modelFileName="gp_model";
else
modelFileName=getCurrentArgument();
CGp* pmodel=readGpFromFile(modelFileName, getVerbosity());
pmodel->display(cout);
exitNormal();
}
void CClgp::gnuplot()
{
incrementArgument();
setMode("gnuplot");
double pointSize = 2;
double lineWidth = 2;
int resolution = 80;
string name = "gp";
string modelFileName="gp_model";
string labelFileName="";
while(isFlags()) {
if(isCurrentArgumentFlag()) {
int j=1;
if(getCurrentArgumentLength()!=2)
unrecognisedFlag();
else if(isCurrentArg("-?","--?") || isCurrentArg("-h","--help")) {
helpInfo();
exitNormal();
}
else if (isCurrentArg("-l", "--labels")) {
incrementArgument();
labelFileName=getStringFromCurrentArgument();
}
else if (isCurrentArg("-p", "--point-size")) {
incrementArgument();
pointSize=getDoubleFromCurrentArgument();
}
else if (isCurrentArg("-r", "--resolution")) {
incrementArgument();
resolution=getIntFromCurrentArgument();
}
else {
unrecognisedFlag();
}
incrementArgument();
}
else
setFlags(false);
}
if(getCurrentArgumentNo()>=argc)
exitError("There are not enough input parameters.");
string dataFileName=getCurrentArgument();
if((getCurrentArgumentNo()+1)<argc)
modelFileName=argv[getCurrentArgumentNo()+1];
if((getCurrentArgumentNo()+2)<argc)
name=argv[getCurrentArgumentNo()+2];
string outputFileName=name+"_plot_data";
if((getCurrentArgumentNo()+3)<argc)
outputFileName=argv[getCurrentArgumentNo()+2];
CMatrix y;
CMatrix X;
readData(X, y, dataFileName);
CGp* pmodel=readGpFromFile(modelFileName, getVerbosity());
pmodel->py=&y;
pmodel->updateM();
pmodel->pX=&X;
/// START HERE
if(pmodel->getNoiseType()!="gaussian" && pmodel->getInputDim()!=2) {
exitError("Incorrect number of model inputs.");
}
if(pmodel->getNoiseType()=="gaussian" && pmodel->getInputDim()>2) {
exitError("Incorrect number of model inputs.");
}
if(X.getCols()!=pmodel->getInputDim()) {
exitError("Incorrect dimension of input data.");
}
if(pmodel->getNoiseType()=="probit" || pmodel->getNoiseType()=="ncnm") {
pmodel->X_u.toUnheadedFile(name+"_inducing_set.dat");
int numPos = 0;
int numNeg = 0;
int numUnlab = 0;
for(int i=0; i<X.getRows(); i++) {
if(y.getVal(i)==1.0)
numPos++;
else if(y.getVal(i)==-1.0)
numNeg++;
else
numUnlab++;
}
CMatrix XPos(numPos, X.getCols()+1);
CMatrix XNeg(numNeg, X.getCols()+1);
CMatrix XUnlab(numUnlab, X.getCols()+1);
int posIndex = 0;
int negIndex = 0;
int unlabIndex = 0;
for(int i=0; i<X.getRows(); i++) {
if(y.getVal(i)==1.0) {
for(int j=0; j<X.getCols(); j++)
XPos.setVal(X.getVal(i, j), posIndex, j);
XPos.setVal(0, posIndex, XPos.getCols()-1);
posIndex++;
}
else if(y.getVal(i)==-1.0) {
for(int j=0; j<X.getCols(); j++)
XNeg.setVal(X.getVal(i, j), negIndex, j);
XNeg.setVal(0, negIndex, XNeg.getCols()-1);
negIndex++;
}
else {
for(int j=0; j<X.getCols(); j++)
XUnlab.setVal(X.getVal(i, j), unlabIndex, j);
XUnlab.setVal(0, unlabIndex, XUnlab.getCols()-1);
unlabIndex++;
}
}
if(numPos>0)
XPos.toUnheadedFile(name+"_positive.dat");
if(numNeg>0)
XNeg.toUnheadedFile(name+"_negative.dat");
if(numUnlab>0)
XUnlab.toUnheadedFile(name+"_unlabelled.dat");
CMatrix minVals(1, X.getCols());
CMatrix maxVals(1, X.getCols());
X.maxRow(maxVals);
X.minRow(minVals);
int numx=resolution;
int numy=resolution;
double xspan=maxVals.getVal(0, 0)-minVals.getVal(0, 0);
double xdiff=xspan/(numx-1);
double yspan= maxVals.getVal(0, 1)-minVals.getVal(0, 1);
double ydiff=yspan/(numy-1);
CMatrix Xgrid(numx*numy, 2);
vector<CMatrix*> probOut;
double y = minVals.getVal(0, 1);
double x = 0.0;
for(int i=0; i<numy; y+=ydiff, i++) {
probOut.push_back(new CMatrix(numx, 3));
x=minVals.getVal(0, 0);
for(int j=0; j<numx; x+=xdiff, j++) {
Xgrid.setVal(x, i*numy+j, 0);
probOut[i]->setVal(x, j, 0);
Xgrid.setVal(y, i*numy+j, 1);
probOut[i]->setVal(y, j, 1);
}
}
CMatrix yTest(Xgrid.getRows(), pmodel->getOutputDim());
yTest.ones();
CMatrix probs(yTest.getRows(), yTest.getCols());
//TODO need to fill in for classification pmodel->likelihoods(probs, yTest, Xgrid);
for(int i=0; i<numy; i++)
for(int j=0; j<numx; j++) {
probOut[i]->setVal(probs.getVal(i*numy+j), j, 2);
}
string matrixFile = name + "_prob_matrix.dat";
ofstream out(matrixFile.c_str());
if(!out) throw ndlexceptions::FileWriteError(matrixFile);
out << setiosflags(ios::scientific);
out << setprecision(17);
out << "# Prepared plot of model file " << endl;
for(int i=0; i<numy; i++) {
probOut[i]->toUnheadedStream(out);
out << endl;
}
out.close();
string plotFileName = name + "_plot.gp";
ofstream outGnuplot(plotFileName.c_str());
if(!outGnuplot) throw ndlexceptions::FileWriteError(plotFileName);
outGnuplot << "set nosurface" << endl;
outGnuplot << "set contour base" << endl;
outGnuplot << "set cntrparam levels discrete 0.5" << endl;
outGnuplot << "set table '" << name << "_decision.dat'" << endl;
outGnuplot << "splot \"" << name << "_prob_matrix.dat\"" << endl;
outGnuplot << "set cntrparam levels discrete 0.25, 0.75" << endl;
outGnuplot << "set table '" << name << "_contours.dat'" << endl;
outGnuplot << "splot \"" << name << "_prob_matrix.dat\"" << endl;
outGnuplot << "unset table" << endl;
outGnuplot << "reset" << endl;
writeGnuplotTermSelect(outGnuplot);
writeGnuplotStyleHeader(outGnuplot);
outGnuplot << "plot ";
bool firstPlot = true;
if(numPos>0) {
outGnuplot << "\"" << name << "_positive.dat\" with points ls 5 ps " << pointSize << " title \"positive\"";
firstPlot = false;
}
if(numNeg>0) {
if(!firstPlot) outGnuplot << ", ";
outGnuplot << "\"" << name << "_negative.dat\" with points ls 6 ps " << pointSize << " title \"negative\"";
firstPlot = false;
}
if(!firstPlot) outGnuplot << ", ";
outGnuplot << "\"" << name << "_active_set.dat\" with points ls 4 ps " << pointSize*2 << " title \"active\"";
if(numUnlab>0)
outGnuplot << ", \"" << name << "_unlabelled.dat\" with points ls 7 ps " << pointSize << " title \"unlabelled\"";
outGnuplot << ", \"" << name << "_decision.dat\" with lines ls 8 lw " << lineWidth << " title \"decision\"";
outGnuplot << ", \"" << name << "_contours.dat\" with lines ls 9 lw " << lineWidth << " title \"0.25/0.75\"" << endl;
writeGnuplotFinish(outGnuplot);
outGnuplot.close();
}
else if(pmodel->getNoiseType()=="gaussian") {
switch(pmodel->getApproximationType())
{
case CGp::DTC:
case CGp::DTCVAR:
case CGp::FITC:
case CGp::PITC:
CMatrix scatterActive(pmodel->X_u.getRows(), pmodel->X_u.getCols()+1);
CMatrix scatterOut(pmodel->X_u.getRows(), pmodel->getOutputDim());
pmodel->out(scatterOut, pmodel->X_u);
for(int i=0; i<pmodel->X_u.getRows(); i++)
{
for(int j=0; j<pmodel->X_u.getCols(); j++)
scatterActive.setVal(pmodel->X_u.getVal(i, j), i, j);
scatterActive.setVal(scatterOut.getVal(i, 0), i, pmodel->X_u.getCols());
}
scatterActive.toUnheadedFile(name+"_active_set.dat");
}
CMatrix scatterData(X.getRows(), X.getCols()+1);
for(int i=0; i<X.getRows(); i++)
{
for(int j=0; j<X.getCols(); j++)
{
scatterData.setVal(X.getVal(i, j), i, j);
}
scatterData.setVal(y.getVal(i, 0), i, X.getCols());
}
scatterData.toUnheadedFile(name+"_scatter_data.dat");
CMatrix minVals(1, X.getCols());
CMatrix maxVals(1, X.getCols());
X.maxRow(maxVals);
X.minRow(minVals);
if(pmodel->pX->getCols()==2) // two dimensional inputs
{
int numx=resolution;
int numy=resolution;
double xspan=maxVals.getVal(0, 0)-minVals.getVal(0, 0);
double xdiff=xspan/(numx-1);
double yspan= maxVals.getVal(0, 1)-minVals.getVal(0, 1);
double ydiff=yspan/(numy-1);
CMatrix Xgrid(numx*numy, 2);
vector<CMatrix*> regressOut;