在本教程中,我們將學習如何在 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-tw/n/256729.html