使用 DBSCAN(基于密度的聚类算法) 对二维数据进行聚类分析-代码

时间:2024-11-19 18:53:05
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler

# 1. 生成示例数据
X, y = make_moons(n_samples=300, noise=0.05, random_state=42)  # 生成类似月亮形状的数据

# 2. 数据标准化(DBSCAN 对距离敏感,建议先标准化)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 3. 应用 DBSCAN
dbscan = DBSCAN(eps=0.2, min_samples=5)  # 设置超参数
labels = dbscan.fit_predict(X_scaled)

# 4. 可视化结果
# 获取每个簇的颜色
unique_labels = set(labels)
colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]

# 绘制聚类结果
plt.figure(figsize=(8, 6))
for k, col in zip(unique_labels, colors):
    if k == -1:
        # 噪声点标记为黑色
        col = [0, 0, 0, 1]
    
    class_member_mask = (labels == k)
    xy = X[class_member_mask]
    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=6)

plt.title("DBSCAN Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()

# 5. 输出聚类结果
for i in unique_labels:
    if i == -1:
        print(f"Cluster: Noise (Label {i}) - Number of points: {(labels == i).sum()}")
    else:
        print(f"Cluster: {i} - Number of points: {(labels == i).sum()}")