Spatial Fuzzy CMean with R"

knitr::opts_chunk$set(echo = TRUE)


This document is a short introduction to the package geocmeans. It implements fuzzy classification methods bringing spatial information and neighbouring in its calculation

In their article, @cai2007fast described the method, originally applied in the analysis of brain imagery. The generalized version of the spatial fuzzy c-means is presented by @zhao2013kernel.

@gelb2021apport applied the method to socio-residential and environmental data comparing the results with other unsupervised classification algorithms (in French).

There are actually numerous packages and functions to perform unsupervised classification in R (hclust, kmeans, cmeans, factoextra, etc.). However, these methods are not always well-suited to analyze spatial data. Indeed, they do not account for spatial information such as proximity or contiguity between observations. This may lead to solutions for which close observations end up in different groups event though they are very similar.

To our knowledge, the package ClustGeo is the only package proposing an unsupervised classification method which directly consider spatial proximity between observations. The proposed approach is appealing because the user can select a parameter (alpha) that controls the weight of the spatial distance matrix (calculated between observations with their locations) versus the semantic distance matrix (calculated between observations with their variables).

However, this method belongs to the category of "hard-clustering" algorithms. Each observation ends up in one cluster/group. The main draw-back here is the difficulty to identify observations that are undecided, at the frontier of two clusters/groups. The soft or fuzzy clustering algorithms provide more information because they calculate the "probability" of each observation to belong to each group.

The algorithms SFCM (spatial fuzzy c-means) and SGFCM (spatial generalized fuzzy c-means) propose to combine the best of both worlds.

The package geocmeans is an implementation in R of these methods. It comes with a set of functions to facilitate the analysis of the final membership matrices:

The general workflow for applying a spatial fuzzy clustering algorithm with geocmeans is described with the following figure.

Image Title{height=800px}

Loading the packages and the data

geocmeans comes with a toy dataset LyonIris, combining many demographic and environmental variables aggregated at the scale of the Iris (aggregated units for statistical information) in Lyon (France).

Note that the dataset used for a fuzzy classification can only contain continuous variables. For dataset with categorical variables, one could start with a PCA (Principal Component Analysis), MCA (multiple Correspondence Analysis) or a MDFA (Mixed Data Factor Analysis) and uses the obtained factors as inputs for the clustering.

Before starting the analysis, the data must be standardized because most of the calculus is based on Euclidean distance (we plan to also include Manhattan distance in a future release).

#charging packages and data


# selecting the columns for the analysis
AnalysisFields <-c("Lden","NO2","PM25","VegHautPrt","Pct0_14",

# rescaling the columns
Data <- LyonIris@data[AnalysisFields]
for (Col in names(Data)){
  Data[[Col]] <- scale(Data[[Col]])

# preparing some elements for further mapping
LyonIris$OID <- as.character(1:nrow(LyonIris))
FortiData <- ggplot2::fortify(LyonIris,region="OID")
# loading the pre-calculated results
load(system.file("extdata", "results_vignette_intro.rda",
                           package = "geocmeans", mustWork = TRUE))

Classical Kmeans

To explore the dataset and choose the right number of cluster/groups (k) we propose to start with a classical kmeans.

# finding the best k by using the r2 of the classification
# trying for k from 2 to 10
R2s <- sapply(2:10,function(k){
  Clust <- kmeans(Data,centers=k,iter.max = 150)
  R2 <- Clust$betweenss / Clust$totss

Df <- data.frame(K=2:10,
                 R2 = R2s)

  xlab("Number of groups")+
  ylab("R2 of classification")

By plotting the R-squared of the kmeans classification for each k between 2 and 10, we can see a first elbow at k=3. But this small number of groups leads to a classification explaining only 43% of the original data variance. We decide to keep k=4 to have one more group in the analysis.

Let us map the obtained groups.

KMeanClust <-  kmeans(Data,centers=4,iter.max = 150)
LyonIris$Cluster <-paste("cluster",KMeanClust$cluster,sep="_")

# mapping the groups
DFmapping <- merge(FortiData,LyonIris,by.x="id",by.y="OID")

  coord_fixed(ratio = 1)+
  scale_fill_manual(name="Cluster",values = c("cluster_1"="palegreen3",
  theme( axis.title = ggplot2::element_blank(),
    axis.text = ggplot2::element_blank(),
    axis.ticks = ggplot2::element_blank()

We can clearly distinguish 4 strong spatial structures, but with some mixing between the clusters.

We could now compare this solution with a classical c-means algorithm.

Classical c-means and generalized c-means

The classical c-means is a simple method to perform fuzzy unsupervised classification. The package geocmeans proposes the function CMeans. We set the fuzziness degree (m) to 1.5.

We do not present the algorithm here, but only the two main formulas.

The first one is used to update the values of the membership matrix at each iteration $u_ik$

$$u_{ik} = \frac{(||x_{k} - v{i}||^{2}) ^{(-1/(m-1))}}{\sum{j=1}^c(||x_{k} - v{_j}||^2 )^{(-1/(m-1))}}$$ And the second one to update the centers of the clusters

$$v_{i} = \frac{\sum_{k=1}^N u_{ik}^m(x_{k})}{\sum_{k=1}^N u_{ik}^m}$$

With :

Cmean <- CMeans(Data,4,1.5,500,standardize = FALSE, seed = 456, tol = 0.00001, verbose = FALSE)

We can now use the function calcqualityIndexes which combines many indices from the package fclust to analyze the quality of the classification. We will use these values later for the purpose of comparisons among the different algorithms.

calcqualityIndexes(Data, Cmean$Belongings, m = 1.5)

Note, geocmeans also proposes a so-called generalized version of the c-means algorithm. It is known to accelerate convergence and yield less fuzzy results by adjusting the membership matrix at each iteration. It requires an extra beta parameter controlling the strength of the modification. The modification only affects the formula updating the membership matrix.

$$u_{ik} = \frac{(||x_{k} - v{i}||^{2} - \beta_k) ^{(-1/(m-1))}}{\sum{j=1}^c(||x_{k} - v{_j}||^2 - \beta_k)^{(-1/(m-1))}}$$

with $\beta_k = min(||x_{k} - v||^2)$ and $0 \leq \beta \leq 1$.

To select an appropriate value for this parameter, we will try all the possible values between 0 and 1 with a step of 0.05.

beta_values <- selectParameters("GFCM",data = Data, k = 4, m = 1.5,
                                 beta = seq(0,1,0.05), spconsist = FALSE,
                                 tol = 0.00001, seed = 456)
             col.names = c("beta", "silhouette index",
                           "Xie and Beni index", "explained inertia"),digits = 3)

Considering the table above, we select beta = 0.7, it maintains a good silhouette index, and increases Xie and Beni index and explained inertia. Let us compare the results of GFCM and FCM.

GCmean <- GCMeans(Data,k = 4,m = 1.5, beta = 0.7,500,standardize = FALSE, seed=456,
                  tol = 0.00001, verbose = FALSE)
r1 <- calcqualityIndexes(Data,GCmean$Belongings,m=1.5)
r2 <- calcqualityIndexes(Data,Cmean$Belongings,m=1.5)
df <- cbind(unlist(r1), unlist(r2))

             digits = 3,col.names = c("GFCM", "FCM"))

The results indicate that the GFCM provides a solution that is less fuzzy (higher explained inertia and lower partition entropy) but keeps a good silhouette index and an even better Xie and Beni index.

We can now map the two membership matrices and the most likely group for each observation. To do so, we use the function mapClusters from geocmeans. We propose here to define a threshold of 0.45. If an observation only has values below this probability in a membership matrix, it will be labeled as "undecided" (represented with transparency on the map).

We can compare the maps of the classical c-means and the generalized version.

cmeansMaps<- mapClusters(LyonIris,Cmean$Belongings,undecided = 0.45)
GcmeansMaps<- mapClusters(LyonIris,GCmean$Belongings,undecided = 0.45)

          nrow = 1, ncol = 2, common.legend = TRUE, legend = "bottom")
          nrow = 1, ncol = 2, common.legend = TRUE, legend = "bottom")
          nrow = 1, ncol = 2, common.legend = TRUE, legend = "bottom")
          nrow = 1, ncol = 2, common.legend = TRUE, legend = "bottom")
          nrow = 1, ncol = 2, common.legend = TRUE, legend = "bottom")

As expected, the results are very similar, but the generalized version provides a more clear-cut classification.

Spatial c-means and generalized c-means

Selecting alpha for SFCM

Now we can use the SFCM function to perform a spatial c-means. The first step is to define a spatial weight matrix indicating which observations are neighbours and the strength of their relationship. We propose here to use a basic queen neighbour matrix (built with spdep). The matrix must be row-standardized to ensure that the interpretation of all the parameters remains clear.


Neighbours <- poly2nb(LyonIris,queen = TRUE)
WMat <- nb2listw(Neighbours,style="W",zero.policy = TRUE)

The main challenge with the SFCM method is to select the parameter alpha. It represents the weight of the spatial dimension (lagged values) in the calculus of the membership matrix and the cluster centers.

The two following formulas show how the functions updating the membership matrix and the centers of the clusters are modified.

$$u_{ik} = \frac{(||x_{k} - v{i}||^2 + \alpha||\bar{x{k}} - v{i}||^2)^{(-1/(m-1))}}{\sum{j=1}^c(||x_{k} - v{j}||^2 + \alpha||\bar{x{k}} - v{_j}||^2)^{(-1/(m-1))}}$$

$$v_{i} = \frac{\sum_{k=1}^N u_{ik}^m(x_{k} + \alpha\bar{x_{k}})}{(1 + \alpha)\sum_{k=1}^N u_{ik}^m}$$ with $\bar{x}$ the lagged version of x and $\alpha \geq 0$

As the formula suggests, the SFCM can be seen as a spatially smoothed version of the classical c-means and alpha controls the degree of spatial smoothness. This smoothing can be interpreted as an attempt to reduce spatial overfitting of the classical c-means.

To select alpha, we propose to check all possible values between 0 and 2 with a step of 0.05.

DFindices_SFCM <- selectParameters(algo = "SFCM", data = Data,
                               k = 4, m = 1.5, alpha = seq(0,2,0.05),
                               nblistw = WMat, standardize = FALSE,
                               tol = 0.0001, verbose = FALSE, seed = 456)

Now we are able to check the indices to select the best alpha. The goal is to reduce spatial inconsistency as much as possible and to maintain a good classification quality.

Let us start with the spatial inconsistency. This indicator (developed for this package) calculates the sum of the squared differences between each observation and its neighbours on the membership matrix. Thus, the maximum for each observation is $kj$ with j the number of neighbours for the observation and k* the number of groups. A maximum is reached if each observation has 100% chance belonging to a cluster that is different from all its neighbours. So, when we sum up the values obtained for all the observations, we obtain a quantity of spatial inconsistency. This quantity is divided by the quantity obtained when randomly permuting the rows of the membership matrix. This second quantity represents the spatial inconsistency that we might expect if the observations were randomly scattered in space. We can repeat the permutation step (Monte Carlo approach) and keep the mean of the ratios to have a more robust indicator (see help(spConsistency) for details).

A smaller value indicates a smaller spatial inconsistency and thus a greater spatial consistency. 0 meaning that all observations have exactly the same values in the membership matrix as their neighbours (perfect spatial consistency).

  geom_smooth(aes(x=alpha,y=spConsistency), color = "black")+
  geom_point(aes(x=alpha,y=spConsistency), color = "red")

Not surprisingly, increasing alpha leads to a decrease of the spatial inconsistency. This gain follows an inverse function.

Let us now check the explained inertia

  geom_smooth(aes(x=alpha,y=Explained.inertia), color = "black")+
  geom_point(aes(x=alpha,y=Explained.inertia), color = "red")

As expected, the explained inertia decreases when alpha increases and again follows an inverse function. The classification has to find a compromise between the original values and the lagged values. However, the loss is very small here: only 3% between alpha = 0 and alpha = 2.

To finish here, we can observe the silhouette and Xie and Beni indicators.

  geom_smooth(aes(x=alpha,y=Silhouette.index), color = "black")+
  geom_point(aes(x=alpha,y=Silhouette.index), color = "red")
  geom_smooth(aes(x=alpha,y=XieBeni.index), color = "black")+
  geom_point(aes(x=alpha,y=XieBeni.index), color = "red")

The detail of the meaning of these indicators is beyond the scope of this vignette. Let us just stress that a larger silhouette index indicates a better classification, and a smaller Xie and Beni index indicates a better classification.

After considering all the previous charts, we decide to keep alpha = 0.7 as it seems to provide a good balance between spatial consistency and classification quality in this case.

SFCM <- SFCMeans(Data, WMat, k = 4, m = 1.5, alpha = 0.7,
                 tol = 0.0001, standardize = FALSE,
                 verbose = FALSE, seed = 456)

Selecting alpha and beta for SGFCM

It is also possible to use the so-called generalized version of the spatial c-means. In that case, we must define both alpha and beta.

The next formula shows how the membership matrix is updated at each iteration. Note that the centres of the clusters are updated with the same formula as SFCM.

$$u_{ik} = \frac{(||x_{k} - v{i}||^2 -\beta_k + \alpha||\bar{x{k}} - v{i}||^2)^{(-1/(m-1))}}{\sum{j=1}^c(||x_{k} - v{j}||^2 -\beta_k + \alpha||\bar{x{k}} - v{_j}||^2)^{(-1/(m-1))}}$$

Because we select a high resolution for our grid search of alpha and beta, we will use a multiprocessing approach.

DFindices_SFGCM <- = "SGFCM", data = Data,
                               k = 4, m = 1.5, alpha = seq(0,2,0.05),
                               beta = seq(0,0.85,0.05),
                               nblistw = WMat, standardize = FALSE, chunk_size = 50,
                               tol = 0.0001, verbose = FALSE, seed = 456)
ggplot(DFindices_SFGCM) + 
  geom_raster(aes(x = alpha, y = beta, fill = Silhouette.index),  size = 5) + 
  scale_fill_viridis() +
ggplot(DFindices_SFGCM) + 
  geom_raster(aes(x = alpha, y = beta, fill = XieBeni.index),  size = 5) + 
  scale_fill_viridis() +
ggplot(DFindices_SFGCM) + 
  geom_raster(aes(x = alpha, y = beta, fill = spConsistency),  size = 5) + 
  scale_fill_viridis() +

The first two plots indicate that some specific pairs of alpha and beta yield good results in the range 0.8 < alpha < 1.2 and 0.6 < beta < 0.8. The last plot shows that the selection of beta has no impact on the spatial consistency.

Considering the previous plots, we decide to retain the solution with beta = 0.65 and alpha = 0.95 which yield very good results for all the indices considered.

SGFCM <- SGFCMeans(Data,WMat,k = 4,m=1.5, alpha=0.95, beta = 0.65,
                    tol=0.0001, standardize = FALSE, verbose = FALSE, seed = 456)

Again, we compare here the generalized and the classical version of the spatial c-means algorithm.

r1 <- calcqualityIndexes(Data, SFCM$Belongings,m = 1.5)
r2 <- calcqualityIndexes(Data, SGFCM$Belongings,m = 1.5)

diagSFCM <- spatialDiag(SFCM$Belongings, nblistw = WMat,
                        undecided = 0.45,nrep = 500)
diagSGFCM <- spatialDiag(SGFCM$Belongings, nblistw = WMat,
                         undecided = 0.45,nrep = 500)

df <- cbind(
row.names(df)[length(row.names(df))] <- "sp.consistency"

knitr::kable(df,digits = 3,col.names = c("SFCM","SGFCM"))

The solution of the SGFCM is better on the semantic and the spatial aspects.

We can compare the maps

SFCMMaps <- mapClusters(geodata = LyonIris, object = SFCM$Belongings,undecided = 0.45)
SGFCMMaps <- mapClusters(geodata = LyonIris, object = SGFCM$Belongings,undecided = 0.45)

ggarrange(SFCMMaps$ProbaMaps[[1]],SGFCMMaps$ProbaMaps[[1]], nrow = 1, ncol = 2,
          common.legend = TRUE, legend = "bottom")
ggarrange(SFCMMaps$ProbaMaps[[2]],SGFCMMaps$ProbaMaps[[2]], nrow = 1, ncol = 2,
          common.legend = TRUE, legend = "bottom")
ggarrange(SFCMMaps$ProbaMaps[[3]],SGFCMMaps$ProbaMaps[[3]], nrow = 1, ncol = 2,
          common.legend = TRUE, legend = "bottom")
ggarrange(SFCMMaps$ProbaMaps[[4]],SGFCMMaps$ProbaMaps[[4]], nrow = 1, ncol = 2,
          common.legend = TRUE, legend = "bottom")
ggarrange(SFCMMaps$ClusterPlot,SGFCMMaps$ClusterPlot, nrow = 1, ncol = 2,
          common.legend = TRUE, legend = "bottom")

Comparing the spatial consistency of FCM, GFCM, SFCM and SGFCM

Now, we can do a deeper spatial analysis and compare the spatial consistency of the four classifications realized (FCM, GFCM, SFCM, SGFCM).

spdiag_1 <- spatialDiag(Cmean$Belongings, nblistw = WMat, nrep=250)
spdiag_2 <- spatialDiag(GCmean$Belongings, nblistw = WMat, nrep=250)
spdiag_3 <- spatialDiag(SFCM$Belongings, nblistw = WMat, nrep=250)
spdiag_4 <- spatialDiag(SGFCM$Belongings, nblistw = WMat, nrep=250)

#looking at the moran I values for each group
moran_table <- data.frame(cbind(spdiag_1$MoranValues$MoranI,
row.names(moran_table) <- paste("cluster ",1:4,sep="")
knitr::kable(moran_table, digits = 3,
             col.names = c("FCM","GFCM","SFCM","SGFCM"),
             caption = "Moran I index for the columns of the membership matrix"

Not surprisingly, the Moran I values calculated on the membership matrices are higher for SFCM and SGFCM, indicating stronger spatial structures in the classifications.

print(c(spdiag_1$SpConsist, spdiag_2$SpConsist,spdiag_3$SpConsist,spdiag_4$SpConsist))

Considering the values of spatial inconsistency, we could check if the value obtained for SGFCM is significantly lower than the one of SFCM. Considering the previous r length(spdiag_3$SpConsistSamples) values obtained by permutations, we can calculate a pseudo p-value:

sum(spdiag_4$SpConsist > spdiag_3$SpConsistSamples) / length(spdiag_3$SpConsistSamples)

It appears that out of r length(spdiag_3$SpConsistSamples) permutations, the observed values of spatial inconsistency of SGFCM are always lower than that of SFCM. The difference is significant at the threshold r 1/length(spdiag_3$SpConsistSamples) (=1/r length(spdiag_3$SpConsistSamples))

We can map the undecided observations of the final solution. These entities should be analyzed more precisely. Selecting them is easy with the function undecidedUnits of the geocmeans package.

Undecided <- undecidedUnits(SGFCM$Belongings,0.45)
LyonIris$FinalCluster <- ifelse(Undecided=="Undecided",

# mapping the groups
DFmapping <- merge(FortiData,LyonIris,by.x="id",by.y="OID")

  coord_fixed(ratio = 1)+
  scale_fill_manual(name="FinalCluster",values = c("cluster_V1"="palegreen3",
  theme( axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank()

It is also possible to visualize the uncertainty by using jittered points. The idea is to draw random points in polygons and attribute them to a group proportionally to the membership values of the polygon the fall in.

colors <- c("palegreen3","firebrick","lightyellow2","steelblue","pink")
uncertaintyMap(LyonIris, SGFCM$Belongings, color = colors)

To quantify and map uncertainty, one could Calculate the Shanon entropy index and use it as a measure of uncertainty with the function calcUncertaintyIndex. A value of 1 indicates that an observation has equal membership values among groups and a value of 0 indicates that an observation belongs to only one group.

LyonIris$entropyidx  <- calcUncertaintyIndex(SGFCM$Belongings)

# mapping the uncertainty
DFmapping <- merge(FortiData,LyonIris,by.x="id",by.y="OID")

  coord_fixed(ratio = 1)+
  labs(title = "Uncertainty evaluation", fill = "entropy index") +
  theme(axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank()

Interpreting the results of the final classification

One can obtain a lot of descriptive information about the final groups with four functions of geocmeans :

summarizeClusters(LyonIris@data[AnalysisFields],belongmatrix = SGFCM$Belongings,
                  weighted = TRUE, dec = 3)
# equivalent to : 
# summary(SGFCM, LyonIris@data[AnalysisFields])
spiderPlots(LyonIris@data[AnalysisFields], SGFCM$Belongings,
            chartcolors = c("darkorange3","grey4","darkgreen","royalblue"))
violinPlots(LyonIris@data[AnalysisFields], SGFCM$Groups)

Ensuring clustering stability

All the clustering algorithms of this package depends on a initial state that might influence the results. A good practice is to check the results to ensure that the groups obtained are stable if we replicate the analysis. The function boost_group_validation proposes an approach based on bootstrapping.

bootvalues <- boot_group_validation(SGFCM, nsim = 1000, maxiter = 1000, 
                                     tol = 0.0001, verbose = FALSE)

We can now check if the groups are stable across simulations.

melted_df <- reshape2::melt(bootvalues$group_consistency)
melted_df$variable <- as.factor(melted_df$variable)

ggplot() +
  geom_histogram(mapping = aes(x = value), data = melted_df, bins = 30) +
  labs(title = "stability of clusters", subtitle = "for 1000 iterations",
       x = "Jaccard index") +
  facet_wrap(vars(variable), ncol=2)

The Jaccard index is calculated at each replication and for each cluster in comparison with the original result. A greater value means a more stable cluster. Values above 0.75 indicate a stable cluster. Values between 0.5 and 0.75 indicate a cluster with some uncertainty. Under 0.5, the cluster tends to dissolve during the iterations. In the presented case, the group 3 is more worisome with many Jacard values under 0.5.

We can check the values of the centers of the group 3 across the 1000 iterations.

df_gp3 <- bootvalues$group_centers[["group3"]]

melted_df <- reshape2::melt(df_gp3)
melted_df$variable <- as.factor(melted_df$variable)

ggplot() +
  geom_histogram(mapping = aes(x = value), data = melted_df, bins = 30) +
  labs(title = "stability of group 3 centers", subtitle = "for 1000 iterations") +
  facet_wrap(vars(variable), ncol=3)

It appears that the center values for NO2 and PM2.5 are bimodal, that might explain why this group tends to dissolve. This could mean that group three is the combination of two very similar sub-groups.

Advanced example

SFCM with spatial non-local information

It has been proposed to modify the SFCM algorithm to include "non-local spatial information" instead of the information provided by close observations [@zhao2015multiobjective]. Basically, this implies a modified spatial weighting scheme combining neighbouring and semantic distance. This way, more similar neighbours get more weights in the calculation of the lagged dataset which can be desirable in dataset characterized by a lot of noise. When working with a classical vector dataset, one can use the function adjustSpatialWeights and create a row-standardized weight matrix using the inverse of the euclidean distance between observation and their neighbours as weights.

# create the modified weight matrix
WMat_adj <- adjustSpatialWeights(Data, WMat$neighbours, style = "W")

# calculate the modified version of FCM with non-local information
nl_SFCM <- SFCMeans(Data, WMat_adj, k = 4, m = 1.5, alpha = 0.7,
                 tol = 0.0001, standardize = FALSE,
                 verbose = FALSE, seed = 456)

When working with rasters, the same method can be apllied by giving "nl" as value for the parameter lag_method.

Final words

That's all, folks ! Following are the enhancements for the next version


Try the geocmeans package in your browser

Any scripts or data that you put into this service are public.

geocmeans documentation built on June 17, 2022, 1:05 a.m.