生成数据集
from sklearn import datasets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
data = datasets.load_iris()[:,:2].tolist()
data
- 为了后续可视化方便,故此处选择生成二维数据集,毕竟画二维散点图不怎么需要动脑子;
生成核心对象
MIN_PTS = 3
E = .1
O = []
for i in range(len(data)):
num = 0
for j in range(len(data)):
if distance(i,j) <= E:
num += 1
if num >= MIN_PTS:
O.append(data[i])
O
对数据集可视化展示
plt.figure(figsize=(3,3),dpi=200)
plt.style.use('seaborn-dark')
for i in range(len(data)):
plt.scatter(data[i][0],data[i][1],color='red')
for j in range(len(O)):
plt.scatter(data[j][0],data[j][1],color='blue')
- 此处的红色点以及蓝色点构成所有样本点,而蓝色点也就是我们控制阈值而得出的核心对象;
- 另外,此处所有代码均为现撸,省略很多简单函数,比如distance,懂得自然懂。完整代码在jupyter上,需要可私信我或者评论区回复;
利用生成的核心对象生成簇
OBJ = O.copy()
unflag = data.copy()
MIN_PTS = 3
E = .1
k = 0
colors = ['yellow','green','pink','black']
markers = ['1','2','*','+']
while OBJ:
obj = OBJ[random.randint(0,len(OBJ)-1)]
C = [obj]
Q = [obj]
unflag.remove(obj)
while Q:
q = Q[0]
del Q[0]
num = 0
ts = []
for i in range(len(unflag)):
if distance(q,unflag[i]) < E:
num += 1
ts.append(unflag(i))
if num >= MIN_PTS:
for s in ts:
if s in unflag:
Q.append(s)
C.append(s)
unflag.remove(s)
for j in C:
if j in OBJ:
OBJ.remove(j)
plt.scatter(j[0],j[1],color=colors[k%4],marker = markers[k%4])
k += 1
- 阈值可自己调
- 最终分成三类,list ou of range,所以不仅看颜色 更要看形状
- 本博客仅用于本人学习使用,不得转载用作他途
- 下期出使用K-means做对比的复现
- 目前来看,DBscan可聚类的形状远不止球状,甚好!
|