SciPy - single() 方法



SciPy single() 方法在下述矩陣中執行單/最小/最近連結任務。此方法的使用方式是定義兩個叢集之間的距離像兩個不同點之間的最短距離。

資料科學領域,我們使用此方法進行叢集分析。它用於識別資料模式、對齊項和異常檢測。

語法

以下是 SciPy single() 方法的語法 −

single(y)

引數

此函式僅接受一個引數 −

  • y: 此變數作為 single() 方法的引數,用於儲存資料繪製的列表陣列整數。

返回值

此方法返回連線矩陣(結果)。

示例 1

以下是 SciPy single() 方法闡述繪製資料點的單個連結的任務。

import numpy as np
from scipy.cluster.hierarchy import single, dendrogram
import matplotlib.pyplot as plt

# Distance matrix
y = np.array([0.5, 0.2, 0.3, 0.4, 0.8, 0.6])

# single linkage clustering
result = single(y)

# Plot the dendrogram
plt.figure(figsize=(6, 4))
dendrogram(result)
plt.title('Dendrogram - Single Linkage')
plt.xlabel('indexes')
plt.ylabel('Distance')
plt.show()

輸出

上述程式碼生成以下結果 −

scipy_single_method_one

示例 2

下方提供的一個示例闡述在隨機資料上執行單個連結聚類的任務。

import numpy as np
from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import single, dendrogram
import matplotlib.pyplot as plt

# Generate random data
data = np.random.rand(5, 2)

# calculate the distance matrix
y = pdist(data, metric='euclidean')

# single linkage clustering
result = single(y)

# Plot the dendrogram
plt.figure(figsize=(6, 4))
dendrogram(result)
plt.title('Dendrogram - Single Linkage on Random Data')
plt.xlabel('indexes')
plt.ylabel('Distance')
plt.show()

輸出

上述程式碼生成以下結果 −

scipy_single_method_two

示例 3

在此示例中,我們使用cityblock 作為度量型別來從給定資料集計算距離矩陣,然後利用單個連結聚類。然後我們使用 dendogram() 方法,該方法對聚類進行繪製和視覺化很有幫助。

import numpy as np
from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import single, dendrogram
import matplotlib.pyplot as plt

# Given data
data = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])

# calculate the distance matrix using a custom metric
y = pdist(data, metric='cityblock')

# single linkage clustering
result = single(y)

# Plot the dendrogram
plt.figure(figsize=(6, 4))
dendrogram(result)
plt.title('Dendrogram - Single Linkage with Cityblock Distance')
plt.xlabel('indexes')
plt.ylabel('Distance')
plt.show()

輸出

上述程式碼生成以下結果 −

scipy_single_method_three
scipy_reference.htm
廣告
© . All rights reserved.