san
san

Reputation: 333

'KMeans' object has no attribute 'cluster_centers_'

I am using Jupyter notebook and I have written the following code:

from sklearn.datasets import make_blobs
dataset = make_blobs(n_samples=200, centers = 4,n_features = 2, cluster_std = 1.6, random_state = 50)
points = dataset[0];
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters = 4)
kmeans.fit(points)
plt.scatter(dataset[0][:,0],dataset[0][:,1])
clusters = kmeans.cluster_centers_

// The line below gives the error: 'KMeans' object has no attribute 'cluster_centers_'

clusters = kmeans.cluster_centers_

I was expecting it to display the means or the averages of the points.

Upvotes: 3

Views: 11089

Answers (1)

Luke B
Luke B

Reputation: 1194

It's not clear in your example whether your statement comes before or after you call fit. The attribute is defined in the fit method. Do you call your function before or after fit ?

If you do it like this there's an error :

from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

dataset = make_blobs(n_samples=200, centers = 4,n_features = 2, cluster_std = 1.6, random_state = 50)
points = dataset[0]

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=4)
clusters = kmeans.cluster_centers_
kmeans.fit(points)

plt.scatter(dataset[0][:,0],dataset[0][:,1])

But this way doesn't produce an error

from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

dataset = make_blobs(n_samples=200, centers = 4,n_features = 2, cluster_std = 1.6, random_state = 50)
points = dataset[0]

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=4)
kmeans.fit(points)
clusters = kmeans.cluster_centers_

plt.scatter(dataset[0][:,0],dataset[0][:,1])

Upvotes: 5

Related Questions