DBSCAN密度聚类-Python

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ThinkPet/article/details/83008442
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
密度聚类亦称“基于密度的聚类”(density-based clustering),此类算法假
设聚类结构能通过样本分布的紧密程度确定

DBSCAN是一种著名的密度聚类算法,主要是依赖两个主
要的参数来进行聚类的,即对象点的区域半径Eps和区域内点的个数的阈值MinPts。

DBSCAN算法聚类过程如下:
 将所有的点分别标记为核心点、边界点或噪声点。
 删除识别出的噪声点。
 将在Eps之内的所有核心点连通,并形成一个簇。
 将每个边界点归属到一个与之相关联的核心点的簇中
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
 
np.random.seed(123)
s=list(np.random.uniform(0,10,10))*60
x=pd.Series(np.random.randn(600)*0.2+s)
y= pd.Series(np.random.randn(600)*0.2+s)
x=pd.concat([x,y],axis=1) #横向合并数据

from sklearn.cluster import DBSCAN
'''
# 聚类,半径为0.2,3代表聚类中点的区域必须至少有3个才能聚成一类
'''
model = DBSCAN(eps=0.2,min_samples=3,metric = 'euclidean',metric_params=None).fit(x)
'''
点的Eps区域:以空间中任意一点p为圆心,Eps为半径的区域中的点的集合,
记为集合D。Eps是由用户指定的。
'''
model.eps
model.labels_
labels = pd.Series(model.labels_,name='label')
x1 = pd.concat( [x ,labels] ,axis=1)
'''
# axis中0是横向合并,1是纵向合并,若属性不对应就不会合并
'''
plt.figure(figsize=(8,8)) #8*8的画布
plt.scatter(x1.iloc[:,0] ,x1.iloc[:,1], c=x1['label'])
plt.show()

#去除噪声点
x2 = x1[x1.label > 0]

plt.figure(figsize=(8,8)) #8*8的画布
plt.scatter(x2.iloc[:,0] ,x2.iloc[:,1], c=x2['label'])
plt.show()


猜你喜欢

转载自blog.csdn.net/ThinkPet/article/details/83008442