学习测试代码
"""
# -*- coding: utf-8 -*-
# @Time : 2024/1/27 16:10
# @Author : 王摇摆
# @FileName: code2.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/weixin_44943389?type=blog
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
# 生成模拟数据
centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4, random_state=0)
# 标准化特征值,因为DBSCAN对于特征的标度非常敏感
X = StandardScaler().fit_transform(X)
# 绘制聚类前的数据分布
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.scatter(X[:, 0], X[:, 1], c='gray', edgecolor='k', s=20)
plt.title("Sample data before clustering")
# 应用DBSCAN聚类算法
# 为了模拟DFD-DBSCAN的行为,我们可能需要手动调整eps和min_samples
# 这里我们假设已经通过某种方法得到了这些优化的参数
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
# 计算聚类的数量(忽略噪声即label为-1的点)
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_noise_ = list(labels).count(-1)
# 可视化结果
unique_labels = set(labels)
colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]
plt.figure(figsize=(10, 8))
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 & core_samples_mask]
plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=14)
# 绘制非核心点
xy = X[class_member_mask & ~core_samples_mask]
plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=6)
plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.show()
# 输出噪声点的数量和聚类的数量
print("Estimated number of clusters:", n_clusters_)
print("Estimated number of noise points:", n_noise_)
方法体会
DBSCAN聚类算法的结果。在图中,你可以看到数据点被分成了三个不同的簇,每个簇用不同的颜色标记。
DBSCAN算法的工作原理是基于密度的聚类,意味着算法会将密集的点组成一个簇,而将稀疏的点标记为噪声。在这张图上:
三种颜色的点(红色、绿色和橙色)代表了算法确定的三个簇。
每个簇的点紧密地聚集在一起,这意味着在这些区域内的点之间的密度超过了算法设定的阈值。
黑色点表示噪声,也就是说,这些点的密度太低,无法归入任何簇中。
图中的标题 “Estimated number of clusters: 3” 表明算法估计数据中存在三个簇。DBSCAN算法的优势之一是它不需要预先指定簇的数量;它会基于数据本身的特性来决定簇的数量。