-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathClassificationGAM.m
More file actions
1657 lines (1514 loc) · 62.4 KB
/
ClassificationGAM.m
File metadata and controls
1657 lines (1514 loc) · 62.4 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
## Copyright (C) 2024 Ruchika Sonagote <ruchikasonagote2003@gmail.com>
## Copyright (C) 2024-2025 Andreas Bertsatos <abertsatos@biol.uoa.gr>
## Copyright (C) 2025 Swayam Shah <swayamshah66@gmail.com>
## Copyright (C) 2026 Jayant Chauhan <0001jayant@gmail.com>
##
## This file is part of the statistics package for GNU Octave.
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later
## version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public License along with
## this program; if not, see <http://www.gnu.org/licenses/>.
classdef ClassificationGAM
## -*- texinfo -*-
## @deftp {statistics} ClassificationGAM
##
## Generalized additive model classification
##
## The @code{ClassificationGAM} class implements a gradient boosting algorithm
## for classification, using spline fitting as the weak learner. This
## approach allows the model to capture non-linear relationships between
## predictors and the binary response variable.
##
## Generalized additive model classification is a statistical method that
## extends linear models by allowing non-linear relationships between each
## predictor and the response variable through smooth functions. It combines
## the interpretability of linear models with the flexibility of
## non-parametric methods.
##
## Create a @code{ClassificationGAM} object by using the @code{fitcgam}
## function or the class constructor.
##
## @seealso{fitcgam}
## @end deftp
properties (Access = public)
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} X
##
## Predictor data
##
## A numeric matrix containing the unstandardized predictor data. Each
## column of @var{X} represents one predictor (variable), and each row
## represents one observation. This property is read-only.
##
## @end deftp
X = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} Y
##
## Class labels
##
## Specified as a logical or numeric column vector, or as a character array
## or a cell array of character vectors with the same number of rows as the
## predictor data. Each row in @var{Y} is the observed class label for
## the corresponding row in @var{X}. This property is read-only.
##
## @end deftp
Y = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} NumObservations
##
## Number of observations
##
## A positive integer value specifying the number of observations in the
## training dataset used for training the ClassificationGAM model.
## This property is read-only.
##
## @end deftp
NumObservations = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} RowsUsed
##
## Rows used for fitting
##
## A logical column vector with the same length as the observations in the
## original predictor data @var{X} specifying which rows have been used for
## fitting the ClassificationGAM model. This property is read-only.
##
## @end deftp
RowsUsed = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} NumPredictors
##
## Number of predictors
##
## A positive integer value specifying the number of predictors in the
## training dataset used for training the ClassificationGAM model.
## This property is read-only.
##
## @end deftp
NumPredictors = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} PredictorNames
##
## Names of predictor variables
##
## A cell array of character vectors specifying the names of the predictor
## variables. The names are in the order in which they appear in the
## training dataset. This property is read-only.
##
## @end deftp
PredictorNames = {};
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} ResponseName
##
## Response variable name
##
## A character vector specifying the name of the response variable @var{Y}.
## This property is read-only.
##
## @end deftp
ResponseName = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} ClassNames
##
## Names of classes in the response variable
##
## An array of unique values of the response variable @var{Y}, which has the
## same data types as the data in @var{Y}. This property is read-only.
## @qcode{ClassNames} can have any of the following datatypes:
##
## @itemize
## @item Cell array of character vectors
## @item Character array
## @item Logical vector
## @item Numeric vector
## @end itemize
##
## @end deftp
ClassNames = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} Cost
##
## Cost of Misclassification
##
## A square matrix specifying the cost of misclassification of a point.
## @qcode{Cost(i,j)} is the cost of classifying a point into class @qcode{j}
## if its true class is @qcode{i} (that is, the rows correspond to the true
## class and the columns correspond to the predicted class). The order of
## the rows and columns in @qcode{Cost} corresponds to the order of the
## classes in @qcode{ClassNames}. The number of rows and columns in
## @qcode{Cost} is the number of unique classes in the response. By
## default, @qcode{Cost(i,j) = 1} if @qcode{i != j}, and
## @qcode{Cost(i,j) = 0} if @qcode{i = j}. In other words, the cost is 0
## for correct classification and 1 for incorrect classification.
##
## Add or change the @qcode{Cost} property using dot notation as in:
## @itemize
## @item @qcode{@var{obj}.Cost = @var{costMatrix}}
## @end itemize
##
## @end deftp
Cost = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} Prior
##
## Prior probability for each class
##
## A 2-element numeric vector specifying the prior probabilities for each
## class. The order of the elements in @qcode{Prior} corresponds to the
## order of the classes in @qcode{ClassNames}. This property is read-only.
##
## @end deftp
Prior = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} ScoreTransform
##
## Transformation function for classification scores
##
## Specified as a function handle for transforming the classification
## scores. Add or change the @qcode{ScoreTransform} property using dot
## notation as in:
##
## @itemize
## @item @qcode{@var{obj}.ScoreTransform = 'function_name'}
## @item @qcode{@var{obj}.ScoreTransform = @@function_handle}
## @end itemize
##
## When specified as a character vector, it can be any of the following
## built-in functions. Nevertheless, the @qcode{ScoreTransform} property
## always stores their function handle equivalent.
##
## @multitable @columnfractions 0.2 0.05 0.75
## @headitem @var{Value} @tab @tab @var{Description}
## @item @qcode{"doublelogit"} @tab @tab @math{1 ./ (1 + exp (-2 * x))}
## @item @qcode{"invlogit"} @tab @tab @math{1 ./ (1 + exp (-x))}
## @item @qcode{"ismax"} @tab @tab Sets the score for the class with the
## largest score to 1, and for all other classes to 0
## @item @qcode{"logit"} @tab @tab @math{log (x ./ (1 - x))}
## @item @qcode{"none"} @tab @tab @math{x} (no transformation)
## @item @qcode{"identity"} @tab @tab @math{x} (no transformation)
## @item @qcode{"sign"} @tab @tab @math{-1 for x < 0, 0 for x = 0, 1 for x > 0}
## @item @qcode{"symmetric"} @tab @tab @math{2 * x - 1}
## @item @qcode{"symmetricismax"} @tab @tab Sets the score for the class
## with the largest score to 1, and for all other classes to -1
## @item @qcode{"symmetriclogit"} @tab @tab @math{2 ./ (1 + exp (-x)) - 1}
## @end multitable
##
## @end deftp
ScoreTransform = @(x) x;
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} Formula
##
## Model specification formula
##
## A character vector specifying the model formula using standard Wilkinson
## notation in the form @qcode{"Y ~ terms"}. In addition to basic main
## effects and interactions (@code{+}, @code{:}), it fully supports
## advanced operators including crossing (@code{*}), nesting (@code{/}),
## power/limits (@code{^}), and deletion (@code{-}). The formula is
## evaluated internally via @code{parseWilkinsonFormula}.
## This property is read-only.
##
## @end deftp
Formula = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} Interactions
##
## Interaction terms specification
##
## A logical matrix, positive integer scalar, or character vector
## @qcode{"all"} specifying the interaction terms between predictor
## variables. This property is read-only.
##
## @end deftp
Interactions = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} Knots
##
## Knots for spline fitting
##
## A scalar or row vector specifying the number of knots for each predictor
## variable in the spline fitting. This property is read-only.
##
## @end deftp
Knots = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} Order
##
## Order of spline fitting
##
## A scalar or row vector specifying the order of the spline for each
## predictor variable. This property is read-only.
##
## @end deftp
Order = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} DoF
##
## Degrees of freedom for spline fitting
##
## A scalar or row vector specifying the degrees of freedom for each
## predictor variable in the spline fitting. This property is read-only.
##
## @end deftp
DoF = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} LearningRate
##
## Learning rate for gradient boosting
##
## A scalar value between 0 and 1 specifying the learning rate used in the
## gradient boosting algorithm. This property is read-only.
##
## @end deftp
LearningRate = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} NumIterations
##
## Maximum number of iterations
##
## A positive integer specifying the maximum number of iterations for the
## gradient boosting algorithm. This property is read-only.
##
## @end deftp
NumIterations = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} BaseModel
##
## Base model parameters
##
## A structure containing the parameters of the base model without any
## interaction terms. The base model represents the generalized additive
## model with only the main effects (predictor terms) included.
## This property is read-only.
##
## @end deftp
BaseModel = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} ModelwInt
##
## Model parameters with interactions
##
## A structure containing the parameters of the model that includes
## interaction terms. This model extends the base model by adding
## interaction terms between predictors. This property is read-only.
##
## @end deftp
ModelwInt = [];
## -*- texinfo -*-
## @deftp {ClassificationGAM} {property} IntMatrix
##
## Interaction matrix
##
## A logical matrix or matrix of column indices describing the interaction
## terms applied to the predictor data. This property is read-only.
##
## @end deftp
IntMatrix = [];
endproperties
properties (Access = private, Hidden)
STname = 'none';
endproperties
methods (Hidden)
## Custom display
function display (this)
in_name = inputname (1);
if (! isempty (in_name))
fprintf ('%s =\n', in_name);
endif
disp (this);
endfunction
## Custom display
function disp (this)
fprintf ("\n ClassificationGAM\n\n");
## Print selected properties
fprintf ("%+25s: '%s'\n", 'ResponseName', this.ResponseName);
if (iscellstr (this.ClassNames))
str = repmat ({"'%s'"}, 1, numel (this.ClassNames));
str = strcat ('{', strjoin (str, ' '), '}');
str = sprintf (str, this.ClassNames{:});
elseif (ischar (this.ClassNames))
str = repmat ({"'%s'"}, 1, rows (this.ClassNames));
str = strcat ('[', strjoin (str, ' '), ']');
str = sprintf (str, cellstr (this.ClassNames){:});
else # single, double, logical
str = repmat ({"%d"}, 1, numel (this.ClassNames));
str = strcat ('[', strjoin (str, ' '), ']');
str = sprintf (str, this.ClassNames);
endif
fprintf ("%+25s: %s\n", 'ClassNames', str);
fprintf ("%+25s: '%s'\n", 'ScoreTransform', this.STname);
fprintf ("%+25s: %d\n", 'NumObservations', this.NumObservations);
fprintf ("%+25s: %d\n", 'NumPredictors', this.NumPredictors);
if (! isempty (this.Formula))
fprintf ("%+25s: '%s'\n", 'Formula', this.Formula);
endif
if (! isempty (this.Interactions))
if (ischar (this.Interactions))
fprintf ("%+25s: '%s'\n", 'Interactions', this.Interactions);
else
fprintf ("%+25s: [%dx%d %s]\n", 'Interactions', ...
size (this.Interactions, 1), size (this.Interactions, 2), ...
class (this.Interactions));
endif
endif
endfunction
## Class specific subscripted reference
function varargout = subsref (this, s)
chain_s = s(2:end);
s = s(1);
switch (s.type)
case '()'
error (strcat ("Invalid () indexing for referencing values", ...
" in a ClassificationGAM object."));
case '{}'
error (strcat ("Invalid {} indexing for referencing values", ...
" in a ClassificationGAM object."));
case '.'
if (! ischar (s.subs))
error (strcat ("ClassificationGAM.subsref: '.'", ...
" indexing argument must be a character vector."));
endif
try
out = this.(s.subs);
catch
error (strcat ("ClassificationGAM.subsref:", ...
" unrecognized property: '%s'"), s.subs);
end_try_catch
endswitch
## Chained references
if (! isempty (chain_s))
out = subsref (out, chain_s);
endif
varargout{1} = out;
endfunction
## Class specific subscripted assignment
function this = subsasgn (this, s, val)
if (numel (s) > 1)
error (strcat ("ClassificationGAM.subsasgn:", ...
" chained subscripts not allowed."));
endif
switch s.type
case '()'
error (strcat ("Invalid () indexing for assigning values", ...
" to a ClassificationGAM object."));
case '{}'
error (strcat ("Invalid {} indexing for assigning values", ...
" to a ClassificationGAM object."));
case '.'
if (! ischar (s.subs))
error (strcat ("ClassificationGAM.subsasgn: '.'", ...
" indexing argument must be a character vector."));
endif
switch (s.subs)
case 'Cost'
this = setCost (this, val);
case 'ScoreTransform'
name = "ClassificationGAM";
[this.ScoreTransform, this.STname] = parseScoreTransform ...
(varargin{2}, name);
otherwise
error (strcat ("ClassificationGAM.subsasgn:", ...
" unrecognized or read-only property: '%s'"), ...
s.subs);
endswitch
endswitch
endfunction
endmethods
methods (Access = public)
## -*- texinfo -*-
## @deftypefn {statistics} {@var{obj} =} ClassificationGAM (@var{X}, @var{Y})
## @deftypefnx {statistics} {@var{obj} =} ClassificationGAM (@dots{}, @var{name}, @var{value})
##
## Create a @qcode{ClassificationGAM} class object containing a generalized
## additive classification model.
##
## @code{@var{obj} = ClassificationGAM (@var{X}, @var{Y})} returns
## a ClassificationGAM object, with @var{X} as the predictor data
## and @var{Y} containing the class labels of observations in @var{X}.
##
## @itemize
## @item
## @code{X} must be a @math{NxP} numeric matrix of input data where rows
## correspond to observations and columns correspond to features or
## variables. @var{X} will be used to train the GAM model.
## @item
## @code{Y} is @math{Nx1} matrix or cell matrix containing the class labels
## of corresponding predictor data in @var{X}. @var{Y} can contain any type
## of categorical data. @var{Y} must have the same number of rows as
## @var{X}.
## @end itemize
##
## @code{@var{obj} = ClassificationGAM (@dots{}, @var{name},
## @var{value})} returns a ClassificationGAM object with parameters
## specified by the following @qcode{@var{name}, @var{value}} paired input
## arguments:
##
## @multitable @columnfractions 0.18 0.02 0.8
## @headitem @var{Name} @tab @tab @var{Value}
##
## @item @qcode{'PredictorNames'} @tab @tab A cell array of character
## vectors specifying the names of the predictors. The length of this array
## must match the number of columns in @var{X}.
##
## @item @qcode{'ResponseName'} @tab @tab A character vector specifying the
## name of the response variable.
##
## @item @qcode{'ClassNames'} @tab @tab Names of the classes in the class
## labels, @var{Y}, used for fitting the GAM model.
## @qcode{ClassNames} are of the same type as the class labels in @var{Y}.
##
## @item @qcode{'Cost'} @tab @tab An @math{NxR} numeric matrix containing
## misclassification cost for the corresponding instances in @var{X}, where
## @math{R} is the number of unique categories in @var{Y}. If an instance
## is correctly classified into its category the cost is calculated to be 1,
## otherwise 0. The cost matrix can be altered by using
## @code{@var{Mdl}.cost = somecost}. By default, its value is
## @qcode{@var{cost} = ones (rows (X), numel (unique (Y)))}.
##
## @item @qcode{'Prior'} @tab @tab A numeric vector specifying the prior
## probabilities for each class. The order of the elements in @qcode{Prior}
## corresponds to the order of the classes in @qcode{ClassNames}.
## Alternatively, you can specify @qcode{"empirical"} to use the empirical
## class probabilities or @qcode{"uniform"} to assume equal class
## probabilities.
##
## @item @qcode{'ScoreTransform'} @tab @tab A user-defined function handle
## or a character vector specifying one of the following builtin functions
## specifying the transformation applied to predicted classification scores.
## Supported values include @qcode{'doublelogit'}, @qcode{'invlogit'},
## @qcode{'ismax'}, @qcode{'logit'}, @qcode{'none'}, @qcode{'identity'},
## @qcode{'sign'}, @qcode{'symmetric'}, @qcode{'symmetricismax'}, and
## @qcode{'symmetriclogit'}.
##
## @item @qcode{'Formula'} @tab @tab A character vector specifying the model
## formula using standard Wilkinson notation in the form @qcode{"Y ~ terms"}.
## In addition to basic main effects and interactions (@code{+}, @code{:}),
## it supports advanced operators including crossing (@code{*}), nesting
## (@code{/}), power/limits (@code{^}), and deletion (@code{-}).
##
## @item @qcode{'Interactions'} @tab @tab A logical matrix, a positive
## integer scalar, or the string @qcode{"all"} for defining the interactions
## between predictor variables.
##
## @item @qcode{'Knots'} @tab @tab A scalar or row vector specifying the
## number of knots for each predictor variable in the spline fitting.
##
## @item @qcode{'Order'} @tab @tab A scalar or row vector specifying the
## order of the spline for each predictor variable.
##
## @item @qcode{'DoF'} @tab @tab A scalar or row vector specifying the
## degrees of freedom for each predictor variable in the spline fitting.
##
## @item @qcode{'LearningRate'} @tab @tab A scalar value between 0 and 1
## specifying the learning rate used in the gradient boosting algorithm.
##
## @item @qcode{'NumIterations'} @tab @tab A positive integer specifying
## the maximum number of iterations for the gradient boosting algorithm.
## @end multitable
##
## @seealso{fitcgam}
## @end deftypefn
function this = ClassificationGAM (X, Y, varargin)
## Check for sufficient number of input arguments
if (nargin < 2)
error ("ClassificationGAM: too few input arguments.");
endif
## Check X and Y have the same number of observations
if (rows (X) != rows (Y))
error ("ClassificationGAM: number of rows in X and Y must be equal.");
endif
nsample = rows (X);
ndims_X = columns (X);
## Assign original X and Y data
this.X = X;
this.Y = Y;
## Get groups in Y
[gY, gnY, glY] = grp2idx (Y);
## Set default values before parsing optional parameters
PredictorNames = {};
ResponseName = [];
Formula = [];
Interactions = [];
ClassNames = [];
Prior = "empirical";
DoF = ones (1, ndims_X) * 8;
Order = ones (1, ndims_X) * 3;
Knots = ones (1, ndims_X) * 5;
LearningRate = 0.1;
NumIterations = 100;
Cost = [];
## Number of parameters for Knots, DoF, Order (maximum 2 allowed)
KOD = 0;
## Number of parameters for Formula, Interactions (maximum 1 allowed)
F_I = 0;
## Parse extra parameters
while (numel (varargin) > 0)
switch (tolower (varargin {1}))
case "predictornames"
PredictorNames = varargin{2};
if (! iscellstr (PredictorNames))
error (strcat ("ClassificationGAM: 'PredictorNames'", ...
" must be supplied as a cellstring array."));
elseif (numel (PredictorNames) != columns (X))
error (strcat ("ClassificationGAM: 'PredictorNames'", ...
" must equal the number of columns in X."));
endif
case "responsename"
ResponseName = varargin{2};
if (! ischar (ResponseName))
error (strcat ("ClassificationGAM: 'ResponseName'", ...
" must be a character vector."));
endif
case "classnames"
ClassNames = varargin{2};
if (! (iscellstr (ClassNames) || isnumeric (ClassNames) ||
islogical (ClassNames) || ischar (ClassNames)))
error (strcat ("ClassificationGAM: 'ClassNames' must be a", ...
" cell array of character vectors, a logical", ...
" vector, a numeric vector, or a character array."));
endif
## Check that all class names are available in gnY
if (iscellstr (ClassNames) || ischar (ClassNames))
ClassNames = cellstr (ClassNames);
if (! all (cell2mat (cellfun (@(x) any (strcmp (x, gnY)),
ClassNames, "UniformOutput", false))))
error (strcat ("ClassificationGAM: not all 'ClassNames'", ...
" are present in Y."));
endif
else
if (! all (cell2mat (arrayfun (@(x) any (x == glY),
ClassNames, "UniformOutput", false))))
error (strcat ("ClassificationGAM: not all 'ClassNames'", ...
" are present in Y."));
endif
endif
case "prior"
Prior = varargin{2};
if (! (isnumeric (Prior) || ischar (Prior)))
error (strcat ("ClassificationGAM: 'Prior' must be", ...
" a numeric vector or a string."));
endif
if (ischar (Prior) && ! any (strcmpi (Prior, {"empirical", "uniform"})))
error (strcat ("ClassificationGAM: 'Prior' must be", ...
" 'empirical', 'uniform', or a numeric vector."));
endif
if (isnumeric (Prior) && numel (Prior) != 2)
error ("ClassificationGAM: 'Prior' must be a 2-element vector.");
endif
case "cost"
Cost = varargin{2};
if (! (isnumeric (Cost) && issquare (Cost)))
error (strcat ("ClassificationGAM: 'Cost' must be", ...
" a numeric square matrix."));
endif
case "scoretransform"
name = "ClassificationGAM";
[this.ScoreTransform, this.STname] = parseScoreTransform ...
(varargin{2}, name);
case "formula"
if (F_I < 1)
Formula = varargin{2};
if (! ischar (Formula) && ! islogical (Formula))
error ("ClassificationGAM: 'Formula' must be a string.");
endif
F_I += 1;
else
error (strcat ("ClassificationGAM: 'Interactions'", ...
" have already been defined."));
endif
case "interactions"
if (F_I < 1)
tmp = varargin{2};
if (isnumeric (tmp) && isscalar (tmp)
&& tmp == fix (tmp) && tmp >= 0)
Interactions = tmp;
elseif (islogical (tmp))
Interactions = tmp;
elseif (ischar (tmp) && strcmpi (tmp, "all"))
Interactions = tmp;
else
error ("ClassificationGAM: invalid 'Interactions' parameter.");
endif
F_I += 1;
else
error ("ClassificationGAM: 'Formula' has already been defined.");
endif
case "knots"
if (KOD < 2)
Knots = varargin{2};
if (! isnumeric (Knots) || ! (isscalar (Knots) ||
isequal (size (Knots), [1, ndims_X])))
error ("ClassificationGAM: invalid value for 'Knots'.");
endif
DoF = Knots + Order;
Order = DoF - Knots;
KOD += 1;
else
error (strcat ("ClassificationGAM: 'DoF' and 'Order'", ...
" have been set already."));
endif
case "order"
if (KOD < 2)
Order = varargin{2};
if (! isnumeric (Order) || ! (isscalar (Order) ||
isequal (size (Order), [1, ndims_X])))
error ("ClassificationGAM: invalid value for 'Order'.");
endif
DoF = Knots + Order;
Knots = DoF - Order;
KOD += 1;
else
error (strcat ("ClassificationGAM: 'DoF' and 'Knots'", ...
" have been set already."));
endif
case "dof"
if (KOD < 2)
DoF = varargin{2};
if (! isnumeric (DoF) ||
! (isscalar (DoF) || isequal (size (DoF), [1, ndims_X])))
error ("ClassificationGAM: invalid value for 'DoF'.");
endif
Knots = DoF - Order;
Order = DoF - Knots;
KOD += 1;
else
error (strcat ("ClassificationGAM: 'Knots' and 'Order'", ...
" have been set already."));
endif
case "learningrate"
LearningRate = varargin{2};
if (LearningRate > 1 || LearningRate <= 0)
error (strcat ("ClassificationGAM: 'LearningRate'", ...
" must be between 0 and 1."));
endif
case "numiterations"
NumIterations = varargin{2};
if (! isnumeric (NumIterations) || NumIterations <= 0)
error (strcat ("ClassificationGAM: 'NumIterations'", ...
" must be a positive integer value."));
endif
otherwise
error (strcat ("ClassificationGAM: invalid parameter", ...
" name in optional pair arguments."));
endswitch
varargin (1:2) = [];
endwhile
## Generate default predictors and response variable names (if necessary)
if (isempty (PredictorNames))
for i = 1:columns (X)
PredictorNames {i} = strcat ("x", num2str (i));
endfor
endif
if (isempty (ResponseName))
ResponseName = "Y";
endif
## Assign predictors and response variable names
this.PredictorNames = PredictorNames;
this.ResponseName = ResponseName;
## Handle class names
if (! isempty (ClassNames))
if (iscellstr (ClassNames))
ru = find (! ismember (gnY, ClassNames));
else
ru = find (! ismember (glY, ClassNames));
endif
for i = 1:numel (ru)
gY(gY == ru(i)) = NaN;
endfor
endif
## Remove nans from X and Y
RowsUsed = ! logical (sum (isnan ([X, gY]), 2));
Y = Y (RowsUsed);
X = X (RowsUsed, :);
## Renew groups in Y
[gY, gnY, glY] = grp2idx (Y);
this.ClassNames = gnY;
## Check that we are dealing only with binary classification
if (numel (gnY) > 2)
error ("ClassificationGAM: can only be used for binary classification.");
endif
## Force Y into numeric
if (! isnumeric (Y))
Y = gY - 1;
endif
this.NumObservations = rows (X);
this.RowsUsed = cast (RowsUsed, "double");
## Assign the number of original predictors to the ClassificationGAM object
this.NumPredictors = ndims_X;
## Assign Cost and compute Prior
this = setCost (this, Cost, gnY);
if (ischar (Prior))
if (strcmpi (Prior, "uniform"))
this.Prior = [0.5, 0.5];
elseif (strcmpi (Prior, "empirical"))
counts = histc (gY, 1:2);
this.Prior = counts / sum (counts);
endif
else
## Numeric prior - normalize to sum to 1
this.Prior = Prior / sum (Prior);
endif
## Assign remaining optional parameters
this.Formula = Formula;
this.Interactions = Interactions;
this.Knots = Knots;
this.Order = Order;
this.DoF = DoF;
this.LearningRate = LearningRate;
this.NumIterations = NumIterations;
## Fit the basic model
Inter = mean (Y);
[iter, param, res, RSS, intercept] = this.fitGAM (X, Y, Inter, Knots, ...
Order, LearningRate, ...
NumIterations);
this.BaseModel.Intercept = intercept;
this.BaseModel.Parameters = param;
this.BaseModel.Iterations = iter;
this.BaseModel.Residuals = res;
this.BaseModel.RSS = RSS;
## Handle interaction terms (if given)
if (F_I > 0)
if (isempty (this.Formula))
## Analyze Interactions optional parameter
this.IntMatrix = this.parseInteractions ();
## Append interaction terms to the predictor matrix
for i = 1:rows (this.IntMatrix)
tindex = logical (this.IntMatrix(i,:));
Xterms = X(:,tindex);
Xinter = ones (this.NumObservations, 1);
for c = 1:sum (tindex)
Xinter = Xinter .* Xterms(:,c);
endfor
## Append interaction terms
X = [X, Xinter];
endfor
else
## Analyze Formula optional parameter
this.IntMatrix = this.parseFormula ();
## Add selected predictors and interaction terms
XN = [];
for i = 1:rows (this.IntMatrix)
tindex = logical (this.IntMatrix(i,:));
Xterms = X(:,tindex);
Xinter = ones (this.NumObservations, 1);
for c = 1:sum (tindex)
Xinter = Xinter .* Xterms(:,c);
endfor
## Append selected predictors and interaction terms
XN = [XN, Xinter];
endfor
X = XN;
endif
## Update length of Knots, Order, and DoF vectors to match
## the columns of X with the interaction terms
Knots = ones (1, columns (X)) * Knots(1); # Knots
Order = ones (1, columns (X)) * Order(1); # Order of spline
DoF = ones (1, columns (X)) * DoF(1); # Degrees of freedom
## Fit the model with interactions
[iter, param, res, RSS, intercept] = this.fitGAM (X, Y, Inter, Knots, ...
Order, LearningRate, ...
NumIterations);
this.ModelwInt.Intercept = intercept;
this.ModelwInt.Parameters = param;
this.ModelwInt.Iterations = iter;
this.ModelwInt.Residuals = res;
this.ModelwInt.RSS = RSS;
endif
endfunction
## -*- texinfo -*-
## @deftypefn {ClassificationGAM} {@var{label} =} predict (@var{obj}, @var{XC})
## @deftypefnx {ClassificationGAM} {[@var{label}, @var{score}] =} predict (@var{obj}, @var{XC})
## @deftypefnx {ClassificationGAM} {[@var{label}, @var{score}] =} predict (@dots{}, @qcode{'IncludeInteractions'}, @var{includeInteractions})
##
## Predict labels for new data using the Generalized Additive Model (GAM)
## stored in a ClassificationGAM object.
##
## @code{@var{label} = predict (@var{obj}, @var{XC})} returns the predicted
## labels for the data in @var{XC} based on the model stored in the
## ClassificationGAM object, @var{obj}.
##
## @code{[@var{label}, @var{score}] = predict (@var{obj}, @var{XC})} also
## returns @var{score}, which contains the predicted class scores or
## posterior probabilities for each observation.
##
## @code{[@var{label}, @var{score}] = predict (@var{obj}, @var{XC},
## 'IncludeInteractions', @var{includeInteractions})} allows you to specify
## whether interaction terms should be included when making predictions.
##
## @itemize
## @item
## @var{obj} must be a @qcode{ClassificationGAM} class object.
## @item
## @var{XC} must be an @math{MxP} numeric matrix where each row is an
## observation and each column corresponds to a predictor variable.
## @item
## @var{includeInteractions} is a logical scalar indicating whether to
## include interaction terms in the predictions.
## @end itemize
##
## @seealso{ClassificationGAM, fitcgam}
## @end deftypefn
function [labels, scores] = predict (this, XC, varargin)
## Check for sufficient input arguments
if (nargin < 2)
error ("ClassificationGAM.predict: too few input arguments.");
endif
## Check for valid XC
if (isempty (XC))
error ("ClassificationGAM.predict: XC is empty.");
elseif (this.NumPredictors != columns (XC))
error (strcat ("ClassificationGAM.predict:", ...
" XC must have the same number of", ...
" predictors as the trained model."));
endif
## Clean XC data
notnansf = ! logical (sum (isnan (XC), 2));
XC = XC (notnansf, :);
## Default values for Name-Value Pairs
incInt = ! isempty (this.IntMatrix);
Cost = this.Cost;
## Parse optional arguments
while (numel (varargin) > 0)
switch (tolower (varargin {1}))
case "includeinteractions"
tmpInt = varargin{2};
if (! islogical (tmpInt) || (tmpInt != 0 && tmpInt != 1))
error (strcat ("ClassificationGAM.predict:", ...
" includeinteractions must be a logical value."));
endif
## Check model for interactions
if (tmpInt && isempty (this.IntMatrix))
error (strcat ("ClassificationGAM.predict: trained model", ...
" does not include any interactions."));
endif
incInt = tmpInt;
otherwise
error (strcat ("ClassificationGAM.predict: invalid NAME in", ...
" optional pairs of arguments."));
endswitch
varargin (1:2) = [];
endwhile
## Choose whether interactions must be included
if (incInt)
if (! isempty (this.Interactions))
## Append interaction terms to the predictor matrix
for i = 1:rows (this.IntMatrix)
tindex = logical (this.IntMatrix(i,:));
Xterms = XC(:,tindex);
Xinter = ones (rows (XC), 1);
for c = 1:sum (tindex)
Xinter = Xinter .* Xterms(:,c);
endfor
## Append interaction terms
XC = [XC, Xinter];
endfor
else
## Add selected predictors and interaction terms
XN = [];
for i = 1:rows (this.IntMatrix)
tindex = logical (this.IntMatrix(i,:));