DBSCAN算法的Python实现

先附图为敬:

DBSCAN算法的Python实现_第1张图片

代码如下:

import math
import matplotlib.pyplot as plt
def getData(path):
    file = open(path,'r')
    data = []
    for item in file.readlines():
        item = item.split(',')
        temp = [float(item[0]),float(item[1])]
        if temp not in data:
            data.append(temp)
    return data
def distance(x,y):
    return math.sqrt(pow(x[0]-y[0],2)+pow(x[1]-y[1],2))
def scan(data,radius,Minpts):
    for point in data:
        num = 0
        point.append([])
        for another in data:
            if distance(point,another) <= radius:
                point[2].append(another)
                num = num + 1
        point[2].remove(point)
        if (num-1) >= Minpts:
            point.append(1)
        else:
            point.append(0)
def deal(data):
    cluster = []
    for point in data:
        if point[3] == 0:
            continue
        else:
            temp = []
            temp.append(point)
            for item in temp:
                if item[3] == 1:
                    for t in item[2]:
                        if t in data:
                            data.remove(t)
                            temp.append(t)
            cluster.append(temp)
    return cluster
data = getData('/Users/star/Downloads/data.csv')
scan(data,0.3,10)
cluster = deal(data)
c = {'1':'red','2':'blue','3':'yellow'}
num = 1
for item in cluster:
    for point in item:
        plt.scatter(point[0],point[1],color=c[str(num)])
    num = num + 1
plt.show()

 

你可能感兴趣的:(学习笔记)