如何在python中绘制k距离图

问题描述 投票:2回答:3

如何绘制(在python中)DBSCAN中给定的最小点值的距离图?

我正在寻找膝盖和相应的epsilon值。

在sklearn我没有看到任何返回这种距离的方法....我错过了什么吗?

python cluster-analysis dbscan
3个回答
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()

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.DataFramenumpy.ndarrayn是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
投票

首先,您可以定义一个函数来计算每个点到其第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');

enter image description here

在上面的例子中,绝大多数点位于距其第四个最近邻居0.12个单位内。因此,启发式方法可以选择0.12作为epsilon参数。

© www.soinside.com 2019 - 2024. All rights reserved.