从数据集中以线的形式提取聚类

Extracting clusters in the form of lines from a dataset

我有一个类似于下图的数据集,从我的角度来看,它清楚地形成了线条。我不想绘制标记,而是想用一条线连接每条曲线内的标记。我很好奇,在这种情况下,哪种聚类算法比较好?

import numpy as np
import matplotlib.pyplot as plt
np.random.seed = 42

#Generate (x,y) data
x = np.linspace(0.1,0.9,50)
y = x%1
x += np.sin(2*x%1)
y = y%0.2

#Shuffle (x,y) data
ns = list(range(len(x)))
np.random.shuffle(ns)
x = x[ns]
y = y[ns]

#Plot
fig, axs = plt.subplots(1,2)
axs[0].scatter(x,y)
axs[1].plot(x,y)
plt.savefig("markers vs lines.pdf")

- 左:标记,右:由线连接的数据点。

由于架构原因,此类数据在图像分析中很常见。

为了推断透视,人们使用霍夫变换来识别点线。

这可能是在这里使用的最佳方法。

既然你问的是聚类算法,你可能想看看DBSCAN。

http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html

有两个参数,epsilon 和聚类的点数。

这是让您入门的代码:

from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler

import numpy as np
import matplotlib.pyplot as plt
np.random.seed = 42
%matplotlib inline

#Generate (x,y) data
x = np.linspace(0.1,0.9,50)
y = x%1
x += np.sin(2*x%1)
y = y%0.2

#Shuffle (x,y) data
ns = list(range(len(x)))
np.random.shuffle(ns)
x = x[ns]
y = y[ns]

"""
    Fit the Data 
"""
X = [i for i in zip(x,y)]
X = StandardScaler().fit_transform(X)

"""
    Compute the DBSCAN
"""
db = DBSCAN(eps=0.5, min_samples=1).fit(X)
labels = db.labels_

# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_clusters_

"""
    Plot the clusters
"""
d= dict(zip(set(labels),['red','green','blue','yellow','purple','grey']))
d[-1] = "black"
plt.scatter(x,y,color=[ d[i] for i in labels])
plt.show()

结果:

灵感来自:http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html

更多关于 DBSCAN 参数的信息:http://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#sklearn.cluster.DBSCAN

希望对您有所帮助。