如何绘制(在python中)DBSCAN中给定的最小点值的距离图?
我正在寻找膝盖和相应的epsilon值。
在sklearn我没有看到任何返回这种距离的方法......我错过了什么吗?
答案 0 :(得分:3)
要获得距离,您可以使用此功能:
import numpy as np
import pandas as pd
import math
def k_distances(X, n=None, dist_func=None):
"""Function to return array of k_distances.
X - DataFrame matrix with observations
n - number of neighbors that are included in returned distances (default number of attributes + 1)
dist_func - function to count distance between observations in X (default euclidean function)
"""
if type(X) is pd.DataFrame:
X = X.values
k=0
if n == None:
k=X.shape[1]+2
else:
k=n+1
if dist_func == None:
# euclidean distance square root of sum of squares of differences between attributes
dist_func = lambda x, y: math.sqrt(
np.sum(
np.power(x-y, np.repeat(2,x.size))
)
)
Distances = pd.DataFrame({
"i": [i//10 for i in range(0, len(X)*len(X))],
"j": [i%10 for i in range(0, len(X)*len(X))],
"d": [dist_func(x,y) for x in X for y in X]
})
return np.sort([g[1].iloc[k].d for g in iter(Distances.groupby(by="i"))])
X
应为pandas.DataFrame
或numpy.ndarray
。 n
是d-neighborhood中的邻居数。你应该知道这个号码。默认情况下是属性数+ 1。
要绘制这些距离,您可以使用此代码:
import matplotlib.pyplot as plt
d = k_distances(X,n,dist_func)
plt.plot(d)
plt.ylabel("k-distances")
plt.grid(True)
plt.show()
答案 1 :(得分:3)
您可能希望使用numpy提供的矩阵运算来加速距离矩阵的计算。
def k_distances2(x, k):
dim0 = x.shape[0]
dim1 = x.shape[1]
p=-2*x.dot(x.T)+np.sum(x**2, axis=1).T+ np.repeat(np.sum(x**2, axis=1),dim0,axis=0).reshape(dim0,dim0)
p = np.sqrt(p)
p.sort(axis=1)
p=p[:,:k]
pm= p.flatten()
pm= np.sort(pm)
return p, pm
m, m2= k_distances2(X, 2)
plt.plot(m2)
plt.ylabel("k-distances")
plt.grid(True)
plt.show()
答案 2 :(得分:1)
首先,您可以定义一个函数来计算每个点到第k个最近邻居的距离:
def calculate_kn_distance(X,k):
kn_distance = []
for i in range(len(X)):
eucl_dist = []
for j in range(len(X)):
eucl_dist.append(
math.sqrt(
((X[i,0] - X[j,0]) ** 2) +
((X[i,1] - X[j,1]) ** 2)))
eucl_dist.sort()
kn_distance.append(eucl_dist[k])
return kn_distance
然后,一旦定义了函数,就可以选择一个 k 值,并绘制直方图以找到一个膝盖来定义一个合适的 epsilon 值。
eps_dist = calculate_kn_distance(X[1],4)
plt.hist(eps_dist,bins=30)
plt.ylabel('n');
plt.xlabel('Epsilon distance');
在上面的示例中,绝大多数点位于距它们的第四个最近邻点0.12个单位内。因此,一种启发式方法可能是选择0.12作为 epsilon 参数。
答案 3 :(得分:0)
我会尽力为将来的观众制作广泛的指南
简而言之,步骤是(使用distance matrix)
让我们采用n = 7的简单数据集
x, y
1 1, 1
2 1.5, 1.5
3 1.25,1.25
4 1.5, 1
5 1, 1.5
6 1.75,1.75
7 3, 2
The sorted distance matrix
[[0, 0.353, 0.5, 0.5, 0.707, 1.061, 2.236]
[0, 0.353, 0.353, 0.5, 0.5, 0.707, 1.581]
[0, 0.353, 0.353, 0.353, 0.353, 0.707, 1.904]
[0, 0.353, 0.5, 0.5, 0.707, 0.791, 1.803]
[0, 0.353, 0.5, 0.5, 0.707, 0.791, 2.062]
[0, 0.353, 0.707, 0.791, 0.791, 1.061, 1.275]
[0, 1.273, 1.581, 1.803, 1.904, 2.062, 2.236]]
The sorted kth (k=4) Column (5th column)
[1.904,0.791,0.707,0.707,0.707,0.5,0.353]
现在绘制将产生
plt.plot([0,1,2,3,4,5,6],[1.904,0.791,0.707,0.707,0.707,0.5,0.353])
您可以看到在0.79处有一个很大的弯曲。因此,对于k / minpts = 4,任何第k个邻居距离> 0.79的点都将被视为噪声/非核心点。
当然,我们不能保证图中会出现强烈的弯曲甚至完全弯曲,这完全取决于数据的分布
The original paper