--- title: "Introduction to the evclass package" author: "Thierry Denoeux" date: "`r Sys.Date()`" output: rmarkdown::html_vignette bibliography: tdenoeux.bib vignette: > %\VignetteIndexEntry{Introduction to the evclass package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- The package `evclass` contains methods for *evidential classification*. An evidential classifier quantifies the uncertainty about the class of a pattern by a Dempster-Shafer mass function. In evidential *distance-based* classifiers, the mass functions are computed from distances between the test pattern and either training pattern, or prototypes. Classical classifiers such as logistic regression, radial basis function (RBF) neural networks and multilayer perceptrons with a softmax output layer can also be seen as evidential classifiers. The user is invited to read the papers cited in this vignette to get familiar with the main concepts underlying evidential classification. These papers can be downloaded from the author's web site, at . Here, we provide a short guided tour of the main functions in the `evclass` package. The classification methods implemented to date are: * The evidential K-nearest neighbor classifier [@denoeux95a] [@zouhal97b]; * The evidential neural network classifier [@denoeux00a]; * RBF neural network with weight-of-evidence interpretation [@denoeux19d] [@huang22]. Also included in this package are functions to express the outputs of already trained logistic regression of multilayer perceptron classifiers in the belief function framework, using the approach described in [@denoeux19d]. You first need to install this package: ```{r, message=FALSE} library(evclass) ``` The following sections contain a brief introduction on the way to use the main functions in the package `evclass` for evidential classification. ## Evidential K-nearest neighbor classifier The principle of the evidential K-nearest neighbor (EK-NN) classifier is explained in [@denoeux95a], and the optimization of the parameters of this model is presented in [@zouhal97b]. The reader is referred to these references. Here, we focus on the practical application of this method using the functions implemented in `evclass`. Consider, for instance, the `ionosphere` data. This dataset consists in 351 instances grouped in two classes and described by 34 numeric attributes. The first 175 instances are training data, the rest are test data. Let us first load the data, and split them into a training set and a test set. ```{r} data(ionosphere) xtr<-ionosphere$x[1:176,-2] ytr<-ionosphere$y[1:176] xtst<-ionosphere$x[177:351,-2] ytst<-ionosphere$y[177:351] ``` The EK-NN classifier is implemented as three functions: `EkNNinit` for initialization, `EkNNfit` for training, and `EkNNval` for testing. Let us initialize the classifier and train it on the `ionosphere` data, with $K=5$ neighbors. (If the argument `param` is not passed to `EkNNfit`, the function `EkNNinit` is called inside `EkNNfit`; here, we make the call explicit for clarity). ```{r} set.seed(20221229) param0<- EkNNinit(xtr,ytr) options=list(maxiter=300,eta=0.1,gain_min=1e-5,disp=FALSE) fit<-EkNNfit(xtr,ytr,param=param0,K=5,options=options) ``` The list `fit` contains the optimized parameters, the final value of the cost function, the leave-one-out (LOO) error rate, the LOO predicted class labels and the LOO predicted mass functions. Here the LOO error rate and confusion matrix are: ```{r} print(fit$err) table(fit$ypred,ytr) ``` We can then evaluate the classifier on the test data: ```{r} val<-EkNNval(xtrain=xtr,ytrain=ytr,xtst=xtst,K=5,ytst=ytst,param=fit$param) print(val$err) table(val$ypred,ytst) ``` To determine the best value of $K$, we may compute the LOO error for different candidate value. Here, we will all values between 1 and 15 ```{r} err<-rep(0,15) i<-0 for(K in 1:15){ fit<-EkNNfit(xtr,ytr,K,options=list(maxiter=100,eta=0.1,gain_min=1e-5,disp=FALSE)) err[K]<-fit$err } plot(1:15,err,type="b",xlab='K',ylab='LOO error rate') ``` The minimum LOO error rate is obtained for $K=8$. The test error rate and confusion matrix for that value of $K$ are obtained as follows: ```{r} fit<-EkNNfit(xtr,ytr,K=8,options=list(maxiter=100,eta=0.1,gain_min=1e-5,disp=FALSE)) val<-EkNNval(xtrain=xtr,ytrain=ytr,xtst=xtst,K=8,ytst=ytst,param=fit$param) print(val$err) table(val$ypred,ytst) ``` ## Evidential neural network classifier In the evidential neural network classifier, the output mass functions are based on distances to protypes, which allows for faster classification. The prototypes and their class-membership degrees are leanrnt by minimizing a cost function. This function is defined as the sum of an error term and, optionally, a regularization term. As for the EK-NN classifier, the evidential neural network classifier is implemented as three functions: `proDSinit` for initialization, `proDSfit` for training and `proDSval` for evaluation. Let us demonstrate this method on the `glass` dataset. This data set contains 185 instances, which can be split into 89 training instances and 96 test instances. ```{r} data(glass) xtr<-glass$x[1:89,] ytr<-glass$y[1:89] xtst<-glass$x[90:185,] ytst<-glass$y[90:185] ``` We then initialize a network with 7 prototypes: ```{r} param0<-proDSinit(xtr,ytr,nproto=7,nprotoPerClass=FALSE,crisp=FALSE) ``` and train this network without regularization: ```{r} options<-list(maxiter=500,eta=0.1,gain_min=1e-5,disp=20) fit<-proDSfit(x=xtr,y=ytr,param=param0,options=options) ``` Finally, we evaluate the performance of the network on the test set: ```{r} val<-proDSval(xtst,fit$param,ytst) print(val$err) table(ytst,val$ypred) ``` If the training is done with regularization, the hyperparameter `mu` needs to be determined by cross-validation. ## Decision In the belief function framework, there are several definitions of expectation. Each of these definitions results in a different decision rule that can be used for classification. The reader is referred to [@denoeux96b] for a detailed description of theses rules and there application to classification. Here, we will illustrate the use of the function `decision` for generating decisions. We consider the Iris dataset from the package `datasets`. To plot the decisions regions, we will only use two input attributes: 'Petal.Length' and 'Petal.Width'. This code plots of the data and trains the evidential neural network classifiers with six prototypes: ```{r, fig.width=6, fig.height=6} data("iris") x<- iris[,3:4] y<-as.numeric(iris[,5]) c<-max(y) plot(x[,1],x[,2],pch=y,xlab="Petal Length",ylab="Petal Width") param0<-proDSinit(x,y,6) fit<-proDSfit(x,y,param0) ``` Let us assume that we have the following loss matrix: ```{r} L=cbind(1-diag(c),rep(0.3,c)) print(L) ``` This matrix has four columns, one for each possible act (decision). The first three decisions correspond to the assignment to each the three classes. The losses are 0 for a correct classification, and 1 for a misclassification. The fourth decision is rejection. For this act, the loss is 0.3, whatever the true class. The following code draws the decision regions for this loss matrix, and three decision rules: the minimization of the lower, upper and pignistic expectations (see [@denoeux96b] for details about these rules). ```{r, fig.width=6, fig.height=6} xx<-seq(-1,9,0.01) yy<-seq(-2,4.5,0.01) nx<-length(xx) ny<-length(yy) Dlower<-matrix(0,nrow=nx,ncol=ny) Dupper<-Dlower Dpig<-Dlower for(i in 1:nx){ X<-matrix(c(rep(xx[i],ny),yy),ny,2) val<-proDSval(X,fit$param) Dupper[i,]<-decision(val$m,L=L,rule='upper') Dlower[i,]<-decision(val$m,L=L,rule='lower') Dpig[i,]<-decision(val$m,L=L,rule='pignistic') } contour(xx,yy,Dlower,xlab="Petal.Length",ylab="Petal.Width",drawlabels=FALSE) for(k in 1:c) points(x[y==k,1],x[y==k,2],pch=k) contour(xx,yy,Dupper,xlab="Petal.Length",ylab="Petal.Width",drawlabels=FALSE,add=TRUE,lty=2) contour(xx,yy,Dpig,xlab="Petal.Length",ylab="Petal.Width",drawlabels=FALSE,add=TRUE,lty=3) ``` As suggested in [@denoeux96b], we can also consider the case where there is an unknown class, not represented in the learning set. We can then construct a loss matrix with four rows (the last row corresponds to the unknown class) and five columns (the last column corresponds to the assignment to the unknown class). Assume that the losses are defined as follows: ```{r} L<-cbind(1-diag(c),rep(0.2,c),rep(0.22,c)) L<-rbind(L,c(1,1,1,0.2,0)) print(L) ``` We can now plot the decision regions for the pignistic decision rule: ```{r, fig.width=6, fig.height=6} for(i in 1:nx){ X<-matrix(c(rep(xx[i],ny),yy),ny,2) val<-proDSval(X,fit$param,rep(0,ny)) Dlower[i,]<-decision(val$m,L=L,rule='lower') Dpig[i,]<-decision(val$m,L=L,rule='pignistic') } contour(xx,yy,Dpig,xlab="Petal.Length",ylab="Petal.Width",drawlabels=FALSE) for(k in 1:c) points(x[y==k,1],x[y==k,2],pch=k) ``` The outer region corresponds to the assignment to the unknown class: this hypothesis becomes more plausible when the test vector is far from all the prototypes representing the training data. ## RBF neural network classifier As shown in [@denoeux19d], the calculations performed in the softmax layer of a feedforward neural network can be interpreted in terms of combination of evidence by Dempster's rule. The output class probabilities can be seen as normalized plausibilities according to an underlying belief function. Applying these ideas to a radial basis function (RBF) network, it is possible to derive an alternative evidential classifier with properties similar to those of the evidential neural network classifier described above [@huang22]. As for the EK-NN and evidential neural network classifiers, the RBF classifier is implemented as three functions: `RBFinit` for initialization, `RBFfit` for training and `RBFval` for evaluation. Let us demonstrate this method on the `glass` dataset. We initialize a network with 7 prototypes: ```{r} param0<-RBFinit(xtr,ytr,nproto=7) ``` and train this network with regularization coefficient $\lambda=0.001$: ```{r} fit<-RBFfit(xtr,ytr,param0,lambda=0.001,control=list(fnscale=-1,maxit=1000)) ``` Finally, we evaluate the performance of the network on the test set: ```{r} val<-RBFval(xtst,fit$param,ytst) print(val$err) table(ytst,val$ypred) ``` The output mass functions are contained in `val$Belief`: ```{r} val$Belief$mass[1:5,] val$Belief$pl[1:5,] val$Belief$bel[1:5,] ``` We note that, in contrast with the outputs from evidential k-NN and neural network classifiers, the output mass functions based on weights of evidence have $2^M-1$ focal sets, where $M$ is the number of classes. The focal sets are obtained as ```{r} val$Belief$focal ``` ## Latent mass functions from neural network classifiers As shown in [@denoeux19d], logistic regression and multilayer feedforward neural networks can be viewed as converting input or higher-level features into Dempster-Shafer mass functions and aggregating them by Dempster's rule of combination. The probabilistic outputs of these classifiers are the normalized plausibilities corresponding to the underlying combined mass function. This mass function is more informative than the output probability distribution. Here, we illustrate the computation of mass functions for trained logistic regression and multilayer perceptron classifiers. ### Logistic regression Let us first consider again the `ionosphere` dataset: ```{r} data(ionosphere) x<-ionosphere$x[,-2] y<-ionosphere$y-1 ``` Let us fit a logistic regression classifier on these data: ```{r,warning=FALSE} fit<-glm(y ~ x,family='binomial') ``` The optimal cofficients (denoted as $\alpha$ and $\beta$ in [@denoeux19d] can be computed using function `calcAB`: ```{r} AB<-calcAB(fit$coefficients,colMeans(x)) ``` Using these coefficients, we can then compute the output mass functions and the corresponding contour functions: ```{r} Bel<-calcm(x,AB$A,AB$B) Bel$focal Bel$mass[1:5,] Bel$pl[1:5,] ``` ### Multilayer perceptron Let us now consider again the `glass` dataset: ```{r} data(glass) M<-max(glass$y) d<-ncol(glass$x) n<-nrow(glass$x) x<-scale(glass$x) y<-as.factor(glass$y) ``` We train a neural network with $J=5$ hidden units, using function `nnet` of package `nnet`, with a regularization coefficient `decay=0.01`: ```{r} library(nnet) J<-5 fit<-nnet(y~x,size=J,decay=0.01) ``` We first need to extract the two layers of weights and to recompute the outputs from the hidden units; ```{r} W1<-matrix(fit$wts[1:(J*(d+1))],d+1,J) W2<-matrix(fit$wts[(J*(d+1)+1):(J*(d+1) + M*(J+1))],J+1,M) a1<-cbind(rep(1,n),x)%*%W1 o1<-1/(1+exp(-a1)) ``` We can then compute the output mass functions as ```{r} AB<-calcAB(W2,colMeans(o1)) Bel<-calcm(o1,AB$A,AB$B) Bel$mass[1:5,] Bel$pl[1:5,] ``` ## References