Refined Online Learning Algorithm for FMNN

This example shows how to use the fuzzy min-max neural network classifier using a refined online learning algorithm (RFMNN)

Note that the numerical features in training and testing datasets must be in the range of [0, 1] because the RFMNN classifiers require features in the unit cube.

1. Execute directly from the python file

[1]:
%matplotlib notebook
[2]:
import os
import warnings
warnings.filterwarnings('ignore')

Get the path to the this jupyter notebook file

[3]:
this_notebook_dir = os.path.dirname(os.path.abspath("__file__"))
this_notebook_dir
[3]:
'C:\\hyperbox-brain\\docs\\tutorials'

Get the home folder of the Hyperbox-Brain project

[4]:
from pathlib import Path
project_dir = Path(this_notebook_dir).parent.parent
project_dir
[4]:
WindowsPath('C:/hyperbox-brain')

Create the path to the Python file containing the implementation of the RFMNN classifier

[5]:
rfmnn_file_path = os.path.join(project_dir, Path("hbbrain/numerical_data/incremental_learner/rfmnn.py"))
rfmnn_file_path
[5]:
'C:\\hyperbox-brain\\hbbrain\\numerical_data\\incremental_learner\\rfmnn.py'

Run the found file by showing the execution directions

[6]:
!python "{rfmnn_file_path}" -h
usage: rfmnn.py [-h] -training_file TRAINING_FILE -testing_file TESTING_FILE
                [--theta THETA] [--gamma GAMMA] [--is_draw IS_DRAW]

The description of parameters

required arguments:
  -training_file TRAINING_FILE
                        A required argument for the path to training data file
                        (including file name)
  -testing_file TESTING_FILE
                        A required argument for the path to testing data file
                        (including file name)

optional arguments:
  --theta THETA         Maximum hyperbox size (in the range of (0, 1])
                        (default: 0.5)
  --gamma GAMMA         A sensitivity parameter describing the speed of
                        decreasing of the membership function in each
                        dimension (larger than 0) (default: 1)
  --is_draw IS_DRAW     Show the existing hyperboxes during the training
                        process on the screen (default: False)

Create the path to training and testing datasets stored in the dataset folder

[7]:
training_data_file = os.path.join(project_dir, Path("dataset/syn_num_train.csv"))
training_data_file
[7]:
'C:\\hyperbox-brain\\dataset\\syn_num_train.csv'
[8]:
testing_data_file = os.path.join(project_dir, Path("dataset/syn_num_test.csv"))
testing_data_file
[8]:
'C:\\hyperbox-brain\\dataset\\syn_num_test.csv'

Run a demo program

[9]:
!python "{rfmnn_file_path}" -training_file "{training_data_file}" -testing_file "{testing_data_file}" --theta 0.1 --gamma 1
Number of hyperboxes = 95
Testing accuracy =  86.20%

2. Using the RFMNN classifier through its init, fit, and predict functions

[10]:
from hbbrain.numerical_data.incremental_learner.rfmnn import RFMNNClassifier
import pandas as pd

Create training and testing data sets

[11]:
df_train = pd.read_csv(training_data_file, header=None)
df_test = pd.read_csv(testing_data_file, header=None)

Xy_train = df_train.to_numpy()
Xy_test = df_test.to_numpy()

Xtr = Xy_train[:, :-1]
ytr = Xy_train[:, -1]

Xtest = Xy_test[:, :-1]
ytest = Xy_test[:, -1]

Initializing parameters

[12]:
theta = 0.1
gamma = 1
is_draw = True

Training

[13]:
rfmnn_clf = RFMNNClassifier(theta=theta, gamma=gamma, is_draw=is_draw)
rfmnn_clf.fit(Xtr, ytr)
[13]:
RFMNNClassifier(C=array([1, 2, 1, 1, 1, 2, 1, 2, 2, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 1, 2, 1,
       2, 1, 1, 2, 2, 2, 2, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
       2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1,
       2, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 1, 2,
       1, 2, 2, 1, 2, 1, 2]),
                V=array([[0.42413 , 0.53516 ],
       [0.77074 , 0.48234 ],
       [0.91059 , 0.82085 ],
       [0.64586 , 0.46818 ],
       [0.4713  , 0.672   ],
       [0.33484 , 0.18424 ],
       [0.32289 , 0.60093 ],
       [...
       [0.72496 , 0.34978 ],
       [0.73681 , 0.71261 ],
       [0.38312 , 0.65216 ],
       [0.37646 , 0.62974 ],
       [0.76138 , 0.32629 ],
       [0.52124 , 0.41288 ],
       [0.59655 , 0.56029 ],
       [0.38038 , 0.67232 ],
       [0.91185 , 0.48697 ],
       [0.6504  , 0.51624 ],
       [0.65227 , 0.56081 ],
       [0.29163 , 0.086547],
       [0.35813 , 0.58584 ],
       [0.56487 , 0.17003 ],
       [0.287   , 0.46814 ],
       [0.44575 , 0.64683 ],
       [0.25924 , 0.42696 ],
       [0.77398 , 0.5357  ],
       [0.68469 , 0.2221  ]]),
                is_draw=True, theta=0.1)

The code below shows how to display decision boundaries among classes if input data are 2-dimensional

[14]:
rfmnn_clf.draw_hyperbox_and_boundary("The trained RFMNN classifier and its decision boundaries")
[15]:
print("Number of existing hyperboxes = %d"%(rfmnn_clf.get_n_hyperboxes()))
Number of existing hyperboxes = 95
[16]:
print("Traning time = %f (s)"%rfmnn_clf.elapsed_training_time)
Traning time = 48.427096 (s)

Prediction

[17]:
from sklearn.metrics import accuracy_score
[18]:
y_pred = rfmnn_clf.predict(Xtest)
acc = accuracy_score(ytest, y_pred)
print(f'Accuracy = {acc * 100: .2f}%')
Accuracy =  86.20%

Explaining the predicted result for the input sample by showing membership values and hyperboxes for each class

[19]:
sample_need_explain = 10
y_pred_input_0, mem_val_classes, min_points_classes, max_points_classes = rfmnn_clf.get_sample_explanation(Xtest[sample_need_explain])
[20]:
print("Predicted class for sample X = [%f, %f] is %d and real class is %d" % (Xtest[sample_need_explain, 0], Xtest[sample_need_explain, 1], y_pred_input_0, ytest[sample_need_explain]))
Predicted class for sample X = [0.571640, 0.233700] is 2 and real class is 2
[21]:
print("Membership values:")
for key, val in mem_val_classes.items():
    print("Class %d has the maximum membership value = %f" % (key, val))

for key in min_points_classes:
    print("Class %d has the representative hyperbox: V = %s and W = %s" % (key, min_points_classes[key], max_points_classes[key]))
Membership values:
Class 1 has the maximum membership value = 0.957157
Class 2 has the maximum membership value = 0.995862
Class 1 has the representative hyperbox: V = [0.55763 0.40507] and W = [0.58339 0.43813]
Class 2 has the representative hyperbox: V = [0.57285 0.24904] and W = [0.66773 0.31638]

Show input sample and hyperboxes belonging to each class. In 2D, we can show rectangles or use parallel coordinates

Using rectangles to show explanations

[22]:
rfmnn_clf.show_sample_explanation(Xtest[sample_need_explain], Xtest[sample_need_explain], min_points_classes, max_points_classes, y_pred_input_0, "2D")

Using parallel coordinates. This mode best fits for any dimensions

[23]:
# Create a parallel coordinates graph
rfmnn_clf.show_sample_explanation(Xtest[sample_need_explain], Xtest[sample_need_explain], min_points_classes, max_points_classes, y_pred_input_0, file_path="par_cord/rfmnn_par_cord.html")
[24]:
# Load parallel coordinates to display on the notebook
from IPython.display import IFrame
# We load the parallel coordinates from GitHub here for demostration in readthedocs
# On the local notebook, we only need to load from the graph storing at 'par_cord/rfmnn_par_cord.html'
IFrame('https://uts-caslab.github.io/hyperbox-brain/docs/tutorials/par_cord/rfmnn_par_cord.html', width=820, height=520)
[24]: