Sklearn Kmeans Elbow Method - Plotting Inertia With Matplotlib

Python

This code snippet gives an example of how to assess how many cluster to use with the K-Means algorithm by using the elbow method and the inertia value.

 1|  import matplotlib.pyplot as plt
 2|  from sklearn.cluster import KMeans
 3|  
 4|  # Step 1: Set range of clusters to try and 
 5|  # create inertia values dictionary
 6|  clusters_range = (1,10)
 7|  inertia_values = {}
 8|  
 9|  # Step 2: For each set of clusters fit a kmeans algorithm and add
10|  # inertia value to interia values dictionary
11|  for clusters in range(clusters_range[0], clusters_range[1] + 1):
12|      k_means = KMeans(n_clusters=clusters,
13|                       random_state=101)
14|      k_means.fit(X_train)
15|      inertia_values[str(clusters)] = k_means.inertia_
16|  
17|  # Step 3: Plot inertia values dictionary to assess optimum
18|  # number of clusters to use
19|  plt.figure(figsize=(10,6))
20|  
21|  plt.plot(inertia_values.keys(),
22|           inertia_values.values(),
23|           marker='o')
24|  
25|  plt.title('KMeans Clustering Elbow Method')
26|  plt.ylabel('Inertia')
27|  plt.xlabel('Clusters')
28|  
29|  plt.show()
Sklearn Kmeans Elbow Method - Plotting Inertia With Matplotlib
Did you find this snippet useful?

Sign up for free to to add this to your code library