简体   繁体   中英

Cannot use Kmeans Cluster inside a python function

As above - I'm trying to create a function for clustering specific data types and displaying them.

The function looks a bit like this at the moment,

def cluster(inputData):
    variable_s= inputData.groupby(['x','z', 'c'])['w'].sum().unstack()
    ## 4 Clusters
    model = cluster.MiniBatchKMeans(n_clusters=5)
    model.fit(variable_s.fillna(0))
    variable_s['kmeans_4'] = model.predict(variable_s.fillna(0))

    ## 8 Clusters
    model = cluster.KMeans(n_clusters=8)
    model.fit(variable_s.fillna(0))
    variable_s['kmeans_8'] = model.predict(variable_s.fillna(0))

    ## Looking at hourly distribution.
    variable_s_Hourly = variable_s.reset_index(1, inplace=True)
    variable_s_Hourly['hour'] = variable_s_Hourly.index.hour
    return variable_s, variable_s_Hourly

it uses

from sklearn import cluster
    

to do the clustering, and it's giving me an error like this,

AttributeError: 'function' object has no attribute 'MiniBatchKMeans'

Any clues on solving this issue? I would have thought the function would be fine as long as the library is imported into the file itself - this is in jupyter notebook:)

Cheers!

The function name ("cluster") shadows the import. Change the function name to solve it.

Alternatively, you can give the import an alias:

from sklearn import cluster as clstr

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