DBSCAN算法 python代码
时间: 2023-10-02 12:14:13 浏览: 129
以下是一个简单的Python实现DBSCAN算法的代码示例:
```python
import numpy as np
class DBSCAN:
def __init__(self, eps=0.5, min_samples=5):
self.eps = eps
self.min_samples = min_samples
def fit(self, X):
self.labels_ = np.zeros(len(X))
C = 0
for i in range(len(X)):
if self.labels_[i] != 0:
continue
neighbors = self.get_neighbors(X, i)
if len(neighbors) < self.min_samples:
self.labels_[i] = -1 # noise point
else:
C += 1
self.expand_cluster(X, i, neighbors, C)
def get_neighbors(self, X, i):
d = np.sqrt(np.sum((X - X[i]) ** 2, axis=1))
return np.where(d <= self.eps)[0]
def expand_cluster(self, X, i, neighbors, C):
self.labels_[i] = C
for j in neighbors:
if self.labels_[j] == -1:
self.labels_[j] = C
elif self.labels_[j] == 0:
self.labels_[j] = C
new_neighbors = self.get_neighbors(X, j)
if len(new_neighbors) >= self.min_samples:
neighbors = np.concatenate((neighbors, new_neighbors))
```
该代码实现了DBSCAN算法的核心逻辑,其中`fit`函数是算法的主要实现部分。在该函数中,首先初始化所有样本点的标签为0,然后遍历每一个样本点。对于每个未被访问过的点,找到与其距离小于等于eps的邻居,如果邻居数量小于min_samples,则将该点标记为噪声点;否则,将该点标记为第C个簇的一个点,并将该点的邻居加入到簇中,并继续向外扩展簇。在扩展簇时,同样需要考虑邻居是否已被访问过或已被归到某个簇中。
阅读全文