pyclustering clarans.get_clusters() returns empty list

Viewed 360

I am trying CLARANS clustering with pyclustering module, but for all the data I've tried clarans(data, number_clusters, numlocal, maxneighbor) all the methods returns [] (an empty list) no matter what the parameter values are. I made a random data to test the method, but the answer is the same, the only data that works is the iris data datasets.load_iris() form sklearn module. Am I doing something wrong?

This is the testing data:

import pandas as pd
import numpy as np
import seaborn as sns
from pyclustering.cluster.clarans import clarans

x1 = np.random.normal(10, 5, 100)
x2 = np.random.normal(30, 5, 100)
x = np.concatenate((x1, x2), axis=0)
y1 = np.random.normal(50, 5, 100)
y2 = np.random.normal(60, 5, 100)
y = np.concatenate((y1, y2), axis=0)
Gr = np.array(['G1']*100 + ['G2']*100)

df = pd.DataFrame(x, columns=['X'])
df['Y'] = y
df['Gr'] = Gr

This is when I run the clustering technique (I convert the df to a 2D list):

datalist = np.zeros((200,2))
for i in df.index:
    datalist[i][0] = round(float(df['X'][i]), 2)
    datalist[i][1] = round(float(df['Y'][i]), 2)

cluster_clarans = clarans(datalist, 2, 6, 4)

cluster_clarans.get_clusters()

And the answer is:

[]
1 Answers

You forgot to peform the processing using process() function before printing out the clusters.

This statement

cluster_clarans = clarans(datalist, 2, 6, 4)

Initializes the class object. You then need to call the process method.

cluster_clarans.process()

Now, when you print out the clusters, you will get 2 lists, each containing the index of data points in each clusters. See the official documentation of get_clusters here.

print(cluster_clarans.get_clusters())

Here is the complete code down below. Note that I have changed the size of the random data below:

import pandas as pd
import numpy as np
import seaborn as sns
from pyclustering.cluster.clarans import clarans

x1 = np.random.normal(30, 10, 20)
x2 = np.random.normal(60, 5, 20)
x = np.concatenate((x1, x2), axis=0)
y1 = np.random.normal(20, 5, 20)
y2 = np.random.normal(40, 15, 20)
y = np.concatenate((y1, y2), axis=0)
Gr = np.array(['G1']*20 + ['G2']*20)

df = pd.DataFrame(x, columns=['X'])
df['Y'] = y
df['Gr'] = Gr

datalist = np.zeros((40,2))
for i in df.index:
    datalist[i][0] = round(float(df['X'][i]), 2)
    datalist[i][1] = round(float(df['Y'][i]), 2)

# Initialize the cluster object
cluster_clarans = clarans(datalist, 2, 6, 4)

# Process the data
cluster_clarans.process()

# Get the points in each clusters
print(cluster_clarans.get_clusters())
# Output: [[9,14,15,16,20,21,27,28,29,30,31,32,33,34,35,37,38,39],
           [0,1,2,3,4,5,6,7,8,10,11,12,13,17,18,19,22,23,24,25,36]]

You can read more about the process() function here.

Related