Skip to content

Instantly share code, notes, and snippets.

@victormurcia
Created October 20, 2022 18:07
Show Gist options
  • Select an option

  • Save victormurcia/b886d5118c18473d70278eee41c724d6 to your computer and use it in GitHub Desktop.

Select an option

Save victormurcia/b886d5118c18473d70278eee41c724d6 to your computer and use it in GitHub Desktop.
calculate distortions for k means for elbow method
#Determine optimal k value for clustering using elbow method
distortions = [] #Initialize array with distortions from each clustering run
K = range(1,11) #Explore k values between 1 and 10
#Run the clustering routine
for k in K:
#Convert image into a 1D array
flat_img = np.reshape(rgb_img,(-1,3))
kmeanModel = KMeans(n_clusters=k)
kmeanModel.fit(flat_img)
distortions.append(kmeanModel.inertia_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment