在python中将pdist()与您定义的自定义距离函数一起使用 [英] Use pdist() in python with a custom distance function defined by you

查看:84
本文介绍了在python中将pdist()与您定义的自定义距离函数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 scipy.spatial.distance.pdist(...) 在python中已变得有用且快速.

I have been interested in usage of scipy.spatial.distance.pdist(...) in python which has come to be useful and fast for some of the applications I have been working on.

我需要使用成对的距离函数,该函数是自定义的,而不是度量标准定义的标准默认距离度量标准.让我们做一个简单的例子,假设我不想使用 euclidean 距离函数,如下所示:

I need to use a pairwise distance function which are custom and not standard default distance metrics as defined by the metric. Let's make a simple example, suppose I do not want to use euclidean distance function as the following:

 Y = pdist(X, 'euclidean')

相反,我想自己定义欧几里得函数,并将其作为函数或参数传递给 pdist().如何将 euclidean distance函数的实现传递给该函数,以获得完全相同的结果.该问题的答案将帮助我以自己感兴趣的方式使用该功能.

Instead I want to define the euclidean function myself and pass it as a function or argument to pdist(). How can I pass the implementation of euclidean distance function to this function to get exactly the same results. The answer to this question, will help me to use the function in the way I am interested in.

在MATLAB中,我知道如何使用 pdist(),而在Python中我还没有使用.谢谢您的建议

In MATLAB, I know how to use pdist(), in Python I don't yet. Thanks for your suggestion

推荐答案

There is an example in the documentation for pdist:

import numpy as np
from scipy.spatial.distance import pdist

dm = pdist(X, lambda u, v: np.sqrt(((u-v)**2).sum()))

如果要使用常规函数而不是lambda函数,则等价于

If you want to use a regular function instead of a lambda function the equivalent would be

import numpy as np
from scipy.spatial.distance import pdist

def dfun(u, v):
    return np.sqrt(((u-v)**2).sum())

dm = pdist(X, dfun)

这篇关于在python中将pdist()与您定义的自定义距离函数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆