---
title: 'Partitioning Cluster Analysis with Possibilistic C-Means'
author: 'Zeynel Cebeci'
date: '`2017-11-10`'
output:
  html_document:
    theme: yeti
    highlight: kate
    toc: true
    toc_depth: 2
    toc_float:
      collapsed: false
      smooth_scroll: false
    df_print: paged
    code_folding: show
    number_sections: true
vignette: >
  %\VignetteIndexEntry{Partitioning Cluster Analysis with Possibilistic C-Means}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding[UTF-8]{inputenc}
---
<style>
body {
text-align: justify}
</style>

# PREPARING FOR THE ANALYSIS
## Install and load the package ppclust
This vignette is designed to be used with the '`ppclust`' package. You can download the recent version of the package from CRAN with the following command:

```{r, eval=FALSE, message=FALSE, warning=FALSE}
install.packages("ppclust")
```

If you have already installed '`ppclust`', you can load it into R working environment by using the following command:

```{r, echo=TRUE, message=FALSE, warning=FALSE}
library(ppclust)
```

## Load the required packages
For visualization of the clustering results, some examples in this vignette use the functions from some cluster analysis packages such as '`cluster`', '`fclust`' and '`factoextra`'. Therefore, these packages should be loaded into R working environment with the following commands:

```{r, echo=TRUE, message=FALSE, warning=FALSE}
library(factoextra)
library(cluster)
library(fclust)
```

## Load the data set 
We demonstrate PCM on the Iris data set (Anderson, 1935) which is a real data set of the four features (Sepal.Length, Sepal.Width, Petal.Length and Petal.Width) of 150 iris flowers. The data set contains 50 samples from each of three iris species which is represented with the class variable in the last column of data set. One of these three natural clusters (Class 1) is linearly well-separated from the other two clusters, while Classes 2 and 3 have some overlap as seen in the plot below.

```{r echo=TRUE, message=FALSE, warning=FALSE, cols.print=5, rows.print=10}
data(iris)
x=iris[,1:4]
head(x, 5)
tail(x, 5)
```

Plot the data by the classes of iris species

```{r fig.width=7, fig.height=6}
pairs(x, col=iris[,5])
```

# POSSIBILISTIC C-MEANS CLUSTERING

Possibilistic C-Means (PCM) clustering algorithm was proposed by Krishnapuram and Keller (1993) in order to overcome the noise sensitivity problem of FCM. The algorithm differs from the other clustering algorithms that the resulting partition of the data can be interpreted as a possibilistic partition, and the membership values can be interpreted as degrees of possibility of the points belonging to the classes, i.e., the compatibilities of the points with the class prototypes (Krishnapuram & Keller, 1993). PCM relaxes the probabilistic constraint on the sum of the memberships of an object to all clusters in FCM. However, PCM must run on the fuzzy clustering results of FCM in order to calculate the vector $\vec{\Omega}$. Although it solves the noise sensitivity problem of FCM, the performance of PCM depends heavily on the initialization and often deteriorates due to the coincident clustering problem (Filippone et al, 2007).  

## Run PCM with Single Start
### Initialization
In order to start PCM as well as the other alternating optimization algorithms, an initialization step is required to build the initial cluster prototypes matrix and fuzzy membership degrees matrix. 

PCM is started with an integer specifying the number of clusters. In this case, the prototypes matrix is internally generated by using any of the prototype initalization techniques which are included in the package '`inaparc`'. The default initialization technique is *K-means++* with the current version of `pcm` function in this package. In the following code block, PCM runs for three clusters with the default values of the remaining arguments.

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm <- pcm(x, centers=3)
```

In order to generate the matrices of cluster prototypes and membership degrees, users can choose any of existing initialization algorithms in the R package '`inaparc`'. For this purpose, `alginitv` is used for assigning the cluster prototypes as shown for `inofrep` prototype initialization as follows:

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm <- pcm(x, centers=3, alginitv="inofrep")
```
Although the prototypes can be automatically initialized by using the function `pcm`, the users can also supply their own initial matrices as the input arguments of the function. In fact, PCM often suffers from stability problems if it is not initialized with terminal outputs of a corresponding probabilistic algorithm. Therefore, in order to compute some of the input arguments such as the cluster prototypes and mobilization scale parameter it needs fuzzy partitioning results of a probabilistic algorithm, i.e. FCM, (Timm et al, 2004).

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.fcm <- fcm(x, centers=3)
res.pcm <- pcm(x, centers=res.fcm$v, memberships=res.fcm$u)
```
In the first line of above code chunk, FCM is run to obtain its terminal outputs and used as the input arguments of PCM as shown in the second line of the code chunk. If these arguments are not directly specified by the user they are automatically formed with an internal run of the FCM. But the function cancels to use the terminal outputs of FCM if the input argument `fcmrun` is set to `FALSE`. 

In general, the squared Euclidean distance metric is used with PCM in order to compute the distances between the cluster centers and the data objects. Users can specify the other distance metrics with the argument `dmetric` as follows:

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm <- pcm(x, centers=3, dmetric="euclidean")
```
Although the argument eta ($\eta$), typicality exponent is usually choosen as `2` in most of the applications using PCM, users can increase $\eta$ to higher values in order to make the typicalities more strict as follows:

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm <- pcm(x, centers=3, eta=4)
```

> There are other input arguments available with the function `pcm` to control the run of PCM algoritm. For the details, see `pcm` in  the package manual of `ppclust`.

### Clustering Results
#### Typicality Degrees Matrix
The typicality degrees matrix is the main output of the function `pcm`. The example code chuck below shows the top and bottom five rows of the typicality matrix.

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm <- pcm(x, centers=3)
head(res.pcm$t, 5)
tail(res.pcm$t, 5)
```

#### Initial and Final Cluster Prototypes
Initial and final cluster prototypes matrices can be achieved as follows:

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm$v0
res.pcm$v
```
#### Summary of Clustering Results
The function `pcm` returns the clustering results as an intance of '`ppclust`' class. This object is summarized with the `summary` method of the package '`ppclust`' as follows:

```{r echo=TRUE, message=FALSE, warning=FALSE}
summary(res.pcm)
```

All available components of the '`ppclust`' object are listed at the end of summary. These elements can be accessed using as the attributes of the object. For example, the execution time of the run of PCM is accessed as follows:

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm$comp.time
```

## Run PCM with Multiple Starts
In order to find an optimal solution, the function `pcm` can be started for multiple times. As seen in the following code chunk, the argument `nstart` is used for this purpose. 

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm <- pcm(x, centers=3, nstart=5)
```

When the multiple start is performed, either initial cluster prototypes or initial membership degrees could be wanted to keep unchanged between the starts of algorithm. In this case, the arguments `fixcent` and `fixmemb` are used for fixing the initial cluster prototypes matrix and initial membership degrees matrix, respectively.

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm <- pcm(x, centers=3, nstart=5, fixmemb=TRUE)
```

> Both the prototypes and memberships cannot be fixed at the same time.

### Display the best solution
The clustering result contains some outputs providing information about some components such as the objective function values, number of iterations and computing time obtained with each start of the algorithm. The following code chunk demonstrates these outputs. 

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm$func.val
res.pcm$iter
res.pcm$comp.time
```
Among the outputs from succesive starts of the algorithm, the best solution is obtained from the start giving the minimum value of the objective function, and stored as the final clustering result of the multiple starts of PCM.

```{r echo=TRUE, message=FALSE, warning=FALSE}
res.pcm$best.start
```

### Display the summary of clustering results
As described for the single start of PCM above, the result of multiple starts of PCM is displayed by using `summary` method of the '`ppclust`' package.

```{r echo=TRUE, message=FALSE, warning=FALSE}
summary(res.pcm)
```

# VISUALIZATION OF THE CLUSTERING RESULTS

## Pairwise Scatter Plots
There are many ways of visual presentations of the clustering results. One common techique is to display the clustering results by using scatter plots of pairs of the features. For this purpose, the `plotcluster` can be used to plot the clustering results with the color palette 1 and transparent colors as follows:

```{r fig.width=7, fig.height=6}
plotcluster(res.pcm, cp=1, trans=TRUE)
```

In the above figure, the plot shows the objects which have typicality degrees greater than 0.5. In order to filter the objects for different typicality degrees, the  value of `tv` argument can be changed as follows:

```{r fig.width=7, fig.height=6}
plotcluster(res.pcm, cp=1, tv=0.2, trans=TRUE)
```

> The details can be viewed on the package manual for the function `plotcluster`. 

## Cluster Plot with fviz_cluster
There are some nice versions of the cluster plots in some of the R packages. One of them is the function `fviz_cluster` of the package '`factoextra`' (Kassambara & Mundt, 2017). In order to use this function for the fuzzy clustering result, first the fuzzy clustering object of `ppclust` should be converted to `kmeans` object by using the `ppclust2` of the package '`ppclust`' as shown in the first line of the code chunk below:

```{r fig.width=7, fig.height=6}
res.pcm2 <- ppclust2(res.pcm, "kmeans")
factoextra::fviz_cluster(res.pcm2, data = x, 
  ellipse.type = "convex",
  palette = "jco",
  repel = TRUE)
```

## Cluster Plot with clusplot
User can also use the function `clusplot` in the package '`cluster`' (Maechler et al, 2017) for plotting the clustering results. For this purpose, the fuzzy clustering object of `ppclust` should be converted to `fanny` object by using the `ppclust2` function of the package '`ppclust`' as seen in the following code chunk.

```{r fig.width=7, fig.height=6}
res.pcm3 <- ppclust2(res.pcm, "fanny")

cluster::clusplot(scale(x), res.pcm3$cluster,  
  main = "Cluster plot of Iris data set",
  color=TRUE, labels = 2, lines = 2, cex=1)
```	 

#References{-}

Anderson, E. (1935). The irises of the GASPE peninsula, in *Bull. Amer. Iris Soc.*, 59: 2-5.

Bezdek J.C. (1981). \emph{Pattern recognition with fuzzy objective function algorithms}. Plenum, NY. https://isbnsearch.org/isbn/0306406713

Krishnapuram, R. & Keller, J.M. (1993). A possibilistic approach to clustering. *IEEE Transactions on Fuzzy Systems*, 1(2):98-110.

Krishnapuram, R. & Keller, J.M. (1996). The possibilistic c-means algorithm: insights and recommendations. *IEEE Transactions on Fuzzy Systems*, 4(3):385-393.

Timm, H., Borgelt, C., Döring, C. & Kruse, R. (2004). An extension to possibilistic fuzzy cluster analysis. *Fuzzy Sets and Systems*, 147 (1): 3-16.

Filippone, M., Masulli, F., & Rovetta, S. (2007). Possibilistic clustering in feature space. In *Int. Workshop on Fuzzy Logic and Applications*, pp. 219-226. Springer, Berlin, Heidelberg.

Ferraro, M.B. & Giordani, P. (2015). A toolbox for fuzzy clustering using the R programming language. *Fuzzy Sets and Systems*, 279, 1-16. http://dx.doi.org/10.1016/j.fss.2015.05.001

Kassambara, A. & Mundt, F. (2017). factoextra: Extract and Visualize the Results of Multivariate Data Analyses. R package version 1.0.5. https://CRAN.R-project.org/package=factoextra

Maechler, M., Rousseeuw, P., Struyf, A., Hubert, M. & Hornik, K.(2017).  cluster: Cluster Analysis Basics and Extensions. R package version 2.0.6. https://CRAN.R-project.org/package=cluster
