Visualizing K-means Clustering on an Iris Dataset with Matplotlib
Topic Overview
Welcome to this lesson on "Visualizing Clusters with Matplotlib using an Iris Dataset". Previously, we introduced unsupervised learning, with a focus on clustering and the K-means clustering algorithm. In this unit, we will visualize the clusters resulting from the K-means algorithm using Python's Matplotlib library. The goal of this lesson is to illustrate the implementation of the K-means clustering algorithm and to demonstrate how to visualize the results using Matplotlib, utilizing a simple Iris dataset as an example.
Loading the Iris Dataset
In this lesson, we will focus on the scatter() function, which allows us to create scatter plots, and the show() function, which will enable us to display the plot.
We begin by loading the Iris dataset. It is a classic and widely used dataset in pattern recognition, consisting of 150 samples from three species of Iris flowers (Iris setosa, Iris virginica, and Iris versicolor), with four features measured for each sample: the length and the width of the sepals and petals.
Utilizing Sklearn for K-means Clustering and Visualization
Let's see how to apply KMeans from sklearn and visualize results using Matplotlib. Horizontal and vertical indicators alone may not provide all the clarity we need in a plot. That's where Python's Matplotlib shines — its assortment of plot customization capabilities. Let's delve into customizing the colormap and other parameters for your plots for improving visualization and readability.
Before jumping into plotting, let's cluster our data first:
A colormap is like an artist's palette, essentially mapping values to colors on a plot. Matplotlib offers a variety of default colormaps. The scatter() function uses a colormap to define the colors of markers.
The colormap can be specified using the parameter cmap of the scatter() method.
The c parameter passed to the scatter() method is a list of the same length as data that specifies the color of each point.
Let's customize our plot:
With Sklearn's implementation, we instantiate the KMeans model with the desired number of clusters, then fit it to our data. The labels of the clusters for each data point are obtained via the labels_ attribute of the model, while the cluster_centers_ attribute gives us the centroid of these clusters. These are then visualized through the scatter function in Matplotlib just as we did before. Check out the plot presented below:

