kmeans and wss: Find optimal number of clusters (k)

3clustersegment

A K-Means Clustering algorithm allows us to group observations in close proximity to the mean. This allows us to create greater efficiency in categorising the data into specific segments. Here is how the wss command is used to firstly determine the number of clusters, and how kmeans is then used to conduct the k-means analysis.

One can employ this type of analysis across many different types of situations where we wish to analyse data broken down into specific groups and networks. This could include areas such as social network analysis, market segmentation, and so on.

My specific example looks at how clustering can be used to analyse stock price data. For another general example, I highly recommend Ben Larson’s tutorial on k-means clustering using student test result data, which applies many of the principles that I also use here.

In this particular example, we use a hypothetical dataset of stock returns and dividends in order to segment our data into different clusters. We also wish to analyse the relative groupings of stocks based on their 1-year returns and dividend yields. We use the sample_stock dataset (csv found below).

wss: Determining Number of Clusters

Firstly, we must determine the appropriate number of clusters in R as follows:

# Determine number of clusters
wss <- (nrow(sample_stocks)-1)*sum(apply(sample_stocks,2,var))
for (i in 2:20) wss[i] <- sum(kmeans(sample_stocks,centers=i)$withinss)
plot(1:20, wss, type="b", xlab="Number of Clusters",
     ylab="Within groups sum of squares")

In the above code, we use a maximum of 20 clusters through plotting 1:20. This number is arbitrary, we could have chosen 5 as the maximum possible number of clusters. Once this is done, we then identify the ideal number of clusters at the point at which there is a cut off in our scree plot:

3-clusters

From the above, we see that our scree plot cuts off at 3 clusters. This is the point at which the "within groups sum of squares" is minimised at the third cluster.

kmeans: Clustering Algorithm

We now compute our k-means algorithm and plot output, setting the number of specified clusters equal to 3:

# K-Means Cluster Analysis
fit <- kmeans(sample_stocks, 3) # 3 cluster solution
# get cluster means
aggregate(sample_stocks,by=list(fit$cluster),FUN=mean)
# append cluster assignment
sample_stocks <- data.frame(sample_stocks, fit$cluster)
sample_stocks
sample_stocks$fit.cluster <- as.factor(sample_stocks$fit.cluster)
library(ggplot2)
ggplot(sample_stocks, aes(x=dividendyield, y=returns, color = sample_stocks$fit.cluster)) + geom_point()

Upon running this code, we see that our data has been "clustered" into three separate segments. Even though we do have a few outliers, our data has largely been separated into distinct groups:

kmeans

From this graph, we can identify that stocks which have had higher dividend yields have also seen higher returns. In this regard, we can use k-means clustering to identify patterns in data that would not otherwise be apparent through traditional methods of analysis.

Code Scripts and Datasets

Hope you enjoyed this tutorial!

The full code and dataset is available by subscribing to my mailing list.

Upon subscription, you will receive full access to the codes and datasets for my tutorials, as well as a comprehensive course in regression analysis in both Python and R.