Search code examples
pythonpython-3.xscikit-learncluster-analysisdbscan

Separating the coordinates(3D coordinates) for each cluster in DBSCAN using python


I was clustering some 3D coordinates using DBSCAN (using python). I was able to cluster it into different clusters. But now i want to separate the coordinates which belong to each of these clusters and print those coordinates into different text files. Can anybody please help me how to do it.

I have already tried to cluster into separate clusters and get the coordinates of each cluster. whole different codes will be also fine

I'm unable to post my codes due to some issue. But i will post the commands that i used to make my one. (This one is 2D)

from sklearn.cluster import DBSCAN
import numpy as np
data = np.random.rand(500,3)

db = DBSCAN(eps=0.12, min_samples=1).fit(data)
labels = db.labels_
from collections import Counter
Counter(labels)

Solution

  • To store samples (numpy.array) in .txt files, you should first divide your samples in partitions based on cluster assignment and then save the resulting partitions.

    from collections import defaultdict
    
    clusters = defaultdict(list)
    
    for i,c in enumerate(db.labels_):
        clusters[c].append(data[i])
    
    for k,v in clusters.items():
        np.savetxt('cluster{}.txt'.format(k), v, delimiter=",", fmt='%s')
    

    and you get 68 txt files, each one containing coordinates for one or multiple samples from your dataset.