Search code examples
pythonpandasscikit-learnk-means

Error when calling model.labels in KMeans


I am running this code

import pandas as np
import numpy as np

from sklearn import cluster
from sklearn.cluster import KMeans

model = cluster.KMeans(n_clusters=4, random_state=10)

Then I put that through a dataframe I am working on and that includes the columns age and income, which is the clusters I am working on,

model.fit(df[['income', 'age']]

And so far it works well until I run the following bit, which aims at creating a column with the label of the cluster each data point belongs to.

df['cluster'] = model.labels_df.head()

And this is the error code I get:

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

Any suggestions?


Solution

  • The attribute to access the labels of the model is: model.labels_

    Use:

    df['cluster'] = model.labels_
    

    By typing model.labels_df.head() you request the head of model.labels_df that does not exist.

    I believe you have mistyped it and you need:

    df['cluster'] = model.labels_
    df.head()