http://blog.csdn.net/pipisorry/article/details/48814183

在scipy.spatial中最重要的模块应该就是距离计算模块distance了。

from scipy import spatial

距离计算

矩阵距离计算函数

矩阵参数每行代表一个观测值,计算结果就是每行之间的metric距离。Distance matrix computation from a collection of raw observation vectors stored in a rectangular array.

向量距离计算函数Distance functions between two vectors u and v

Distance functions between two vectors u and v. Computingdistances over a large collection of vectors is inefficient for thesefunctions. Use pdist for this purpose.

输入的参数应该是向量,也就是维度应该是(n, ),当然也可以是(1, n)它会使用squeeze自动去掉维度为1的维度;但是如果是多维向量,至少有两个维度>1就会出错。

e.g. spatial.distance.correlation(u, v)    #计算向量u和v之间的相关系数(pearson correlation coefficient, Centered Cosine)

Note: 如果向量u和v元素数目都只有一个或者某个向量中所有元素相同(分母norm(u - u.mean())为0),那么相关系数当然计算无效,会返回nan。

braycurtis(u, v) Computes the Bray-Curtis distance between two 1-D arrays.
canberra(u, v) Computes the Canberra distance between two 1-D arrays.
chebyshev(u, v) Computes the Chebyshev distance.
cityblock(u, v) Computes the City Block (Manhattan) distance.
correlation(u, v) Computes the correlation distance between two 1-D arrays.
cosine(u, v) Computes the Cosine distance between 1-D arrays.
dice(u, v) Computes the Dice dissimilarity between two boolean 1-D arrays.
euclidean(u, v) Computes the Euclidean distance between two 1-D arrays.
hamming(u, v) Computes the Hamming distance between two 1-D arrays.
jaccard(u, v) Computes the Jaccard-Needham dissimilarity between two boolean 1-D arrays.
kulsinski(u, v) Computes the Kulsinski dissimilarity between two boolean 1-D arrays.
mahalanobis(u, v, VI) Computes the Mahalanobis distance between two 1-D arrays.
matching(u, v) Computes the Matching dissimilarity between two boolean 1-D arrays.
minkowski(u, v, p) Computes the Minkowski distance between two 1-D arrays.
rogerstanimoto(u, v) Computes the Rogers-Tanimoto dissimilarity between two boolean 1-D arrays.
russellrao(u, v) Computes the Russell-Rao dissimilarity between two boolean 1-D arrays.
seuclidean(u, v, V) Returns the standardized Euclidean distance between two 1-D arrays.
sokalmichener(u, v) Computes the Sokal-Michener dissimilarity between two boolean 1-D arrays.
sokalsneath(u, v) Computes the Sokal-Sneath dissimilarity between two boolean 1-D arrays.
sqeuclidean(u, v) Computes the squared Euclidean distance between two 1-D arrays.
wminkowski(u, v, p, w) Computes the weighted Minkowski distance between two 1-D arrays.
yule(u, v) Computes the Yule dissimilarity between two boolean 1-D arrays.

[距离和相似度计算 ]

scipy.spatial.distance.pdist(X, metric=’euclidean’, p=2, w=None, V=None, VI=None)

pdist(X[, metric, p, w, V, VI])Pairwise distances between observations in n-dimensional space.观测值(n维)两两之间的距离。Pairwise distances between observations in n-dimensional space.距离值越大,相关度越小。

注意,距离转换成相似度时,由于自己和自己的距离是不会计算的默认为0,所以要先通过dist = spatial.distance.squareform(dist)转换成dense矩阵,再通过1 - dist计算相似度。

metric:

1 距离计算可以使用自己写的函数。Y = pdist(X, f) Computes the distance between all pairs of vectors in Xusing the user supplied 2-arity function f.

如欧式距离计算可以这样:

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

但是如果scipy库中有相应的距离计算函数的话,就不要使用dm = pdist(X, sokalsneath)这种方式计算,sokalsneath调用的是python自带的函数,会调用c(n, 2)次;而应该使用scipy中的optimized C version,使用dm = pdist(X, 'sokalsneath')。

再如矩阵行之间的所有cause effect值的计算可以这样:

def causal_effect(m):
    effect = lambda u, v: u.dot(v) / sum(u) - (1 - u).dot(v) / sum(1 - u)
    return spatial.distance.squareform(spatial.distance.pdist(m, metric=effect))

2 这里计算的是两两之间的距离,而不是相似度,如计算cosine距离后要用1-cosine才能得到相似度。从下面的consine计算公式就可以看出。

Y = pdist(X, ’euclidean’)    #d=sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2)

Y = pdist(X, ’minkowski’, p)

scipy.spatial.distance.cdist(XA, XB, metric=’euclidean’, p=2, V=None, VI=None, w=None)

cdist(XA, XB[, metric, p, V, VI, w])Computes distance between each pair of the two collections of inputs.

当然XA\XB最简单的形式是一个二维向量(也必须是,否则报错ValueError: XA must be a 2-dimensional array.),计算的就是两个向量之间的metric距离度量。

scipy.spatial.distance.squareform(X, force=’no’, checks=True)

squareform(X[, force, checks])Converts a vector-form distance vector to a square-form distance matrix, and vice-versa.

将向量形式的距离表示转换成dense矩阵形式。Converts a vector-form distance vector to a square-form distance matrix, and vice-versa.

注意:Distance matrix 'X' must be symmetric&diagonal must be zero.

皮皮blog

矩阵距离计算示例

示例1

x
array([[0, 2, 3],
       [2, 0, 6],
       [3, 6, 0]])
y=dis.pdist(x)
Iy
array([ 4.12310563,  5.83095189,  8.54400375])
z=dis.squareform(y)
z
array([[ 0.        ,  4.12310563,  5.83095189],
       [ 4.12310563,  0.        ,  8.54400375],
       [ 5.83095189,  8.54400375,  0.        ]])
type(z)
numpy.ndarray
type(y)
numpy.ndarray

示例2

print(sim)
print(spatial.distance.cdist(sim[].reshape((, )), sim[].reshape((, )), metric='cosine'))
print(spatial.distance.pdist(sim, metric='cosine'))

[[-2.85 -0.45]
 [-2.5   1.04]]

[[ 0.14790689]]

[ 0.14790689]

皮皮blog

检验距离矩阵有效性Predicates for checking the validity of distance matrices

Predicates for checking the validity of distance matrices, bothcondensed and redundant. Also contained in this module are functionsfor computing the number of observations in a distance matrix.

is_valid_dm(D[, tol, throw, name, warning]) Returns True if input array is a valid distance matrix.
is_valid_y(y[, warning, throw, name]) Returns True if the input array is a valid condensed distance matrix.
num_obs_dm(d) Returns the number of original observations that correspond to a square, redundant distance matrix.
num_obs_y(Y) Returns the number of original observations that correspond to a condensed distance matrix.

from:http://blog.csdn.net/pipisorry/article/details/48814183

ref: Distance computations (scipy.spatial.distance)

Spatial algorithms and data structures (scipy.spatial)

scipy-ref-0.14.0-p933

Scipy教程 - 距离计算库scipy.spatial.distance的更多相关文章

  1. Scipy 学习第3篇:数字向量的距离计算

    计算两个数字向量u和v之间的距离函数 1,欧氏距离(Euclidean distance) 在数学中,欧几里得距离或欧几里得度量是欧几里得空间中两点间"普通"(即直线)距离.使用这 ...

  2. Scipy教程 - 统计函数库scipy.stats

    http://blog.csdn.net/pipisorry/article/details/49515215 统计函数Statistical functions(scipy.stats) Pytho ...

  3. scipy.spatial.distance.cdist

    scipy.spatial.distance.cdist(XA, XB, metric='euclidean', p=2, V=None, VI=None, w=None)[source] Compu ...

  4. SciPy - 科学计算库(上)

    SciPy - 科学计算库(上) 一.实验说明 SciPy 库建立在 Numpy 库之上,提供了大量科学算法,主要包括这些主题: 特殊函数 (scipy.special) 积分 (scipy.inte ...

  5. SciPy 教程

    章节 SciPy 介绍 SciPy 安装 SciPy 基础功能 SciPy 特殊函数 SciPy k均值聚类 SciPy 常量 SciPy fftpack(傅里叶变换) SciPy 积分 SciPy ...

  6. Linux 64位下一键安装scipy等科学计算环境

    Linux 64位下一键安装scipy等科学计算环境 采用scipy.org的各种方法试过了,安装还是失败.找到了一键式安装包Anaconda,基本python要用到的库都齐了,而且还可以选择安装到其 ...

  7. Windows下安装python的scipy等科学计算包(转)

    如果要使用python进行科学计算.数据分析等,一定要安装scipy.seaborn.numpy等等包. 但Windows下安装python的第三方库经常会出现问题.此前,已介绍过Windows下如何 ...

  8. 相似度与距离计算python代码实现

    #定义几种距离计算函数 #更高效的方式为把得分向量化之后使用scipy中定义的distance方法 from math import sqrt def euclidean_dis(rating1, r ...

  9. 科学计算库Numpy基础&提升(理解+重要函数讲解)

    Intro 对于同样的数值计算任务,使用numpy比直接编写python代码实现 优点: 代码更简洁: numpy直接以数组.矩阵为粒度计算并且支持大量的数学函数,而python需要用for循环从底层 ...

随机推荐

  1. CSharpGL(48)用ShadowVolume画模型的影子

    CSharpGL(48)用ShadowVolume画模型的影子 在Per-Fragment Operations & Tests阶段,有一个步骤是模版测试(Stencil Test).依靠这一 ...

  2. Docker常见仓库MySQL

    MySQL 基本信息 MySQL 是开源的关系数据库实现. 该仓库提供了 MySQL 各个版本的镜像,包括 5.6 系列.5.7 系列等. 使用方法 默认会在 3306 端口启动数据库. $ sudo ...

  3. 王家林人工智能AI课程大纲和电子书 - 老师微信13928463918

    **3980元团购原价19800元的AI课程,团购请加王家林老师微信13928463918. 基于王家林老师独创的人工智能"项目情景投射"学习法,任何IT人员皆可在无需数学和Pyt ...

  4. 安卓onTextChanged参数解释及实现EditText字数监听 Editable使用

    原作者部分修改部分 补充部分 补充部分2 补充部分3 补充部分4 Editable 尊重原作者:此篇文章是借鉴原作者地址 的博文 并进行修改和增加补充说明,我只是补充和修改: 我感觉这篇文章经过我的补 ...

  5. YAML 在Python中的配置应用

    环境搭建 YAML语法 语法规则 数据结构 列表数组 原子量 YAML应用 案例 load dump 总结 YAML是一个堪比XML,JSON数据格式的更加方便,简洁的,易于人眼阅读的序列化数据格式. ...

  6. Bootstarp-table入门

    介绍 介绍什么的,大家自己去下面的网站看 Bootstrap中文网:http://www.bootcss.com/        Bootstrap Table Demo:http://issues. ...

  7. SQLite 创建表(http://www.w3cschool.cc/sqlite/sqlite-create-table.html)

    SQLite 创建表 SQLite 的 CREATE TABLE 语句用于在任何给定的数据库创建一个新表.创建基本表,涉及到命名表.定义列及每一列的数据类型. 语法 CREATE TABLE 语句的基 ...

  8. Struts 1 之配置文件

    web.xml中配置Struts的入口Servlet--ActionServlet,ActionServlet不负责任何的业务处理,它只是查找Action名单,找到path属性与URL属性一致的Act ...

  9. 1.QT中的容器QVector,QList,QSet,QMap,QQueue,QStack,QMultiMap,QSingleList等

    1  新建一个项目 在pro文件中只需要加上CONFIG += C++11 main.cpp #include <QMap> int main() { QMap<int,QStrin ...

  10. java实现异步调用实例

    在JAVA平台,实现异步调用的角色有如下三个角色: 调用者 取货凭证   真实数据 一个调用者在调用耗时操作,不能立即返回数据时,先返回一个取货凭证.然后在过一断时间后凭取货凭证来获取真正的数据.  ...