简体   繁体   中英

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

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM