-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheiol_gfmm.py
More file actions
1597 lines (1373 loc) · 77.9 KB
/
eiol_gfmm.py
File metadata and controls
1597 lines (1373 loc) · 77.9 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 extended improved
incremental learning algorithm for mixed attribute data.
"""
# @Author: Thanh Tung KHUAT <thanhtung09t2@gmail.com>
# License: GPL-3.0
import numpy as np
import pandas as pd
import copy
import time
import random
import itertools
from sklearn.metrics import accuracy_score
from hbbrain.base.base_gfmm_estimator import (
BaseGFMMClassifier,
convert_format_missing_input_zero_one,
is_contain_missing_value,
predict_with_probability,
predict_with_manhattan,
)
from hbbrain.utils.dist_metrics import manhattan_distance, manhattan_distance_with_missing_val
from hbbrain.utils.membership_calc import (
membership_func_extended_iol_gfmm,
get_membership_extended_iol_gfmm_all_classes,
membership_func_gfmm,
)
from hbbrain.utils.adjust_hyperbox import is_overlap_one_many_diff_label_hyperboxes_mixed_data_general
from hbbrain.constants import (
UNLABELED_CLASS,
PROBABILITY_MEASURE,
MANHATTAN_DIS,
DEFAULT_CATEGORICAL_VALUE,
)
def predict_with_manhattan_mixed_data(V, W, D, C, Xl, Xu, X_cat, g=1, alpha=0.5):
"""
Predict class labels for samples in `X` represented in the form of invervals `[Xl, Xu]`
for continuous features and `X_cat` for categorical features.
This is a common function to determine the right class labels for X wrt. a trained hyperbox-based
classifier represented by `[V, W, D, C]`. It uses the winner-takes-all principle to predict
class labels for each sample in X by assigning the class label of the sample to the class
label of the hyperbox with the maximum membership value to that sample. It will use
a Manhattan distance for continous features in the case of many hyperboxes with different
classes having the same maximum membership value.
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.
D : array-like of shape (n_hyperboxes, n_cat_features)
A matrix stores all categorical bounds for categorical features of all
hyperboxes of a trained hyperbox-based model, in which each row is a
categorical bound of a hyperbox.
C : ndarray 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.
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.
alpha : float, optional, default=0.5
The trade-off weighting factor between the impacts of categorical
features and numerical features on the outputs of membership values.
Returns
-------
y_pred : ndarray of shape (n_samples,)
A vector contains the predictions. In binary and multiclass problems,
this is a vector containing `n_samples`.
"""
if Xl is not None and Xl.ndim == 1:
Xl = Xl.reshape(1, -1)
Xu = Xu.reshape(1, -1)
if X_cat is not None and X_cat.ndim == 1:
X_cat = X_cat.reshape(1, -1)
if (Xl is not None) and ((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:
X_cat = impute_missing_categorical_features(X_cat)
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
for i in range(n_samples):
sample_id += 1
if Xl is not None and X_cat is not None:
if is_exist_missing_continous_value == False:
mem_val = membership_func_extended_iol_gfmm(Xl[i], Xu[i], X_cat[i], V, W, D, g, alpha)
else:
mem_val = membership_func_extended_iol_gfmm(Xl[i], Xu[i], X_cat[i], np.minimum(V, W), np.maximum(W, V), D, g, alpha)
else:
if Xl is not None:
if is_exist_missing_continous_value == False:
mem_val = membership_func_gfmm(Xl[i, :], Xu[i, :], V, W, g) # calculate memberships for all hyperboxes
else:
mem_val = membership_func_gfmm(Xl[i, :], Xu[i, :], np.minimum(V, W), np.maximum(W, V), g) # calculate memberships for all hyperboxes
else:
mem_val = membership_func_extended_iol_gfmm(None, None, X_cat[i], V, W, D, g, alpha)
bmax = mem_val.max() # get the maximum membership value
if ((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 the maximum membership values
max_mem_V_id = np.nonzero(mem_val == bmax)[0]
winner_cls = np.unique(C[max_mem_V_id])
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_V_id] > W[max_mem_V_id]).any() == True):
maht_dist = manhattan_distance_with_missing_val(Xl[i], Xu[i], V[max_mem_V_id], W[max_mem_V_id])
else:
if (Xl[i] == Xu[i]).all() == False:
Xl_mat = np.ones((len(max_mem_V_id), 1)) * Xl[i]
Xu_mat = np.ones((len(max_mem_V_id), 1)) * Xu[i]
Xg_mat = (Xl_mat + Xu_mat) / 2
else:
Xg_mat = np.ones((len(max_mem_V_id), 1)) * Xl[i]
# Find all average points of all hyperboxes with the same membership value
avg_point_mat = (V[max_mem_V_id] + W[max_mem_V_id]) / 2
# compute the Manhattan distance from Xg_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_V_id[id_min_dist]]
else:
y_pred[i] = C[max_mem_V_id[0]]
return y_pred
def predict_with_probability_mixed_data(V, W, D, C, N_samples, Xl, Xu, X_cat, g=1, alpha=0.5):
"""
Predict class labels for samples in `X` represented in the form of invervals `[Xl, Xu]`.
This is a common function to determine the right class labels for X wrt. a trained hyperbox-based
classifier represented by `[V, W, C]`. It uses the winner-takes-all principle to predict
class labels for each sample in X by assigning the class label of the sample to the class
label of the hyperbox with the maximum membership value to that sample. It will use
a probability formula based on the number of samples included in each winner hyperbox
in the case of many hyperboxes with different classes having the same maximum membership value.
Parameters
----------
V : array-like of shape (n_hyperboxes, n_continuous_features)
A matrix stores all minimal points of all hyperboxes of a trained
hyperbox based model, each row is a minimal point for continuous
features of a hyperbox.
W : array-like of shape (n_hyperboxes, n_continuous_features)
A matrix stores all maximal points of all hyperboxes of a trained
hyperbox-based model, each row is a maximal point for continuous
features of a hyperbox.
D : array-like of shape (n_hyperboxes, n_cat_features)
A matrix stores all maximal points of all hyperboxes of a trained
hyperbox based model, each row is a categorical bound for a hyperbox.
C : ndarray of shape (n_hyperboxes,)
An array contains all class lables for all hyperboxes of a trained hyperbox-based model.
N_samples : ndarray of shape (n_hyperboxes,)
An array contains number of samples included in each hyperbox of a
trained hyperbox-based model.
Xl : array-like of shape (n_samples, n_continuous_features)
The data matrix contains 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 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 categorical bounds of input categorical
patterns for which we want to predict the targets.
g : float or array-like of shape (n_continuous_features,), optional, default=1
A sensitivity parameter describing the speed of decreasing of the
membership function in each continuous dimension.
alpha : float, optional, default=0.5
The trade-off weighting factor between the impacts of categorical
features and numerical features on the outputs of membership values.
Returns
-------
y_pred : ndarray of shape (n_samples,)
A vector contains the predictions. In binary and multiclass problems,
this is a vector containing `n_samples`.
"""
if Xl is not None:
if Xl.ndim == 1:
Xl = Xl.reshape(1, -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 and X_cat.ndim == 1:
X_cat = X_cat.reshape(1, -1)
if X_cat is not None:
X_cat = impute_missing_categorical_features(X_cat)
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
# classifications
for i in range(n_samples):
sample_id += 1
if Xl is not None and X_cat is not None:
if is_exist_missing_continous_value == False:
mem_val = membership_func_extended_iol_gfmm(Xl[i], Xu[i], X_cat[i], V, W, D, g, alpha)
else:
mem_val = membership_func_extended_iol_gfmm(Xl[i], Xu[i], X_cat[i], np.minimum(V, W), np.maximum(W, V), D, g, alpha)
else:
if Xl is not None:
if is_exist_missing_continous_value == False:
mem_val = membership_func_gfmm(Xl[i, :], Xu[i, :], V, W, g) # calculate memberships for all hyperboxes
else:
mem_val = membership_func_gfmm(Xl[i, :], Xu[i, :], np.minimum(V, W), np.maximum(W, V), g) # calculate memberships for all hyperboxes
else:
mem_val = membership_func_extended_iol_gfmm(None, None, X_cat[i], V, W, D, g, alpha)
bmax = mem_val.max() # get the maximum membership value
if ((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 the maximum membership values
max_mem_V_id = np.nonzero(mem_val == bmax)[0]
cls_same_mem = np.unique(C[max_mem_V_id])
if len(cls_same_mem) > 1:
cls_val = UNLABELED_CLASS
is_find_prob_val = True
if bmax == 1:
id_box_with_one_sample = np.nonzero(N_samples[max_mem_V_id] == 1)[0]
if len(id_box_with_one_sample) > 0:
is_find_prob_val = False
random.seed(0)
sel_id = random.choice(max_mem_V_id[id_box_with_one_sample])
cls_val = C[sel_id]
if is_find_prob_val == True:
sum_prod_denum = (mem_val[max_mem_V_id] * N_samples[max_mem_V_id]).sum()
max_prob = -1
pre_id_cls = None
for c in cls_same_mem:
id_cls = np.nonzero(C[max_mem_V_id] == c)[0]
sum_pro_num = (mem_val[max_mem_V_id[id_cls]] * N_samples[max_mem_V_id[id_cls]]).sum()
if sum_prod_denum != 0:
prob_val = sum_pro_num / sum_prod_denum
else:
prob_val = 0
if prob_val > max_prob or ((prob_val == max_prob) and (pre_id_cls is not None) and (N_samples[max_mem_V_id[id_cls]].sum() > N_samples[max_mem_V_id[pre_id_cls]].sum())):
max_prob = prob_val
cls_val = c
pre_id_cls = id_cls
y_pred[i] = cls_val
else:
y_pred[i] = C[max_mem_V_id[0]]
return y_pred
def impute_missing_categorical_features(X_cat):
"""
Impute missing values in categorical features by a default value.
Parameters
----------
X_cat : array-like of shape (n_samples, n_cat_features)
Input matrix contains categorical features only.
Returns
-------
X_cat : array-like of shape (n_samples, n_cat_features)
The resulting matrix contains categorical features of which missing
categorical values have been imputed by a default value.
"""
id_missing_values = pd.isna(X_cat)
if id_missing_values.any() == True:
X_cat[id_missing_values] = DEFAULT_CATEGORICAL_VALUE
return X_cat
class ExtendedImprovedOnlineGFMM(BaseGFMMClassifier):
"""Extended improved online learning algorithm for a general fuzzy min-max
neural network with mixed-attribute data.
This algorithm can handle the datasets with both continuous and categorical
features. It uses the change in the entropy values of categorical features
of the samples contained in a hyperbox to determine if the current hyperbox
can be expanded to include the categorical values of a new training instance.
An extended architecture of the original general fuzzy min-max neural network
and its new membership function are also introduced for mixed-attribute data.
See [1]_ for more detailed information regarding this extended improved
online learning algorithm.
Parameters
----------
theta : float, optional, default=0.5
Maximum hyperbox size for continuous features.
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.
delta : float, optional, default=0.5
A maximum entropy changing threshold for categorical values after
expansion of the existing hyperbox to cover an input pattern.
alpha : float, optional, default=0.5
A trade-off factor regulating the contribution level of continous
features part and categorical features part to the membership score.
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.
D : array-like of shape (n_hyperboxes, n_cat_features)
A matrix stores a special structure for categorical features of all
existing hyperboxes. Each element in `D` stores a set of symbolic
values with their cardinalities for the j-th categorical dimension of
a given hyperbox.
C : array-like of shape (n_hyperboxes,)
A vector stores all class labels correponding to existing hyperboxes.
N_samples : array-like of shape (n_hyperboxes,)
A vector stores the number of samples fully included in each existing
hyperbox.
Attributes
----------
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.
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.
References
----------
.. [1] T. T. Khuat and B. Gabrys "An Online Learning Algorithm for a
Neuro-Fuzzy Classifier with Mixed-Attribute Data", ArXiv preprint
arXiv:2009.14670, 2020.
Examples
--------
>>> from hbbrain.mixed_data.eiol_gfmm import ExtendedImprovedOnlineGFMM
>>> 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 = ExtendedImprovedOnlineGFMM(theta=0.1, delta=0.6)
>>> clf.fit(X, y, categorical_features)
>>> print("Number of hyperboxes = %d"%clf.get_n_hyperboxes())
Number of hyperboxes = 613
>>> clf.predict(X[[10, 100]])
array([1, 0])
"""
def __init__(self, theta=0.5, gamma=1, delta=0.5, alpha=0.5, V=None, W=None, D=None, C=None, N_samples=None):
BaseGFMMClassifier.__init__(
self, theta, gamma, False, V, W, C)
self.alpha = alpha
self.delta = delta
if D is not None:
self.D = D
else:
self.D = np.array([])
if N_samples is not None:
self.N_samples = N_samples
else:
self.N_samples = np.array([])
def _init_data(self):
"""
Initialise data for hyperboxes.
Returns
-------
None.
"""
self._init_hyperboxes()
if self.D is None:
self.D = np.array([])
if self.N_samples is None:
self.N_samples=np.array([])
def compute_increasing_entropy(self, cat_extended_hyperbox, cat_cur_hyperbox):
"""
Compute the increasing degree in the entropy for each categorical
feature in both the current hyperbox and that hyperbox after extended.
Parameters
----------
cat_extended_hyperbox : array-like of shape (n_cat_features,)
Categorical features in the current hyperbox after extended.
Each dimension contains a dictionary with the key being categorical
values and value being the number of samples in the hyperbox
containing the given categorical value in that dimension.
cat_cur_hyperbox : array-like of shape (n_cat_features,)
Categorical features in the current hyperbox.
Each dimension contains a dictionary with the key being categorical
values and value being the number of samples in the hyperbox
containing the given categorical value in that dimension.
Returns
-------
increased_entropy : array-like of shape (n_cat_features,)
The increased entropy value for each categorical dimension after
extended.
"""
n_cat_features = len(cat_extended_hyperbox)
increased_entropy = np.zeros(n_cat_features)
for j in range(n_cat_features):
n_new = sum(cat_extended_hyperbox[j].values())
n = sum(cat_cur_hyperbox[j].values())
p_new = np.array(list(cat_extended_hyperbox[j].values())) / n_new
p = np.array(list(cat_cur_hyperbox[j].values())) / n
increased_entropy[j] = sum(-p_new * np.log2(p_new)) - n / n_new * sum(-p * np.log2(p))
return increased_entropy
def fit(self, X, y, categorical_features=None, N_incl_samples=None, type_cat_expansion=0):
"""
Build a general fuzzy min-max neural network from the training set
(X, y) using the extended improved online learning algorithm.
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.
N_incl_samples : array-like of shape (n_samples,), optional, default=None
A vector stores numbers of samples fully contained in the input
patterns in the case that input patterns form hyperboxes.
type_cat_expansion : int, optional, default=0
Type of the expansion condition for categorical features.
If `type_cat_expansion` gets the value of 0, then the categorical
feature expansion condition regarding the maximum entropy changing
threshold will be applied for every categorical dimension.
Otherwise, this expansion condition will be applied for the average
entropy changing values of all categorical features.
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_cat = X[:, categorical_features]
X_cat = impute_missing_categorical_features(X_cat)
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, N_incl_samples, type_cat_expansion)
else:
X_cat = X_cat[:n_samples, :]
return self._fit(Xl, Xu, X_cat, y, N_incl_samples, type_cat_expansion)
else:
if categorical_features is None:
return self._fit(X_con, X_con, None, y, N_incl_samples)
else:
return self._fit(X_con, X_con, X_cat, y, N_incl_samples, type_cat_expansion)
else:
self.continuous_features_ = None
return self._fit(None, None, X_cat, y, N_incl_samples, type_cat_expansion)
def _fit(self, Xl, Xu, X_cat, y, N_incl_samples=None, type_cat_expansion=0):
"""
Build a general fuzzy min-max neural network from the training set
using the extended improved online learning algorithm. 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.
N_incl_samples : array-like of shape (n_samples,), optional, default=None
A vector stores numbers of samples fully contained in the input
hyperboxes.
type_cat_expansion : int, optional, default=0
Type of the expansion condition for categorical features.
If `type_cat_expansion` gets the value of 0, then the categorical
feature expansion condition regarding the maximum entropy changing
threshold will be applied for every categorical dimension.
Otherwise, this expansion condition will be applied for the average
entropy changing values of all categorical features.
Returns
-------
self : object
The fitted estimator.
"""
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._init_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)
time_start = time.perf_counter()
is_firt_run = True
for i in range(n_samples):
if (n_continuous_features > 0 and self.V.size == 0) or (n_cat_features > 0 and self.D.size == 0):
# no model provided, start from scratch
if n_continuous_features > 0:
self.V = np.array([Xl[i]])
self.W = np.array([Xu[i]])
if n_cat_features > 0:
self.D = np.empty((1, n_cat_features), dtype=object)
for j in range(n_cat_features):
dis = {}
if N_incl_samples is None:
dis[X_cat[i, j]] = 1
else:
dis[X_cat[i, j]] = N_incl_samples[i]
self.D[0, j] = dis
self.C = np.array([y[i]])
# save number of samples included in each hyperbox
if N_incl_samples is None:
self.N_samples = np.array([1])
else:
self.N_samples = np.array([N_incl_samples[i]])
else:
if y[i] == UNLABELED_CLASS:
id_same_input_label_group = np.arange(len(self.C))
else:
id_same_input_label_group = np.nonzero(((self.C == y[i]) | (self.C == UNLABELED_CLASS)))[0]
if len(id_same_input_label_group) > 0:
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, W_sameX = None, None
if n_cat_features > 0:
D_sameX = self.D[id_same_input_label_group]
else:
D_sameX = None
lb_sameX = self.C[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_extended_iol_gfmm(Xl[i], Xu[i], X_cat[i], V_sameX, W_sameX, D_sameX, self.gamma, self.alpha)
else:
b = membership_func_extended_iol_gfmm(Xl[i], Xu[i], X_cat[i], np.minimum(V_sameX, W_sameX), np.maximum(W_sameX, V_sameX), D_sameX, self.gamma, self.alpha)
else:
if n_continuous_features > 0:
if not self.is_exist_continuous_missing_value:
b = membership_func_extended_iol_gfmm(Xl[i], Xu[i], None, V_sameX, W_sameX, D_sameX, self.gamma, self.alpha)
else:
b = membership_func_extended_iol_gfmm(Xl[i], Xu[i], None, np.minimum(V_sameX, W_sameX), np.maximum(W_sameX, V_sameX), D_sameX, self.gamma, self.alpha)
else:
b = membership_func_extended_iol_gfmm(None, None, X_cat[i], V_sameX, W_sameX, D_sameX, self.gamma, self.alpha)
index = np.argsort(b)[::-1]
if b[index[0]] != 1:
adjust = False
is_refind_diff_hyperbox = True
if y[i] != UNLABELED_CLASS:
id_lb_diff = ((self.C != y[i]) | (self.C == UNLABELED_CLASS))
for j in id_same_input_label_group[index]:
is_meet_continous_cond = True
is_meet_categorical_cond = True
if n_continuous_features > 0:
minV_new = np.minimum(self.V[j], Xl[i])
maxW_new = np.maximum(self.W[j], Xu[i])
is_meet_continous_cond = ((maxW_new - minV_new) <= self.theta).all()
else:
minV_new, maxW_new = None, None
if y[i] == UNLABELED_CLASS:
id_lb_diff = ((self.C != self.C[j]) | (self.C == UNLABELED_CLASS))
if is_refind_diff_hyperbox == True:
if y[i] != UNLABELED_CLASS:
is_refind_diff_hyperbox = False
no_check_overlap = False
if len(id_lb_diff) == 0:
# No hyperbox belongs to other class
no_check_overlap = True
if n_cat_features > 0 and no_check_overlap == False:
D_diff = self.D[id_lb_diff]
else:
D_diff = None
if no_check_overlap == False:
N_sample_diff = self.N_samples[id_lb_diff]
if n_continuous_features > 0 and no_check_overlap == False:
V_diff = self.V[id_lb_diff]
W_diff = self.W[id_lb_diff]
# examine only hyperboxes w/o missing dimensions,
# meaning that in each dimension upper bound is
# larger than lower bounds
indcomp = np.nonzero((W_diff >= V_diff).all(axis = 1))[0]
if len(indcomp) == 0:
no_check_overlap = True
else:
V_diff = V_diff[indcomp]
W_diff = W_diff[indcomp]
N_sample_diff = N_sample_diff[indcomp]
if n_cat_features > 0:
D_diff = D_diff[indcomp]
else:
V_diff, W_diff = None, None
if (n_cat_features > 0) and (is_meet_continous_cond == True):
D_new = np.empty(n_cat_features, dtype=object)
for fi in range(n_cat_features):
dis = copy.deepcopy(self.D[j, fi])
if X_cat[i, fi] in dis:
if N_incl_samples is None:
dis[X_cat[i, fi]] += 1
else:
dis[X_cat[i, fi]] += N_incl_samples[i]
else:
if N_incl_samples is None:
dis[X_cat[i, fi]] = 1
else:
dis[X_cat[i, fi]] = N_incl_samples[i]
D_new[fi] = dis
increased_entropy = self.compute_increasing_entropy(D_new, self.D[j])
if type_cat_expansion == 0:
is_meet_categorical_cond = (increased_entropy <= self.delta).all()
else:
is_meet_categorical_cond = np.average(increased_entropy) <= self.delta
else:
D_new = None
if N_incl_samples is None:
N_sample_new = self.N_samples[j] + 1
else:
N_sample_new = self.N_samples[j] + N_incl_samples[i]
# test violation of max hyperbox size and class labels
if (is_meet_continous_cond == True) and (is_meet_categorical_cond == True):
if no_check_overlap == False and y[i] == UNLABELED_CLASS and self.C[j] == UNLABELED_CLASS:
if n_continuous_features > 0:
# remove hyperbox themself
keep_id = (V_diff != self.V[j]).any(1)
V_diff = V_diff[keep_id]
W_diff = W_diff[keep_id]
N_sample_diff = N_sample_diff[keep_id]
if n_cat_features > 0:
D_diff = D_diff[keep_id]
else:
# remove hyperbox themself
keep_id = (D_diff != self.D[j]).any(1)
D_diff = D_diff[keep_id]
N_sample_diff = N_sample_diff[keep_id]
# Test overlap
if no_check_overlap == True or is_overlap_one_many_diff_label_hyperboxes_mixed_data_general(V_diff, W_diff, D_diff, N_sample_diff, minV_new, maxW_new, D_new, N_sample_new) == False:
# adjust the j-th hyperbox
if n_continuous_features > 0:
self.V[j] = minV_new
self.W[j] = maxW_new
if n_cat_features > 0:
self.D[j] = D_new
self.N_samples[j] = N_sample_new
if y[i] != UNLABELED_CLASS and self.C[j] == UNLABELED_CLASS:
self.C[j] = y[i]
adjust = True
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)
if n_cat_features > 0:
tmp_D = np.empty((1, n_cat_features), dtype=object)
for ll in range(n_cat_features):
dis = {}
if N_incl_samples is None:
dis[X_cat[i, ll]] = 1
else:
dis[X_cat[i, ll]] = N_incl_samples[i]
tmp_D[0, ll] = dis
self.D = np.concatenate((self.D, tmp_D), axis = 0)
self.C = np.concatenate((self.C, [y[i]]))
if N_incl_samples is None:
self.N_samples = np.concatenate((self.N_samples, [1]))
else:
self.N_samples = np.concatenate((self.N_samples, [N_incl_samples[i]]))
else:
t = 0
# Find the first winner hyperbox with the same class with the input pattern
while (t + 1 < len(index)) and (b[index[t]] == 1) and (self.C[id_same_input_label_group[index[t]]] != y[i]) and (self.C[id_same_input_label_group[index[t]]] != UNLABELED_CLASS):
t = t + 1
if b[index[t]] == 1 and self.C[id_same_input_label_group[index[t]]] == y[i]:
# Update class label for the unlabelled hyperbox
if y[i] != UNLABELED_CLASS and self.C[id_same_input_label_group[index[t]]] == UNLABELED_CLASS:
self.C[id_same_input_label_group[index[t]]] = y[i]
# Update categorical values
for fi in range(n_cat_features):
if X_cat[i, fi] in self.D[id_same_input_label_group[index[t]], fi]:
if N_incl_samples is None:
self.D[id_same_input_label_group[index[t]], fi][X_cat[i, fi]] += 1
else:
self.D[id_same_input_label_group[index[t]], fi][X_cat[i, fi]] += N_incl_samples[i]
else:
if N_incl_samples is None:
self.D[id_same_input_label_group[index[t]], fi][X_cat[i, fi]] = 1
else:
self.D[id_same_input_label_group[index[t]], fi][X_cat[i, fi]] = N_incl_samples[i]
if N_incl_samples is None:
self.N_samples[id_same_input_label_group[index[t]]] = self.N_samples[id_same_input_label_group[index[t]]] + 1
else:
self.N_samples[id_same_input_label_group[index[t]]] = self.N_samples[id_same_input_label_group[index[t]]] + N_incl_samples[i]
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)
if n_cat_features > 0:
tmp_D = np.empty((1, n_cat_features), dtype=object)
for ll in range(n_cat_features):
dis = {}
if N_incl_samples is None:
dis[X_cat[i, ll]] = 1
else:
dis[X_cat[i, ll]] = N_incl_samples[i]
tmp_D[0, ll] = dis
self.D = np.concatenate((self.D, tmp_D), axis = 0)
self.C = np.concatenate((self.C, [y[i]]))
if N_incl_samples is None:
self.N_samples = np.concatenate((self.N_samples, [1]))
else:
self.N_samples = np.concatenate((self.N_samples, [N_incl_samples[i]]))
time_end = time.perf_counter()
self.elapsed_training_time = time_end - time_start
return self
def predict(self, X, type_boundary_handling=PROBABILITY_MEASURE):
"""
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
probability generated by number of samples included in winner
hyperboxes and membership values or the Manhattan distance between
the central point of winner hyperboxes and the input sample is 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`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix for which we want to predict the targets.
type_boundary_handling : int, optional, default=PROBABILITY_MEASURE (aka 1)
The way of handling many winner hyperboxes, i.e., PROBABILITY_MEASURE or MANHATTAN_DIS
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:
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_]
X_cat = impute_missing_categorical_features(X_cat)
y_pred = self._predict(X_con, X_con, X_cat, type_boundary_handling)
else:
y_pred = self._predict(X, X, None, type_boundary_handling)
return y_pred
def _predict(self, Xl, Xu, X_cat, type_boundary_handling=PROBABILITY_MEASURE):
"""
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 bound :math:`Xcat_i` for categorical
features, an additional criterion based on a probability measure
using the number of samples included in the hyperbox or 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`.
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.
type_boundary_handling : int, optional, default=PROBABILITY_MEASURE (aka 1)
The way of handling many winner hyperboxes, i.e., PROBABILITY_MEASURE or MANHATTAN_DIS
Returns
-------
y_pred : ndarray of shape (n_samples,)
Vector containing the predictions. In binary and
multiclass problems, this is a vector containing `n_samples`.
"""
if type_boundary_handling == PROBABILITY_MEASURE:
y_pred = predict_with_probability_mixed_data(self.V, self.W, self.D, self.C, self.N_samples, Xl, Xu, X_cat, self.gamma, self.alpha)
else:
y_pred = predict_with_manhattan_mixed_data(self.V, self.W, self.D, self.C, Xl, Xu, X_cat, self.gamma, self.delta)
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:
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_]
X_cat = impute_missing_categorical_features(X_cat)
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):
"""