add labels to sklearn k-means
Question: I am trying to use kmeans in python.

    
    
    data = [[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]]
    

Each of this data have a label. Example:

    
    
    [1,2,3,4,5] -> Fiat1
    [1,0,3,2,4] -> Fiat2
    [4,3,234,5,5] -> Mercedes
    [23,4,5,1,4] -> Opel
    [23,5,2,3,5] -> bmw
    
    kmeans = KMeans(init='k-means++', n_clusters=3, n_init=10)
    kmeans.fit(data)
    

My objective is after I run the KMeans, I want to obtain the labels of each
cluster.

A fake example:

Cluster 1: Fiat1, Fiat2

Cluster 2: Mercedes

Cluster 3: bmw, Opel

How can I do that ?


Answer: ### Code

    
    
    from sklearn.cluster import KMeans
    import numpy as np
    
    data = np.array([[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]])
    labels = np.array(['Fiat1', 'Fiat2', 'Mercedes', 'Opel', 'BMW'])
    N_CLUSTERS = 3
    
    kmeans = KMeans(init='k-means++', n_clusters=N_CLUSTERS, n_init=10)
    kmeans.fit(data)
    pred_classes = kmeans.predict(data)
    
    for cluster in range(N_CLUSTERS):
        print('cluster: ', cluster)
        print(labels[np.where(pred_classes == cluster)])
    

### Output:

    
    
    cluster:  0
    ['Opel' 'BMW']
    cluster:  1
    ['Mercedes']
    cluster:  2
    ['Fiat1' 'Fiat2']
    

