Nisarg Patel
Nisarg Patel

Reputation: 41

AttributeError: 'KMeans' object has no attribute 'inertia_'

from sklearn.cluster import KMeans
import numpy
import pandas as pd
from pandas import read_csv

boston = read_csv("../desktop/Boston.csv")
print(boston)

print(boston.columns)
del boston['index']
del boston['chas']
print(boston)

sse=[]

for i in range(1,9):
    kmeans = KMeans(n_clusters=i , max_iter=300)
    sse.append(kmeans.inertia_)

I am getting

AttributeError: 'KMeans' object has no attribute 'inertia_'

I am trying to find out appropriate number of clusters on Boston data using k means

Upvotes: 2

Views: 10494

Answers (1)

desertnaut
desertnaut

Reputation: 60321

KMeans attributes like inertia_ are created when the model is fitted; but here you don't call the .fit method, hence the error.

You need to run kmeans.fit() with your data before calling kmeans.inertia_; here is a complete example using the Boston data from sklearn:

from sklearn.cluster import KMeans
from sklearn.datasets import load_boston
import matplotlib.pyplot as plt

X, y = load_boston(return_X_y=True)

sse = []
for i in range(1,9):
    kmeans = KMeans(n_clusters=i , max_iter=300)
    kmeans.fit(X)  # <- fit here.....
    sse.append(kmeans.inertia_)

plt.plot(range(1,9),sse)
plt.show() 

Result:

enter image description here

Upvotes: 4

Related Questions