计算向量与矩阵之间的距离 [英] Compute distance between vector and matrix

查看:717
本文介绍了计算向量与矩阵之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sklearn.metrics.pairwise.paired_distances计算单个向量和矩阵之间的距离.我想计算矩阵的每一行和单个向量之间的距离.由于sklearn.metrics.pairwise.paired_distances要求两个数组具有相等的维数,因此我使用np.tile创建一个包含多个向量副本的矩阵,以创建一个与第一个数组大小相同的矩阵.

I am using sklearn.metrics.pairwise.paired_distances to calculate distances between a single vector and a matrix. I want to calculate the distance between every row of the matrix and the single vector. Since sklearn.metrics.pairwise.paired_distances requires the two arrays to have equal dimensions, I use np.tile to create a matrix which contains multiple copies of the vector to create a matrix that has the same size as the first one.

示例:

import numpy as np
from sklearn.metrics.pairwise import paired_distances

# get matrix a and vector b
a = np.array([[1,2],[3,4]])
b = np.array([[5],[6]]).transpose()

# create a matrix with copies of b that has the same size as matrix a
b = np.tile(b,(a.shape[0],1))

distances = paired_distances(a,b)

只是出于好奇:是否有一个功能可以立即使用?在这里时间不是很关键,因为我不处理非常大的数组.但是该功能应提供不同种类的指标.

Just out of curiosity: Is there a function that does that out of the box? Time is not critical here, since I don't deal with very big arrays. But the function should offer different kinds of metrics.

推荐答案

您可以使用numpy.apply_along_axis方法将给定的函数应用于每一行.

You could use numpy.apply_along_axis method to apply a given function to each rows.

这篇关于计算向量与矩阵之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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