Python 中的 DBSCAN 算法

在本教程中,我們將學習如何在 Python 中實現和使用 DBSCAN 算法。

1996 年,一種聚類算法——基於密度的噪聲應用空間聚類首次被提出,並於 2014 年獲得“時間測試”獎。在 KDD 舉行的數據挖掘大會上,DBSCAN 獲得了“時間的考驗”獎項。我們在這裡不學習 DBSCAN 算法,只討論 DBSCAN 算法在 Python 中的實現。但是如果我們必須了解 DBSCAN 算法的實現,我們至少應該對它有一個基本的了解。因此,如果你不知道什麼是 DBSCAN 算法或者它是如何工作的,那麼你應該首先了解 DBSCAN 算法及其工作原理。

DBSCAN 算法在 Python 中的實現

我們將在本節中執行 DBSCAN 算法的實現操作,我們將分步驟進行,以便於理解和學習。我們將在這個實現過程中使用數據集來對其執行各種操作(包括我們在 DBSCAN 算法中所做的操作)。在開始實現過程之前,我們應該滿足在 Python 程序中實現 DBSCAN 算法的先決條件。

實施 DBSCAN 算法的先決條件:

在繼續本節中的 DBSCAN 算法的實現部分之前,我們必須滿足以下先決條件:

1。Numpy 庫:我們應該確保 numpy 庫安裝在我們的系統中,並且是最新版本,因為我們將在實現過程中使用數據集上的 numpy 庫上的函數。如果 numpy 庫不在我們的系統中,或者我們以前沒有安裝過它,那麼我們可以使用設備中的命令提示符終端中的以下命令來安裝它:


pip install numpy

當我們按回車鍵時,numpy 庫開始安裝在我們的系統中。

一段時間後,我們將看到 numpy 庫成功安裝在我們的系統中(這裡,我們的系統中已經有了 numpy 庫)。

2。Panda library: 和 numpy library 一樣,Panda library 也是我們系統中應該存在的必選庫,如果我們系統中不存在,我們可以在命令提示終端中使用以下命令,用 pip installer 進行安裝:


pip install pandas

3。matplotlib 庫:它也是 DBSCAN 算法實現過程中的一個重要庫,因為這個庫的函數將幫助我們顯示來自數據集的結果。如果 matplotlib 庫不在我們的系統中,那麼我們可以使用命令提示符終端中的以下命令,用 pip installer 安裝它:


pip install matplotlib

4。Sklearn 庫:在執行 DBSCAN 算法的實現操作時,Sklearn 庫將是主要需求之一,因為我們必須在程序中從 Sklearn 庫本身導入各種模塊,例如預處理分解等。因此,我們應該確保 Sklearn 庫是否存在於我們的系統中,如果不存在於我們的系統中,那麼我們可以使用命令提示符終端中的以下命令來安裝 pip installer:


pip install matplotlib

5.最後但同樣重要的是,我們還應該了解 DBSCAN 算法(它是什麼以及它是如何工作的),正如我們已經討論過的,這樣我們就可以很容易地理解它在 Python 中的實現。

在我們前進之前,我們應該確保我們已經滿足了上面列出的所有先決條件,這樣我們就不必在執行實施步驟時面臨任何問題。

DBSCAN 算法的實現步驟:

現在,我們將在 Python 中執行 DBSCAN 算法的實現。儘管如此,我們將按照前面提到的步驟進行,這樣實現部分就不會變得複雜,並且我們可以非常容易地理解它。為了在 Python 程序中實現 DBSCAN 算法及其邏輯,我們必須遵循以下步驟:

第一步:導入所有需要的庫:

首先,我們必須導入我們在先決條件部分安裝的所有必需的庫,以便我們可以在實現 DBSCAN 算法時使用它們的功能。

這裡我們首先導入了程序內部所有需要的庫或者庫的模塊:


# Importing numpy library as nmp
import numpy as nmp
# Importing pandas library as pds
import pandas as pds
# Importing matplotlib library as pplt
import matplotlib.pyplot as pplt
# Importing DBSCAN from cluster module of Sklearn library
from sklearn.cluster import DBSCAN
# Importing StandardSclaer and normalize from preprocessing module of Sklearn library
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import normalize
# Importing PCA from decomposition module of Sklearn
from sklearn.decomposition import PCA

第二步:加載數據:

在這一步中,我們必須加載這些數據,我們可以通過在程序中導入或加載數據集(這是 DBSCAN 算法處理數據集所必需的)來實現這一點。為了在程序中加載數據集,我們將使用 panda 庫的 read.csv() 函數,並打印來自數據集的信息,如下所示:


# Loading the data inside an initialized variable
M = pds.read_csv('sampleDataset.csv') # Path of dataset file
# Dropping the CUST_ID column from the dataset with drop() function
M = M.drop('CUST_ID', axis = 1)
# Using fillna() function to handle missing values
M.fillna(method ='ffill', inplace = True)
# Printing dataset head in output
print(M.head())

輸出:

       BALANCE  BALANCE_FREQUENCY  ...  PRC_FULL_PAYMENT  TENURE
0    40.900749           0.818182  ...          0.000000      12
1  3202.467416           0.909091  ...          0.222222      12
2  2495.148862           1.000000  ...          0.000000      12
3  1666.670542           0.636364  ...          0.000000      12
4   817.714335           1.000000  ...          0.000000      12

[5 rows x 17 columns]

上面輸出中給出的數據將在我們運行程序時打印出來,我們將從加載的數據集文件中處理這些數據。

第三步:數據預處理:

現在,我們將利用 Sklearn 庫預處理模塊的功能開始對這一步的數據集數據進行預處理。我們必須使用以下技術,同時用 Sklearn 庫函數預處理數據:


# Initializing a variable with the StandardSclaer() function
scalerFD = StandardScaler()
# Transforming the data of dataset with Scaler
M_scaled = scalerFD.fit_transform(M)
# To make sure that data will follow gaussian distribution
# We will normalize the scaled data with normalize() function
M_normalized = normalize(M_scaled)
# Now we will convert numpy arrays in the dataset into dataframes of panda
M_normalized = pds.DataFrame(M_normalized)

第四步:數據降維:

在這一步中,我們將降低縮放和標準化數據的維度,以便數據可以在程序中輕鬆可視化。為了轉換數據並降低其維數,我們必須以下列方式使用主成分分析函數:


# Initializing a variable with the PCA() function
pcaFD = PCA(n_components = 2) # components of data
# Transforming the normalized data with PCA
M_principal = pcaFD.fit_transform(M_normalized)
# Making dataframes from the transformed data
M_principal = pds.DataFrame(M_principal)
# Creating two columns in the transformed data
M_principal.columns = ['C1', 'C2']
# Printing the head of the transformed data
print(M_principal.head())

輸出:

         C1        C2
0 -0.489949 -0.679976
1 -0.519099  0.544828
2  0.330633  0.268877
3 -0.481656 -0.097610
4 -0.563512 -0.482506

正如我們在輸出中看到的,我們已經使用主成分分析將歸一化數據轉換為兩個分量,即兩列(我們可以在輸出中看到它們)。之後,我們使用 panda library dataframe() 函數從轉換後的數據製作數據幀。

第五步:建立聚類模型:

現在,這是實現的最重要的一步,因為在這裡我們必須構建數據的聚類模型(我們正在對其執行操作),我們可以通過使用 Sklearn 庫的 DBSCAN 函數來實現這一點,如下所述:


# Creating clustering model of the data using the DBSCAN function and providing parameters in it
db_default = DBSCAN(eps = 0.0375, min_samples = 3).fit(M_principal)
# Labelling the clusters we have created in the dataset
labeling = db_default.labels_

步驟 6:可視化聚類模型:


# Visualization of clustering model by giving different colours
colours = {}
# First colour in visualization is green
colours[0] = 'g'
# Second colour in visualization is black
colours[1] = 'k'
# Third colour in visualization is red
colours[2] = 'r'
# Last colour in visualization is blue
colours[-1] = 'b'
# Creating a colour vector for each data point in the dataset cluster
cvec = [colours[label] for label in labeling]
# Construction of the legend
# Scattering of green colour
g = pplt.scatter(M_principal['C1'], M_principal['C2'], color ='g');
# Scattering of black colour
k = pplt.scatter(M_principal['C1'], M_principal['C2'], color ='k');
# Scattering of red colour
r = pplt.scatter(M_principal['C1'], M_principal['C2'], color ='r');
# Scattering of green colour
b = pplt.scatter(M_principal['C1'], M_principal['C2'], color ='b'); 
# Plotting C1 column on the X-Axis and C2 on the Y-Axis
# Fitting the size of the figure with figure function
pplt.figure(figsize =(9, 9))
# Scattering the data points in the Visualization graph
pplt.scatter(M_principal['C1'], M_principal['C2'], c = cvec)
# Building the legend with the coloured data points and labelled
pplt.legend((g, k, r, b), ('Label M.0', 'Label M.1', 'Label M.2', 'Label M.-1'))
# Showing Visualization in the output
pplt.show()

輸出:

正如我們在輸出中看到的,我們使用數據集的數據點繪製了圖表,並通過用不同的顏色標記數據點來可視化聚類。

步驟 7:調整參數:

在這一步中,我們將通過更改先前在 DBSCAN 函數中給出的參數來調整模塊的參數,如下所示:


# Tuning the parameters of the model inside the DBSCAN function
dts = DBSCAN(eps = 0.0375, min_samples = 50).fit(M_principal)
# Labelling the clusters of data points
labeling = dts.labels_

步驟 8:變化的可視化:

現在,在調整我們創建的集群模型的參數之後,我們將通過用不同的顏色標記數據集中的數據點來可視化集群中發生的變化,就像我們之前所做的那樣。


# Labelling with different colours
colours1 = {}
# labelling with Red colour
colours1[0] = 'r'
# labelling with Green colour
colours1[1] = 'g'
# labelling with Blue colour
colours1[2] = 'b'
colours1[3] = 'c'
# labelling with Yellow colour
colours1[4] = 'y'
# Magenta colour
colours1[5] = 'm'
# labelling with Black colour
colours1[-1] = 'k'
# Labelling the data points with the colour variable we have defined
cvec = [colours1[label] for label in labeling]
# Defining all colour that we will use
colors = ['r', 'g', 'b', 'c', 'y', 'm', 'k' ]
# Scattering the colours onto the data points
r = pplt.scatter(
        M_principal['C1'], M_principal['C2'], marker ='o', color = colors[0])
g = pplt.scatter(
        M_principal['C1'], M_principal['C2'], marker ='o', color = colors[1])
b = pplt.scatter(
        M_principal['C1'], M_principal['C2'], marker ='o', color = colors[2])
c = pplt.scatter(
        M_principal['C1'], M_principal['C2'], marker ='o', color = colors[3])
y = pplt.scatter(
        M_principal['C1'], M_principal['C2'], marker ='o', color = colors[4])
m = pplt.scatter(
        M_principal['C1'], M_principal['C2'], marker ='o', color = colors[5])
k = pplt.scatter(
        M_principal['C1'], M_principal['C2'], marker ='o', color = colors[6])
# Fitting the size of the figure with figure function
pplt.figure(figsize =(9, 9))
# Scattering column 1 into X-axis and column 2 into y-axis
pplt.scatter(M_principal['C1'], M_principal['C2'], c = cvec)
# Constructing a legend with the colours we have defined
pplt.legend((r, g, b, c, y, m, k),
           ('Label M.0', 'Label M.1', 'Label M.2', 'Label M.3', 'Label M.4','Label M.5', 'Label M.-1'), # Using different labels for data points
           scatterpoints = 1, # Defining the scatter point
           loc ='upper left', # Location of cluster scattering
           ncol = 3, # Number of columns
           fontsize = 10) # Size of the font
# Displaying the visualisation of changes in cluster scattering
pplt.show()

輸出:

我們可以通過查看輸出來調整 DBSCAN 函數的參數,從而清楚地觀察到數據點的集群分散所帶來的變化。當我們觀察這些變化時,我們也可以理解 DBSCAN 算法是如何工作的,以及它如何有助於數據集中數據點的集群分散的可視化。


原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/256729.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-15 12:42
下一篇 2024-12-15 12:42

相關推薦

  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29

發表回復

登錄後才能評論