iamdeit
iamdeit

Reputation: 6035

How to get inertia value for each k-means cluster using scikit-learn?

I'm using scikit learn for clustering (k-means). When I run the code with the verbose option, it prints the inertia for each iteration.

Once the algorithm finishes, I would like to get the inertia for each formed cluster (k inertia values). How can I achieve that?

Upvotes: 13

Views: 7899

Answers (1)

Raphael Adamski
Raphael Adamski

Reputation: 53

I manage to get that information using fit_transform method and them getting the distance between each sample and its cluster.

model = cluster.MiniBatchKMeans(n_clusters=n)
distances = model.fit_transform(trainSamples)
variance = 0
i = 0
for label in model.labels_:
    variance = variance + distances[i][label]
    i = i + 1

Upvotes: 2

Related Questions