我希望在几个时间戳(几分钟)内进行聚类。 所以我到目前为止所做的是:
1)将点转换为弧度
#points containing time value in minutes
points = [100, 200, 600, 659, 700]
def convert_to_radian(x):
return((x / (24 * 60)) * 2 * pi)
rad_function = np.vectorize(convert_to_radian)
points_rad = rad_function(points)
2)生成距离矩阵
#generate distance matrix from each point
dist = points_rad[None,:] - points_rad[:, None]
3)从每个点分配最短距离
dist[((dist > pi) & (dist <= (2*pi)))] = dist[((dist > pi) & (dist <= (2*pi)))] -(2*pi)
dist[((dist > (-2*pi)) & (dist <= (-1*pi)))] = dist[((dist > (-2*pi)) & (dist <= (-1*pi)))] + (2*pi)
dist = abs(dist)
现在我想在距离矩阵上使用DBSCAN,我如何将其聚类到弧度距离?
谢谢!
答案 0 :(得分:1)
好的,经过多次挖掘,我意识到我可以简单地将DBSCAN指标设置为“预先计算”,使用.fit()
方法并传入我的距离矩阵。对于那些感兴趣的人来源:
import numpy as np
from math import pi
from sklearn.cluster import DBSCAN
#points containing time value in minutes
points = [100, 200, 600, 659, 700]
def convert_to_radian(x):
return((x / (24 * 60)) * 2 * pi)
rad_function = np.vectorize(convert_to_radian)
points_rad = rad_function(points)
#generate distance matrix from each point
dist = points_rad[None,:] - points_rad[:, None]
#Assign shortest distances from each point
dist[((dist > pi) & (dist <= (2*pi)))] = dist[((dist > pi) & (dist <= (2*pi)))] -(2*pi)
dist[((dist > (-2*pi)) & (dist <= (-1*pi)))] = dist[((dist > (-2*pi)) & (dist <= (-1*pi)))] + (2*pi)
dist = abs(dist)
#check dist
print(dist)
#using default values, set metric to 'precomputed'
db = DBSCAN(eps=((100 / (24*60)) * 2 * pi ), min_samples = 2, metric='precomputed')
#check db
print(db)
db.fit(dist)
#get labels
labels = db.labels_
#get number of clusters
no_clusters = len(set(labels)) - (1 if -1 in labels else 0)
print('No of clusters:', no_clusters)
print('Cluster 0 : ', np.nonzero(labels == 0)[0])
print('Cluster 1 : ', np.nonzero(labels == 1)[0])
输出:
[[ 0. 0.43633231 2.18166156 2.43909763 2.61799388]
[ 0.43633231 0. 1.74532925 2.00276532 2.18166156]
[ 2.18166156 1.74532925 0. 0.25743606 0.43633231]
[ 2.43909763 2.00276532 0.25743606 0. 0.17889625]
[ 2.61799388 2.18166156 0.43633231 0.17889625 0. ]]
DBSCAN(algorithm='auto', eps=0.4363323129985824, leaf_size=30,
metric='precomputed', min_samples=2, p=None, random_state=None)
No of clusters: 2
Cluster 0 : [0 1]
Cluster 1 : [2 3 4]