-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfreq_cat_onln_gfmm.py
More file actions
1543 lines (1339 loc) · 76.4 KB
/
freq_cat_onln_gfmm.py
File metadata and controls
1543 lines (1339 loc) · 76.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
"""
General fuzzy min-max neural network trained by the batch incremental
learning algorithm, in which categorical features are encoded using
the ordinal encoding method and the similarity among categorical
values are computed using their frequency of occurence with respect to all
class labels in a training set.
"""
# @Author: Thanh Tung KHUAT <thanhtung09t2@gmail.com>
# License: GPL-3.0
import numpy as np
import pandas as pd
import time
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import OrdinalEncoder
from hbbrain.base.base_estimator import BaseHyperboxClassifier
from hbbrain.base.base_gfmm_estimator import (
convert_format_missing_input_zero_one,
is_contain_missing_value,
)
from hbbrain.utils.membership_calc import (
membership_func_freq_cat_gfmm,
get_membership_freq_cat_gfmm_all_classes,
)
from hbbrain.utils.adjust_hyperbox import (
overlap_resolving_num_data,
is_two_hyperboxes_overlap_num_data_general,
hyperbox_overlap_test_freq_cat_gfmm,
hyperbox_contraction_freq_cat_gfmm,
)
from hbbrain.utils.dist_metrics import (
manhattan_distance,
manhattan_distance_with_missing_val,
)
from hbbrain.utils.matrix_transformation import hashing, hashing_mat
from hbbrain.constants import UNLABELED_CLASS, DEFAULT_CATEGORICAL_VALUE
def ordinal_encode_categorical_features(X, categorical_features, encoder=None):
"""
Encode categorical features as an integer array.
Parameters
----------
X : array-like of shape (n_samples, n_features)
An input data matrix includes both continuous and categorical features.
categorical_features : a list of integer
Indices of categorical features in `X`.
encoder : sklearn.preprocessing.OrdinalEncoder, optional, default=None
An existing ordinal encoder is used to encode categorical features.
Returns
-------
X : array-like of shape (n_samples, n_features)
An input data matrix with the encoded categorical features.
encoder : sklearn.preprocessing.OrdinalEncoder
An ordinal encoder was used to encode categorical features.
"""
X_cat = X[:, categorical_features]
id_missing_values = pd.isna(X_cat)
if id_missing_values.any() == True:
X_cat[id_missing_values] = DEFAULT_CATEGORICAL_VALUE
if encoder is None:
encoder = OrdinalEncoder()
encoder.fit(X_cat)
X_cat_trans = encoder.transform(X_cat)
if id_missing_values.any() == True:
X_cat_trans[id_missing_values] = DEFAULT_CATEGORICAL_VALUE
X_trans = X.copy()
X_trans[:, categorical_features] = X_cat_trans
return X_trans, encoder
def compute_similarity_among_categorical_values(X_cat, y):
"""
Compute the similarity among pairs of categorical values
for each categorical feature.
Parameters
----------
X_cat : array-like of shape (n_samples, n_cat_features)
Input patterns contain only categorical features.
y : array-like of shape (n_samples, )
The class label corresponds to each input pattern.
Returns
-------
similarity_of_cat_vals : array-like of shape (n_cat_features,)
An array stores all similarity values among all pairs of categorical values
for each categorical feature index. Each element in this array is an dictionary
with keys being a hashed value of two categorical values and values of this
dictionary being a similarity value.
"""
similarity_of_cat_vals = np.full(X_cat.shape[1], None, dtype=np.object)
unique_cls = np.unique(y)
for i in range(X_cat.shape[1]):
# Get unique values in each categorical feature
cat_vals = np.unique(X_cat[:, i])
if len(cat_vals) > 2:
# return the number of elements for each class
# corresponding to each unique categorical value
store_prob_freq = {}
for cat_val in cat_vals:
cat_vals_cls, cat_vals_count = np.unique(y[X_cat[:, i] == cat_val], return_counts=True)
if len(cat_vals_cls) == len(unique_cls):
store_prob_freq[cat_val] = cat_vals_count / np.sum(cat_vals_count)
else:
# if a class with no categorical feature values, then cat_vals_cls does not contain
# that class id, and so we need to add probability values of zeros manually.
prob_cat_features = np.full(len(unique_cls), 0)
for cls_id, cls_val in enumerate(unique_cls):
count_cls_ele = cat_vals_count[cat_vals_cls == cls_val]
if len(count_cls_ele) > 0:
prob_cat_features[cls_id] = count_cls_ele[0]
store_prob_freq[cat_val] = prob_cat_features / np.sum(prob_cat_features)
# compute the similarity among categorical values for each categorical feature
sim_cat_vals_each_feature = {}
cat_vals_keys = np.fromiter(store_prob_freq.keys(), dtype=np.int)
for j in range(len(cat_vals_keys)):
sim_cat_vals_each_feature[hashing(cat_vals_keys[j], DEFAULT_CATEGORICAL_VALUE)] = 0
for k in range(j, len(cat_vals_keys)):
sim_cat_vals_each_feature[hashing(cat_vals_keys[j], cat_vals_keys[k])] = np.linalg.norm(store_prob_freq[cat_vals_keys[j]] - store_prob_freq[cat_vals_keys[k]])
max_val = max(sim_cat_vals_each_feature.values())
sim_cat_vals_each_feature = {k: v/max_val for k, v in sim_cat_vals_each_feature.items()}
similarity_of_cat_vals[i] = sim_cat_vals_each_feature
else:
sim_cat_vals_each_feature = {}
sim_cat_vals_each_feature[hashing(cat_vals[0], cat_vals[0])] = 0
sim_cat_vals_each_feature[hashing(cat_vals[1], cat_vals[1])] = 0
sim_cat_vals_each_feature[hashing(cat_vals[0], DEFAULT_CATEGORICAL_VALUE)] = 0
sim_cat_vals_each_feature[hashing(cat_vals[1], DEFAULT_CATEGORICAL_VALUE)] = 0
sim_cat_vals_each_feature[hashing(cat_vals[0], cat_vals[1])] = 1
similarity_of_cat_vals[i] = sim_cat_vals_each_feature
return similarity_of_cat_vals
def predict_freq_cat_feature_manhanttan(V, W, E, F, C, Xl, Xu, X_cat, similarity_of_cat_vals, g=1):
"""
Predict class labels for samples in the form of hyperboxes with continuous
features represented by low bounds `Xl` and upper bounds `Xu` and categorical
features stored in `X_cat`. The predicted results will be computed from
existing hyperboxes with continuous features matrices for lower bounds `V`
and upper bounds `W` and categorical features matrices for lower bounds `E`
and upper bounds `F`.
.. note::
In the case there are many winner hyperboxes representing different
class labels but with the same membership value with respect to the
input pattern :math:`X_i` in the form of an hyperbox represented by a
lower bound :math:`Xl_i` and an upper bound :math:`Xu_i` for continous
features and a matrix :math:`Xcat_i` for categorical features, an
additional criterion based on the minimum Manhattan distance between
the central point of continous features in the input hyperbox
:math:`X_i = [Xl_i, Xu_i]` and the central points of continous features
in winner hyperboxes are used to find the final winner hyperbox that
its class label is used for predicting the class label of the input
hyperbox :math:`X_i`.
.. warning::
Another important point to pay attention is that the categorical
features storing in :math:`X_cat` need to be encoded by using the
function :func:`ordinal_encode_categorical_features` before pushing the
values to this method.
Parameters
----------
V : array-like of shape (n_hyperboxes, n_continuous_features)
A matrix stores all minimal points for all continuous features of all
hyperboxes of a trained hyperbox-based model, in which each row is a
minimal point of a hyperbox.
W : array-like of shape (n_hyperboxes, n_continuous_features)
A matrix stores all maximal points for all continuous features of all
hyperboxes of a trained hyperbox-based model, in which each row is a
maximal point of a hyperbox.
E : array-like of shape (n_hyperboxes, n_cat_features)
A matrix stores all lower bounds for all categorical features of all
hyperboxes of a trained hyperbox-based model, in which each row is a
lower bound for categorical features of a hyperbox.
F : array-like of shape (n_hyperboxes, n_cat_features)
A matrix stores all upper bounds for all categorical features of all
hyperboxes of a trained hyperbox-based model, in which each row is a
upper bound for categorical features of a hyperbox.
C : array-like of shape (n_hyperboxes,)
An array contains all class lables for all hyperboxes of a trained
hyperbox-based model.
Xl : array-like of shape (n_samples, n_continuous_features)
The data matrix contains lower bounds for continuous features of input
patterns for which we want to predict the targets.
Xu : array-like of shape (n_samples, n_continuous_features)
The data matrix contains upper bounds for continuous features of input
patterns for which we want to predict the targets.
X_cat : array-like of shape (n_samples, n_cat_features)
The data matrix contains categorical bounds for categorical features
of input patterns for which we want to predict the targets.
similarity_of_cat_vals : array-like of shape (n_cat_features,)
An array stores all similarity values among all pairs of categorical
values for each categorical feature index. Each element in this array
is an dictionary with keys being a hashed value of two categorical
values and values of this dictionary being a similarity value.
g : float or array-like of shape (n_features,), optional, default=1
A sensitivity parameter describing the speed of decreasing of the
membership function in each continuous dimension.
Returns
-------
y_pred : array-like of shape (n_samples,)
Predicted class labels for all input patterns.
"""
if Xl is not None:
if Xl.ndim == 1:
Xl = Xl.reshape(1, -1)
if Xu.ndim == 1:
Xu = Xu.reshape(1, -1)
if is_contain_missing_value(Xl) == True or is_contain_missing_value(Xu) == True:
Xl, Xu, _ = convert_format_missing_input_zero_one(Xl, Xu)
if X_cat is not None:
if X_cat.ndim == 1:
X_cat = X_cat.reshape(1, -1)
if Xl is not None:
n_samples = Xl.shape[0]
else:
n_samples = X_cat.shape[0]
if V is not None:
is_exist_missing_continous_value = (V > W).any()
else:
is_exist_missing_continous_value = False
y_pred = np.full(n_samples, 0)
sample_id = 0
np.random.seed(0)
for i in range(n_samples):
if (Xl is not None) and (X_cat is not None):
if not is_exist_missing_continous_value:
mem_vals = membership_func_freq_cat_gfmm(Xl[i], Xu[i], X_cat[i], V, W, E, F, similarity_of_cat_vals, g)
else:
mem_vals = membership_func_freq_cat_gfmm(Xl[i], Xu[i], X_cat[i], np.minimum(V, W), np.maximum(W, V), E, F, similarity_of_cat_vals, g)
else:
if Xl is not None:
if not is_exist_missing_continous_value:
mem_vals = membership_func_freq_cat_gfmm(Xl[i], Xu[i], None, V, W, E, F, similarity_of_cat_vals, g)
else:
mem_vals = membership_func_freq_cat_gfmm(Xl[i], Xu[i], None, np.minimum(V, W), np.maximum(W, V), E, F, similarity_of_cat_vals, g)
else:
mem_vals = membership_func_freq_cat_gfmm(None, None, X_cat[i], V, W, E, F, similarity_of_cat_vals, g)
bmax = mem_vals.max()
if (Xl is not None) and (((Xl[i] < 0).any() == True) or ((Xu[i] > 1).any() == True)):
print(">>> The testing sample %d with the coordinate %s is outside the range [0, 1]. Membership value = %f. The prediction is more likely incorrect." %(sample_id, Xl[i], bmax))
# get indices of all hyperboxes with max membership
max_mem_box_ids = np.nonzero(mem_vals == bmax)[0]
winner_cls = np.unique(C[max_mem_box_ids])
if len(winner_cls) > 1:
if Xl is None:
y_pred[i] = np.random.choice(winner_cls, 1, False)[0]
else:
if ((Xl[i] > Xu[i]).any() == True) or ((V[max_mem_box_ids] > W[max_mem_box_ids]).any() == True):
maht_dist = manhattan_distance_with_missing_val(Xl[i], Xu[i], V[max_mem_box_ids], W[max_mem_box_ids])
else:
if (Xl[i] == Xu[i]).all() == False:
Xl_mat = np.ones((len(max_mem_box_ids), 1)) * Xl[i]
Xu_mat = np.ones((len(max_mem_box_ids), 1)) * Xu[i]
Xg_mat = (Xl_mat + Xu_mat) / 2
else:
Xg_mat = np.ones((len(max_mem_box_ids), 1)) * Xl[i]
# Find all average points of all hyperboxes with the same membership value
avg_point_mat = (V[max_mem_box_ids] + W[max_mem_box_ids]) / 2
# compute the manhattan distance from XgT_mat to all average points of all hyperboxes with the same membership value
maht_dist = manhattan_distance(avg_point_mat, Xg_mat)
id_min_dist = maht_dist.argmin()
y_pred[i] = C[max_mem_box_ids[id_min_dist]]
else:
y_pred[i] = C[max_mem_box_ids[0]]
return y_pred
class FreqCatOnlineGFMM(BaseHyperboxClassifier):
"""Batch Incremental learning algorithm with mixed-attribute data for a
general fuzzy min-max neural network, in which categorical features are
encoded using the ordinal encoding method and the similarity degrees among
categorical values are computed using their frequency of occurence with
respect to all class labels in a training set.
This algorithm uses a distance measure between any two values of a categorical
variable based on the occurrence probability of such categorical values with
respect to the values of the class variable. This distance is then normalised
and used to compute the membership values for categorical features in conjunction
with membership values of continuous features to generate the final membership
values for mixed-attribute data.
See [1]_ for more detailed information regarding this batch incremental
learning algorithm.
Parameters
----------
theta : float, optional, default=0.5
Maximum hyperbox size for continuous features.
theta_min : float, optional, default=1
Minimum value of the maximum hyperbox size for continuous features so
that the training loop is still performed. If the value of `theta_min`
is larger than the value of `theta`, it will be automatically assigned
a value equal to `theta`.
gamma : float or ndarray of shape (n_continuous_features,), optional, default=1
A sensitivity parameter describing the speed of decreasing of the
membership function in each continuous feature.
eta : float, optional, default=0.5
Maximum hyperbox size for the categorical features.
alpha : float, optional, default=0.9
Multiplier factor to reduce the value of maximum hyperbox size after
each training loop.
V : array-like of shape (n_hyperboxes, n_continuous_features)
A matrix stores all minimal points for continuous features of all
existing hyperboxes, in which each row is a minimal point of a hyperbox.
W : array-like of shape (n_hyperboxes, n_continuous_features)
A matrix stores all maximal points for continuous features of all
existing hyperboxes, in which each row is a minimal point of a hyperbox.
E : array-like of shape (n_hyperboxes, n_cat_features)
A matrix stores all lower bounds for categorical features of all
existing hyperboxes, in which each row is a lower bound of a hyperbox.
F : array-like of shape (n_hyperboxes, n_cat_features)
A matrix stores all upper bounds for categorical features of all
existing hyperboxes, in which each row is an upper bound of a hyperbox.
C : array-like of shape (n_hyperboxes,)
A vector stores all class labels correponding to existing hyperboxes.
Attributes
----------
similarity_of_cat_vals : array-like of shape (n_cat_features,)
An array stores all similarity values among all pairs of categorical values
for each categorical feature index. Each element in this array is an dictionary
with keys being a hashed value of two categorical values and values of this
dictionary being a similarity value.
categorical_features_ : int array of shape (n_cat_features,)
Indices of categorical features in the training data and hyperboxes.
continuous_features_ : int array of shape (n_continuous_features,)
Indices of continuous features in the training data and hyperboxes.
encoder_ : sklearn.preprocessing.OrdinalEncoder
An ordinal encoder was used to encode categorical features.
is_exist_continuous_missing_value : boolean
Is there any missing values in continuous features in the training data.
elapsed_training_time : float
Training time in seconds.
n_passes : int
Number of training loops.
References
----------
.. [1] T. T. Khuat and B. Gabrys "An in-depth comparison of methods handling
mixed-attribute data for general fuzzy min–max neural network",
Neurocomputing, vol 464, pp. 175-202, 2021.
Examples
--------
>>> from hbbrain.mixed_data.freq_cat_onln_gfmm import FreqCatOnlineGFMM
>>> from hbbrain.datasets import load_japanese_credit
>>> X, y = load_japanese_credit()
>>> from sklearn.preprocessing import MinMaxScaler
>>> scaler = MinMaxScaler()
>>> numerical_features = [1, 2, 7, 10, 13, 14]
>>> categorical_features = [0, 3, 4, 5, 6, 8, 9, 11, 12]
>>> scaler.fit(X[:, numerical_features])
MinMaxScaler()
>>> X[:, numerical_features] = scaler.transform(X[:, numerical_features])
>>> clf = FreqCatOnlineGFMM(theta=0.1, eta=0.6)
>>> clf.fit(X, y, categorical_features)
>>> print("Number of hyperboxes = %d"%clf.get_n_hyperboxes())
Number of hyperboxes = 416
>>> clf.predict(X[[10, 100]])
array([1, 0])
"""
def __init__(self, theta=0.5, theta_min=1, eta=0.5, gamma=1, alpha=0.9, V=None, W=None, E=None, F=None, C=None):
BaseHyperboxClassifier.__init__(self, theta, False, V, W, C)
if E is not None:
self.E = E
else:
self.E = np.array([])
if F is not None:
self.F = F
else:
self.F = np.array([])
self.gamma = gamma
self.theta_min = theta_min
self.alpha = alpha
self.eta = eta
def _validate_data(self):
"""
Validate the initial values for parameters and initialise default
values for parameters.
Returns
-------
None.
"""
if self.theta > 1:
self.theta = 1
if (self.theta_min > self.theta):
self.theta_min = self.theta
if self.eta > 1:
self.eta = 1
self._init_hyperboxes()
if self.E is None:
self.E = np.array([])
if self.F is None:
self.F = np.array([])
def is_satisfied_cat_expansion_conds(self, Ej, Fj, x_cat):
"""
Check whether the expansion condition for categorical features `x_cat`
of an input pattern can be covered by categorical bounds of the
hyperbox `Bj` with the categorical features stored in the lower bound
`Ej` and the upper bound `Fj`.
Parameters
----------
Ej : array-like of shape (n_cat_features,)
Lower bound of categorical features in the hyperbox `Bj` which can
be extended to cover the input pattern.
Fj : array-like of shape (n_cat_features,)
Upper bound of categorical features in the hyperbox `Bj` which can
be extended to cover the input pattern.
x_cat : array-like of shape (n_cat_features,)
Categorical features of an input pattern.
Returns
-------
bool
If True, the categorical features in `Dj` are satisfied with the
expansion conditions for the categorical feature so that it can be
expanded to cover the input pattern. Otherwise, the conditions for
the categorical features are not met.
"""
n_cat_features = len(Ej)
for i in range(n_cat_features):
if (x_cat[i] != Ej[i]) and (x_cat[i] != Fj[i]):
if (Ej[i] == DEFAULT_CATEGORICAL_VALUE) and (Fj[i] == DEFAULT_CATEGORICAL_VALUE):
return True
else:
if Ej[i] != DEFAULT_CATEGORICAL_VALUE:
if Fj[i] == DEFAULT_CATEGORICAL_VALUE:
if self.similarity_of_cat_vals[i][hashing(Ej[i], x_cat[i])] > self.eta:
return False
else:
cur_dist = self.similarity_of_cat_vals[i][hashing(Ej[i], Fj[i])]
change_low_dist = self.similarity_of_cat_vals[i][hashing(Ej[i], x_cat[i])]
change_up_dist = self.similarity_of_cat_vals[i][hashing(Fj[i], x_cat[i])]
if change_low_dist <= cur_dist and change_up_dist <= cur_dist:
return False
else:
if change_low_dist > self.eta and change_up_dist > self.eta:
return False
return True
def fit(self, X, y, categorical_features=None):
"""
Build a general fuzzy min-max neural network from the training set
(X, y) using the original incremental learning algorithm, in which
categorical features are encoded using the ordinal encoding method and
the similarity among categorical values are computed using their frequency
of occurence with respect to all class labels in a training set.
Parameters
----------
X : array-like of shape (n_samples, n_features) or (2*n_samples, n_features)
The training input samples including both continuous and categorical
features. If the number of rows in `X` is 2*n_samples, the first
n_samples rows contain lower bounds of input patterns and the rest
n_samples rows contain upper bounds.
y : array-like of shape (n_samples,)
The class labels.
categorical_features : a list of int, optional, default=None
Indices of categorical features in the training set. If None, there
is no categorical feature.
Returns
-------
self : object
Fitted estimator.
"""
self.categorical_features_ = categorical_features
if X.ndim == 1:
X = X.reshape(shape=(1, -1))
if is_contain_missing_value(y) == True:
y = np.where(np.isnan(y), UNLABELED_CLASS, y)
y = y.astype('int')
if categorical_features is not None:
X, self.encoder_ = ordinal_encode_categorical_features(X, categorical_features)
X_cat = X[:, categorical_features]
n_features = X.shape[1]
if (categorical_features is None) or (len(categorical_features) < n_features):
continuous_features = []
for i in range(n_features):
if i not in categorical_features:
continuous_features.append(i)
self.continuous_features_ = continuous_features
n_samples = len(y)
X_con = X[:, continuous_features].astype(float)
if X_con.shape[0] > n_samples:
Xl = X_con[:n_samples, :]
Xu = X_con[n_samples:, :]
if categorical_features is None:
return self._fit(Xl, Xu, None, y)
else:
X_cat = X_cat[:n_samples, :]
self.similarity_of_cat_vals = compute_similarity_among_categorical_values(X_cat, y)
return self._fit(Xl, Xu, X_cat, y)
else:
if categorical_features is None:
return self._fit(X_con, X_con, None, y)
else:
self.similarity_of_cat_vals = compute_similarity_among_categorical_values(X_cat, y)
return self._fit(X_con, X_con, X_cat, y)
else:
self.continuous_features_ = None
self.similarity_of_cat_vals = compute_similarity_among_categorical_values(X_cat, y)
return self._fit(None, None, X_cat, y)
def _fit(self, Xl, Xu, X_cat, y, is_compute_similarity_cat_vals=False):
"""
Build a general fuzzy min-max neural network from the training set
using the original incremental learning algorithm, in which
categorical features are encoded using the ordinal encoding method and
the similarity among categorical values are computed using their frequency
of occurence with respect to all class labels in a training set. Input training
data in this method were split into continuous features with lower and
upper bounds and categorical features.
Parameters
----------
Xl : array-like of shape (n_samples, n_continuous_features)
A matrix stores the lower bounds of training continuous features.
If there is no continuous feature, this variable will get a None value.
Xu : array-like of shape (n_samples, n_continuous_features)
A matrix stores the upper bounds of training continuous features.
If there is no continuous feature, this variable will get a None value.
X_cat : array-like of shape (n_samples, n_cat_features)
A matrix stores the training categorical features. If there is no
categorical feature, this variable will get a None value.
y : array-like of shape (n_samples,)
The class labels.
is_compute_similarity_cat_vals : boolean, optional, default=False
Whether a matrix of similarity values among categorical values of
all features is computed or not.
Returns
-------
self : object
The fitted estimator.
"""
time_start = time.perf_counter()
if Xl is not None:
n_samples = Xl.shape[0]
n_continuous_features = Xl.shape[1]
else:
n_samples = X_cat.shape[0]
n_continuous_features = 0
if X_cat is not None:
if X_cat.ndim == 1:
X_cat = X_cat.reshape(-1, 1)
n_cat_features = X_cat.shape[1]
else:
n_cat_features = 0
self._validate_data()
self.is_exist_continuous_missing_value = False
if Xl is not None:
if (is_contain_missing_value(Xl) == True) or (is_contain_missing_value(Xu) == True):
self.is_exist_continuous_missing_value = True
Xl, Xu, y = convert_format_missing_input_zero_one(Xl, Xu, y)
if is_contain_missing_value(y) == True:
y = np.where(np.isnan(y), UNLABELED_CLASS, y)
if is_compute_similarity_cat_vals == True and X_cat is not None:
self.similarity_of_cat_vals = compute_similarity_among_categorical_values(X_cat, y)
theta = self.theta
training_acc = 0
self.n_passes = 0
while theta >= self.theta_min and training_acc < 1:
self.n_passes += 1
threshold_mem_val = 1 - np.max(self.gamma) * theta
# Loop through each training input pattern
for i in range(n_samples):
if (n_continuous_features > 0 and self.V.size == 0) or (n_cat_features > 0 and self.E.size == 0):
# no model provided, start from scratch
if Xl is not None:
self.V = np.array([Xl[i]])
self.W = np.array([Xu[i]])
if X_cat is not None:
self.E = X_cat[i].reshape(1, -1)
self.F = np.full((1, n_cat_features), DEFAULT_CATEGORICAL_VALUE)
self.C = np.array([y[i]])
else:
if y[i] == UNLABELED_CLASS:
id_same_input_label_group = np.ones(len(self.C), dtype=bool)
else:
id_same_input_label_group = (self.C == y[i]) | (self.C == UNLABELED_CLASS)
if id_same_input_label_group.any() == True:
if n_continuous_features > 0:
V_sameX = self.V[id_same_input_label_group]
W_sameX = self.W[id_same_input_label_group]
else:
V_sameX = None
W_sameX = None
if n_cat_features > 0:
E_sameX = self.E[id_same_input_label_group]
F_sameX = self.F[id_same_input_label_group]
else:
E_sameX = None
F_sameX = None
lb_sameX = self.C[id_same_input_label_group]
id_range = np.arange(len(self.C))
id_processing = id_range[id_same_input_label_group]
if n_continuous_features > 0 and n_cat_features > 0:
if not self.is_exist_continuous_missing_value:
b = membership_func_freq_cat_gfmm(Xl[i], Xu[i], X_cat[i], V_sameX, W_sameX, E_sameX, F_sameX, self.similarity_of_cat_vals, self.gamma)
else:
b = membership_func_freq_cat_gfmm(Xl[i], Xu[i], X_cat[i], np.minimum(V_sameX, W_sameX), np.maximum(W_sameX, V_sameX), E_sameX, F_sameX, self.similarity_of_cat_vals, self.gamma)
else:
if n_continuous_features > 0:
if not self.is_exist_continuous_missing_value:
b = membership_func_freq_cat_gfmm(Xl[i], Xu[i], None, V_sameX, W_sameX, E_sameX, F_sameX, self.similarity_of_cat_vals, self.gamma)
else:
b = membership_func_freq_cat_gfmm(Xl[i], Xu[i], None, np.minimum(V_sameX, W_sameX), np.maximum(W_sameX, V_sameX), E_sameX, F_sameX, self.similarity_of_cat_vals, self.gamma)
else:
b = membership_func_freq_cat_gfmm(None, None, X_cat[i], V_sameX, W_sameX, E_sameX, F_sameX, self.sim_vec, self.gamma)
id_descending_mem_val = np.argsort(b)[::-1]
if b[id_descending_mem_val[0]] != 1 or (y[i] != lb_sameX[id_descending_mem_val[0]] and y[i] != UNLABELED_CLASS):
adjust = False
count = 0
for j in id_processing[id_descending_mem_val]:
if n_cat_features == 0 and b[id_descending_mem_val[count]] < threshold_mem_val:
break
count += 1
# test violation of max hyperbox size and class labels
if (y[i] == self.C[j] or self.C[j] == UNLABELED_CLASS or y[i] == UNLABELED_CLASS):
is_met_expansion = False
if n_continuous_features > 0 and n_cat_features > 0:
if (((np.maximum(self.W[j], Xu[i]) - np.minimum(self.V[j], Xl[i])) <= theta).all() == True) and (self.is_satisfied_cat_expansion_conds(self.E[j], self.F[j], X_cat[i]) == True):
is_met_expansion = True
else:
if (n_continuous_features > 0) and (((np.maximum(self.W[j], Xu[i]) - np.minimum(self.V[j], Xl[i])) <= theta).all() == True):
is_met_expansion = True
if (n_cat_features > 0) and (self.is_satisfied_cat_expansion_conds(self.E[j], self.F[j], X_cat[i]) == True):
is_met_expansion = True
if is_met_expansion == True:
# adjust the j-th hyperbox
if n_continuous_features > 0:
self.V[j] = np.minimum(self.V[j], Xl[i])
self.W[j] = np.maximum(self.W[j], Xu[i])
if n_cat_features > 0:
for tt in range(n_cat_features):
if (self.E[j, tt] == DEFAULT_CATEGORICAL_VALUE) and (self.F[j, tt] == DEFAULT_CATEGORICAL_VALUE):
self.E[j, tt] = X_cat[i, tt]
else:
if self.F[j, tt] == DEFAULT_CATEGORICAL_VALUE:
self.F[j, tt] = X_cat[i, tt]
else:
cur_dist = self.similarity_of_cat_vals[tt][hashing(self.E[j, tt], self.F[j, tt])]
expand_up_dist = self.similarity_of_cat_vals[tt][hashing(self.E[j, tt], X_cat[i, tt])]
if (expand_up_dist > cur_dist) and (expand_up_dist <= self.eta):
self.F[j, tt] = X_cat[i, tt]
else:
self.E[j, tt] = X_cat[i, tt]
id_of_winner_hyperbox = j
adjust = True
if y[i] != UNLABELED_CLASS and self.C[j] == UNLABELED_CLASS:
self.C[j] = y[i]
break
# if i-th sample did not fit into any existing box, create a new one
if not adjust:
if n_continuous_features > 0:
self.V = np.concatenate((self.V, Xl[i].reshape(1, -1)), axis = 0)
self.W = np.concatenate((self.W, Xu[i].reshape(1, -1)), axis = 0)
self.C = np.concatenate((self.C, [y[i]]))
if n_cat_features > 0:
self.E = np.vstack((self.E, X_cat[i]))
X_f_tmp = np.full((1, n_cat_features), DEFAULT_CATEGORICAL_VALUE)
self.F = np.vstack((self.F, X_f_tmp))
else:
id_overlap_box_resolve_only_cat = []
for ii in range(len(self.C)):
if ii != id_of_winner_hyperbox and (self.C[ii] != self.C[id_of_winner_hyperbox] or self.C[id_of_winner_hyperbox] == UNLABELED_CLASS):
if n_cat_features > 0:
dim_cat = hyperbox_overlap_test_freq_cat_gfmm(self.E, self.F, id_of_winner_hyperbox, ii, X_cat, self.similarity_of_cat_vals, id_overlap_box_resolve_only_cat)
if (n_continuous_features > 0) and (self.V.shape[0] > 1):
if (len(dim_cat) > 0):
# overlap for both types of features => need to resolve
if dim_cat[0] != -1 and (dim_cat[1][0] is not None or dim_cat[1][1] is not None):
# resolve overlap in cat feature
self.E[id_of_winner_hyperbox], self.F[id_of_winner_hyperbox] = hyperbox_contraction_freq_cat_gfmm(self.E[id_of_winner_hyperbox], self.F[id_of_winner_hyperbox], dim_cat)
id_overlap_box_resolve_only_cat.append(ii)
else:
# Doing overlap resolving for continuous features
is_overlap = is_two_hyperboxes_overlap_num_data_general(
self.V[id_of_winner_hyperbox], self.W[id_of_winner_hyperbox], self.V[ii], self.W[ii])
if is_overlap == True:
self.V[id_of_winner_hyperbox], self.W[id_of_winner_hyperbox], self.V[ii], self.W[ii] = overlap_resolving_num_data(
self.V[id_of_winner_hyperbox], self.W[id_of_winner_hyperbox], self.C[id_of_winner_hyperbox], self.V[ii], self.W[ii], self.C[ii])
else:
# No overlap in cat features, but if overlap in continous features then we need to keep the id of this hypebox
# because when resolve overlap for cat feature by changing its values in the future, maybe we reverse overlap
is_overlap = is_two_hyperboxes_overlap_num_data_general(
self.V[id_of_winner_hyperbox], self.W[id_of_winner_hyperbox], self.V[ii], self.W[ii])
if is_overlap == True:
id_overlap_box_resolve_only_cat.append(ii)
else:
if (len(dim_cat) > 0) and (dim_cat[0] != -1):
self.E[id_of_winner_hyperbox], self.F[id_of_winner_hyperbox] = hyperbox_contraction_freq_cat_gfmm(self.E[id_of_winner_hyperbox], self.F[id_of_winner_hyperbox], dim_cat)
id_overlap_box_resolve_only_cat.append(ii)
else:
is_overlap = is_two_hyperboxes_overlap_num_data_general(
self.V[id_of_winner_hyperbox], self.W[id_of_winner_hyperbox], self.V[ii], self.W[ii])
if is_overlap == True:
self.V[id_of_winner_hyperbox], self.W[id_of_winner_hyperbox], self.V[ii], self.W[ii] = overlap_resolving_num_data(
self.V[id_of_winner_hyperbox], self.W[id_of_winner_hyperbox], self.C[id_of_winner_hyperbox], self.V[ii], self.W[ii], self.C[ii])
else:
if n_continuous_features > 0:
self.V = np.concatenate((self.V, Xl[i].reshape(1, -1)), axis = 0)
self.W = np.concatenate((self.W, Xu[i].reshape(1, -1)), axis = 0)
self.C = np.concatenate((self.C, [y[i]]))
if n_cat_features > 0:
self.E = np.vstack((self.E, X_cat[i]))
X_f_tmp = np.full((1, n_cat_features), DEFAULT_CATEGORICAL_VALUE)
self.F = np.vstack((self.F, X_f_tmp))
if n_continuous_features > 0:
theta = theta * self.alpha
if theta >= self.theta_min:
y_pred = self._predict(Xl, Xu, X_cat)
training_acc = accuracy_score(y, y_pred)
else:
training_acc = 2 # stop the loop
time_end = time.perf_counter()
self.elapsed_training_time = time_end - time_start
return self
def predict(self, X):
"""
Predict class labels for samples in `X`.
.. note::
In the case there are many winner hyperboxes representing different
class labels but with the same membership value with respect to the
input pattern :math:`X_i`, an additional criterion based on the
minimum Manhattan distance between continous featurers of :math:`X_i`
and the central points of continous features of winner hyperboxes
are used to find the final winner hyperbox that its class label is
used for predicting the class label of the input pattern :math:`X_i`.
If there are only categorical features but many winner hyperboxes
belonging to different classes, a random selection will be used to
choose the final class label.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix for which we want to predict the targets.
Returns
-------
y_pred : ndarray of shape (n_samples,)
Vector containing the predictions. In binary and
multiclass problems, this is a vector containing `n_samples`.
"""
X = np.array(X)
if X.ndim == 1:
X = X.reshape(1, -1)
if self.categorical_features_ is not None:
X, _ = ordinal_encode_categorical_features(X, self.categorical_features_, self.encoder_)
if (self.continuous_features_ is not None) and (len(self.continuous_features_) > 0):
X_con = X[:, self.continuous_features_].astype(float)
else:
X_con = None
X_cat = X[:, self.categorical_features_]
y_pred = self._predict(X_con, X_con, X_cat)
else:
y_pred = self._predict(X, X, None)
return y_pred
def _predict(self, Xl, Xu, X_cat):
"""
Predict class labels for samples in the form of hyperboxes represented
by low bounds `Xl` and upper bounds `Xu`.
.. note::
In the case there are many winner hyperboxes representing different
class labels but with the same membership value with respect to the
input pattern :math:`X_i` in the form of an hyperbox represented by
a lower bound :math:`Xl_i` and an upper bound :math:`Xu_i` for
continous features and a matrix :math:`Xcat_i` for categorical
features, an additional criterion based on the minimum Manhattan
distance between the central point of continous features in the
input hyperbox :math:`X_i = [Xl_i, Xu_i]` and the central points of
continous features in the winner hyperboxes are used to find the
final winner hyperbox that its class label is used for predicting
the class label of the input hyperbox :math:`X_i`.
.. warning::
Another important point to pay attention is that the categorical
features storing in :math:`X_cat` need to be encoded by using the
function :func:`ordinal_encode_categorical_features` before pushing
the values to this method.
Parameters
----------
Xl : array-like of shape (n_samples, n_continuous_features)
The data matrix contains the lower bounds of input patterns
for which we want to predict the targets.
Xu : array-like of shape (n_samples, n_continuous_features)
The data matrix contains the upper bounds of input patterns
for which we want to predict the targets.
X_cat : array-like of shape (n_samples, n_cat_features)
The data matrix contains the bounds for categorical features
of input patterns for which we want to predict the targets.
Returns
-------
y_pred : ndarray of shape (n_samples,)
Vector containing the predictions. In binary and
multiclass problems, this is a vector containing `n_samples`.
"""
y_pred = predict_freq_cat_feature_manhanttan(self.V, self.W, self.E, self.F, self.C, Xl, Xu, X_cat, self.similarity_of_cat_vals, self.gamma)
return y_pred
def predict_with_membership(self, X):
"""
Predict class membership values of the input samples X including
both categorical and continuous features.
The predicted class membership value is the membership value
of the representative hyperbox of that class.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
Returns
-------
mem_vals : ndarray of shape (n_samples, n_classes)
The class membership values of the input samples. The order of the
classes corresponds to that in ascending integers of class labels.
"""
X = np.array(X)
if X.ndim == 1:
X = X.reshape(1, -1)
if self.categorical_features_ is not None:
X, _ = ordinal_encode_categorical_features(X, self.categorical_features_, self.encoder_)
if (self.continuous_features_ is not None) and (len(self.continuous_features_) > 0):
X_con = X[:, self.continuous_features_].astype(float)
else:
X_con = None
X_cat = X[:, self.categorical_features_]
mem_vals = self._predict_with_membership(X_con, X_con, X_cat)
else:
mem_vals = self._predict_with_membership(X, X, None)
return mem_vals
def _predict_with_membership(self, Xl, Xu, X_cat):
"""
Predict class membership values of the input hyperboxes represented by
lower bounds Xl and upper bounds Xu for continuous features and
categorical bounds X_cat for categorical features.
The predicted class membership value is the membership value
of the representative hyperbox of that class.
Parameters
----------
Xl : array-like of shape (n_samples, n_continuous_features)
The lower bounds for continous features of input hyperboxes.
Xu : array-like of shape (n_samples, n_continuous_features)
The upper bounds for continous features of input hyperboxes.
X_cat : array-like of shape (n_samples, n_cat_features)
The bounds for categorical features of input hyperboxes.
Returns
-------
mem_vals : ndarray of shape (n_samples, n_classes)
The class membership values of the input samples. The order of the
classes corresponds to that in ascending integers of class labels.
"""
if Xl is not None:
if Xl.ndim == 1:
Xl = Xl.reshape(1, -1)
if Xu.ndim == 1:
Xu = Xu.reshape(1, -1)
if is_contain_missing_value(Xl) == True or is_contain_missing_value(Xu) == True:
Xl, Xu, _ = convert_format_missing_input_zero_one(Xl, Xu)
if X_cat is not None:
if X_cat.ndim == 1:
X_cat = X_cat.reshape(1, -1)
mem_vals, _ = get_membership_freq_cat_gfmm_all_classes(Xl, Xu, X_cat, self.V, self.W, self.E, self.F, self.C, self.similarity_of_cat_vals, self.gamma)
return mem_vals
def predict_proba(self, X):
"""
Predict class probabilities of the input samples X including both
continuous and categorical features.
The predicted class probability is the fraction of the membership value
of the representative hyperbox of that class and the sum of all
membership values of all representative hyperboxes of all classes.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
Returns
-------
proba : ndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the
classes corresponds to that in ascending integers of class labels.
"""
mem_vals = self.predict_with_membership(X)
normalizer = mem_vals.sum(axis=1)[:, np.newaxis]
normalizer[normalizer == 0.0] = 1.0
proba = mem_vals / normalizer
return proba
def _predict_proba(self, Xl, Xu, X_cat):
"""
Predict class probabilities of the input hyperboxes represented by
lower bounds Xl and upper bounds Xu for continuous features and
categorical bounds X_cat for categorical features.
The predicted class probability is the fraction of the membership value
of the representative hyperbox of that class and the sum of all
membership values of all representative hyperboxes of all classes.