详细实现dbscan聚类,并实现可视化聚类结果
时间: 2024-06-11 09:07:04 浏览: 92
DBSCAN(Density-Based Spatial Clustering of Applications with Noise)是一种基于密度的聚类算法。它将数据点分为三类:核心点、边界点和噪声点。核心点是在某个半径内有足够多的其他点的点,边界点是不满足核心点条件但在核心点的半径内的点,噪声点是既不是核心点也不是边界点的点。
DBSCAN算法的基本思路是,从任意一个未被访问的数据点开始,搜索其半径内的邻居点,如果邻居点数量达到阈值,则将这些点视为同一簇的核心点,并将它们的邻居点加入同一簇中。依次遍历所有未被访问的点,直到所有点都被访问。
下面是一个简单的DBSCAN聚类的Python实现:
```python
import numpy as np
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
def dbscan(X, eps, min_samples):
labels = np.zeros(len(X))
cluster_id = 0
for i in range(len(X)):
if labels[i] != 0:
continue
neighbors = find_neighbors(X, i, eps)
if len(neighbors) < min_samples:
labels[i] = -1 # mark as noise
else:
cluster_id += 1
labels[i] = cluster_id
expand_cluster(X, labels, i, neighbors, eps, min_samples, cluster_id)
return labels
def expand_cluster(X, labels, i, neighbors, eps, min_samples, cluster_id):
for j in neighbors:
if labels[j] == -1:
labels[j] = cluster_id
elif labels[j] == 0:
labels[j] = cluster_id
j_neighbors = find_neighbors(X, j, eps)
if len(j_neighbors) >= min_samples:
neighbors = neighbors.union(j_neighbors)
def find_neighbors(X, i, eps):
neighbors = set()
for j in range(len(X)):
if np.linalg.norm(X[i] - X[j]) < eps:
neighbors.add(j)
return neighbors
# generate sample data
X, y = make_blobs(n_samples=1000, centers=3, n_features=2, random_state=123)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.show()
# run DBSCAN
labels = dbscan(X, eps=0.5, min_samples=5)
# plot results
plt.scatter(X[:, 0], X[:, 1], c=labels)
plt.show()
```
在这个例子中,我们生成了一个有3个中心的二维样本数据,然后用DBSCAN聚类算法对其进行聚类,并将结果可视化。可以看到,聚类效果还是比较不错的。
![dbscan](https://cdn.jsdelivr.net/gh/tsyccnh/image-store/img/dbscan.png)
阅读全文