Visualize the Hierarchical based Clustering (Agglomerative, Divisive) for the Iris Dataset using sklearn
Package
I need python program and which computes all required data and output the required plots and visual plots of all.
Assistant
User
Visualize the Hierarchical based Clustering (Agglomerative, Divisive) for the Iris Dataset using sklearn
Package
I need python program and which computes all required data and output the required plots and visual plots of all.
Assistant
Sure, let's use Python with sklearn and other supportive libraries to visualize hierarchical-based clustering (both agglomerative and divisive) on the Iris dataset.
Below is the complete program:
python
To perform hierarchical cluster analysis on the Iris dataset using the agglomerative and divisive approaches, and to visualize the results, you can use the sklearn package along with scipy for more detailed dendrogram plotting. Below is a Python code snippet that accomplishes this task using AgglomerativeClustering from sklearn.cluster for agglomerative clustering, and scipy.cluster.hierarchy for dendrogram visualization.
First, make sure to install the required packages if you haven't already by running:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import datasets
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from scipy.cluster.hierarchy import cut_tree
# Load the Iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Agglomerative Clustering
# Set the number of clusters to the known number of species (3),
# though in practice this might be unknown
agglomerative_clustering = AgglomerativeClustering(n_clusters=3)
agg_clusters = agglomerative_clustering.fit_predict(X)
# Visualize Agglomerative Clustering results with a scatter plot
# We will use the first two dimensions
plt.figure(figsize=(10, 5))
sns.scatterplot(X[:, 0], X[:, 1], hue=agg_clusters, palette='deep')
plt.title('Agglomerative Clustering - Iris Dataset')
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.show()
# Dendrogram for Agglomerative Clustering
plt.figure(figsize=(15, 5))
linked = linkage(X, method='ward')
dendrogram(linked, labels=agglomerative_clustering.labels_, orientation='top',
distance_sort='descending', show_leaf_counts=True)
plt.title('Hierarchical Clustering Dendrogram (Agglomerative)')
plt.xlabel('Sample Index')
plt.ylabel('Distance')
plt.show()
# Divisive Clustering using the scipy 'linkage' function with 'single' method
# This is a demonstration as sklearn does not provide divisive clustering.
# The 'single' linkage method is used here, though others (e.g., 'ward') can be tried.
plt.figure(figsize=(15, 5))
divisive_linked = linkage(X, method='single')
dendrogram(divisive_linked, orientation='top',
distance_sort='descending', show_leaf_counts=True)
plt.title('Hierarchical Clustering Dendrogram (Divisive)')
plt.xlabel('Sample Index')
plt.ylabel('Distance')
plt.show()
# Divisive clustering cannot be directly predicted using linkage; you need
# to cut the dendrogram at a certain distance to get the cluster labels
distance_threshold = 0.5 # Adjust this threshold as needed
divisive_clusters = fcluster(divisive_linked, distance_threshold, criterion='distance')
# Visualize Divisive Clustering results with a scatter plot
plt.figure(figsize=(10, 5))
sns.scatterplot(X[:, 0], X[:, 1], hue=divisive_clusters, palette='deep')
plt.title('Divisive Clustering - Iris Dataset')
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.show()
This code performs and visualizes both agglomerative and divisive hierarchical clustering on the Iris dataset. The agglomerative clustering results are visualized through scatter plots and a dendrogram, while for divisive clustering, a dendrogram is shown (since sklearn doesn't support divisive clustering, we use scipy for that dendrogram). Divisive clusters are visualized in a scatter plot using a distance threshold to determine the clusters. Adjust the distance threshold in fcluster as needed to better match the data at hand.
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.decomposition import PCA
# Load the Iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Perform Agglomerative Clustering
agg_model = AgglomerativeClustering(n_clusters=3)
agg_clusters = agg_model.fit_predict(X)
# Reduce data dimensions for visualization
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
# Plotting Agglomerative Clustering results
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=agg_clusters, cmap='rainbow', alpha=0.7, edgecolors='b')
plt.title("Agglomerative Clustering - Scatter Plot")
# Plotting Agglomerative Clustering dendrogram
Z = linkage(X, 'ward')
plt.subplot(1, 2, 2)
dendrogram(Z, truncate_mode='lastp', p=12, leaf_rotation=45., leaf_font_size=15., show_contracted=True)
plt.title("Agglomerative Clustering - Dendrogram")
plt.xlabel('Cluster Size')
plt.ylabel('Distance')
plt.tight_layout()
plt.show()
Note: scikit-learn does not support divisive clustering directly, so we only provide an agglomerative example with a dendrogram. Divisive clustering is often visualized using the same dendrogram techniques.
This code snippet will provide you with a scatter plot of the Iris data reduced to two principal components labeled by the clusters determined by agglomerative clustering, as well as a dendrogram visualizing the hierarchical clustering. The dendrogram is truncated for clarity, showing only the last p merged clusters. If you wish to see the full dendrogram, remove the truncate_mode and p parameters from the dendrogram function call.
Remember to install required packages if you haven't already:
sh
pip install scikit-learn scipy matplotlib
Run the program in your Python environment and you should see the visualizations as described.