Different inertia values even with random_state set

Viewed 40

Im trying to make my algorithm, which involves KMeans, reproducible, but even If I set random_state value I always get different inertia values. I'm using this page dataset without the first line (dataset size).

Steps/Code to Reproduce

from sklearn.cluster import KMeans
import numpy as np

points = np.genfromtxt('page.txt')
for l in range(10):
    kmeans = KMeans(n_clusters=30, n_init=1, random_state=42)
    kmeans.fit(points)

    centroids = kmeans.cluster_centers_
    print('{0:.20f}'.format(kmeans.inertia_))

Expected Results

I expect to get printed ten time the same value

Actual Results

1008436173.14048004150390625000
1008436173.14048004150390625000
1008436173.14047992229461669922
1008436173.14048004150390625000
1008436173.14047992229461669922
1008436173.14048004150390625000
1008436173.14047992229461669922
1008436173.14048004150390625000
1008436173.14048004150390625000
1008436173.14048004150390625000
1 Answers

I tried to run your code on Google Colaboratory with the dataset you provided (the first line is removed). The outputs are shown exact same results 10 times

Environment

Python 3.7.13

numpy                         1.21.6
scikit-learn                  1.0.2

Output

1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
1008436173.14048218727111816406
Related