日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

机器学习 聚类篇——python实现DBSCAN(基于密度的聚类方法)

發布時間:2025/3/21 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 机器学习 聚类篇——python实现DBSCAN(基于密度的聚类方法) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

機器學習 聚類篇——python實現DBSCAN(基于密度的聚類方法)

  • 摘要
  • python實現代碼
  • 計算實例

摘要

DBSCAN(Density-Based Spatial Clustering of Applications with Noise) 為一種基于密度的聚類算法,它不僅可以找出具有任何形狀的簇,而且還可以用于檢測離群值。其基本思想為數據點分布緊湊的應被劃分為一類,而周圍未分布有或僅有極少數點的數據點則有可能為離群值。本文通過python實現了該聚類方法,并將代碼進行了封裝,方便讀者調用。
下圖為正文計算實例的可視化圖形。

python實現代碼

eps:鄰域半徑(float)
MinPts:密度閾值(int)
.fit(X):對待聚類的數據集進行聚類
用法:指定鄰域半徑密度閾值,這兩個參數對應于不同的數據集需要進行調整,然后直接調用fit(X) 進行數據集的聚類。

# -*- coding: utf-8 -*- # @Time : 2020/12/21 16:34 # @Author : CyrusMay WJ # @FileName: cyrus_dbscan.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Cyrus_Mayimport sys import logging import numpy as np import randomclass CyrusDBSCAN(object):def __init__(self,eps=0.1,MinPts=3):""":param eps: 鄰域半徑:param MinPts: 密度閾值"""self.__build_logger()self.eps = epsself.MinPts = MinPtsdef __build_logger(self):self.logger = logging.getLogger()self.logger.setLevel(logging.INFO)screen_handler = logging.StreamHandler(sys.stdout)screen_handler.setLevel(logging.INFO)formatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s:%(lineno)d - %(levelname)s - %(message)s')screen_handler.setFormatter(formatter)self.logger.addHandler(screen_handler)def fit(self,X):# 初始化數據點狀態及索引號self.X = np.array(X)global index,state,class_clusterindex = [i for i in np.arange(X.shape[0])]state = [0] * X.shape[0]class_cluster = 1while 1:if self.choice() is not None:# 從未劃分的數據點中隨機選擇一個point = self.choice()# 計算在其領域半徑內的點not_use_index = self.not_use_point()temp = []for i in not_use_index:if i != point:if self.cal_dist(self.X[i, :], self.X[point, :]) <= self.eps:temp.append(i)if len(temp) >= self.MinPts:self.logger.info("搜索到第{}簇!".format(class_cluster))self.cal_eps_count([point])self.logger.info("第{}簇搜索完成!".format(class_cluster))class_cluster += 1else:state[point] = "noise"else:breakreturn statedef cal_eps_count(self,points):flag = []for point in points:temp = []for i in self.not_use_point():if self.cal_dist(self.X[i,:],self.X[point,:]) <= self.eps and i != point:state[i] = class_clustertemp.append(i)self.logger.info("第{}簇新增一個數據點!".format(class_cluster))if len(temp) >= self.MinPts:flag += tempif flag:return self.cal_eps_count(flag)def cal_dist(self,x1,x2):return (((x1-x2)**2).sum())**0.5def not_use_point(self):temp = []for i in index:if state[i] in [0,"noise"]:temp.append(i)return tempdef choice(self):temp = []for i in index:if state[i] == 0:temp.append(i)if len(temp) == 1:state[temp[0]] = "noise"return Noneelif len(temp) == 0:return Noneelse:return random.choice(temp)

計算實例

對加入噪聲的月亮形狀數據集進行聚類

if __name__ == '__main__':dbscan = CyrusDBSCAN(eps=0.25,MinPts=3)from sklearn.datasets import make_moonsimport matplotlib.pyplot as pltmoons = make_moons(n_samples=1000,noise=0.05)y = dbscan.fit(moons[0])dbscan.logger.info(y)plt.scatter(moons[0][:, 0], moons[0][:, 1], c=[["r", "b"][i-1] if i != "noise" else "g" for i in y])plt.show() 2020-12-21 21:14:32,952 - cyrus_dbscan.cal_eps_count:68 - INFO - 第2簇新增一個數據點! 2020-12-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 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 1, 2, 1, 2]

by CyrusMay 2020 12 21

我沒有任何天分
我卻有夢的天真
我是傻 不是蠢
我將會證明
用我的一生
——————五月天(咸魚)——————

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的机器学习 聚类篇——python实现DBSCAN(基于密度的聚类方法)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。