简体   繁体   English

在 Python 中,如何将 numpy 数组与矩阵的每一行进行比较以选择与向量最相似的行?

[英]In Python, how can I compare a numpy array to each row of a matrix to chose the row that is most similar to the vector?

For instance, if I have a 1D array [91, 119, 161, 203, 259] and a 2D array [[90,120,160,200,260], [95,115,165,204,255]] , how can I determine which row from the latter is a better match for the former?例如,如果我有一个一维数组[91, 119, 161, 203, 259]和一个二维数组[[90,120,160,200,260], [95,115,165,204,255]] ,我如何确定后者的哪一行是更好的匹配?

In this case, it would be the first row because most numbers are only off by 1, whereas in the second row most numbers are off by 4. Also, the RMSE between the vector and the first row is 1.612, whereas for the second row it is 3.606.在这种情况下,它将是第一行,因为大多数数字仅相差 1,而在第二行中,大多数数字相差 4。此外,向量和第一行之间的 RMSE 为 1.612,而对于第二行它是 3.606。

There are many distance metrics, but cosine is a good measure for vector similarities.有许多距离度量,但余弦是向量相似性的一个很好的度量。 You can use scipy.spatial.distance.cosine to find the cosine distance.您可以使用scipy.spatial.distance.cosine来查找余弦距离。 You'll want the vector with the smallest cosine distance.您将需要具有最小余弦距离的向量。

In code:在代码中:

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

v = np.array([91, 119, 161, 203, 259])
matrix = np.array([[90,120,160,200,260], [95,115,165,204,255]])
assert np.argmin([cosine(v, row) for row in matrix]) == 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何有效地将矩阵变换应用于NumPy数组的每一行? - How can I apply a matrix transform to each row of a NumPy array efficiently? Python-如何将数组添加到唯一的numpy数组? 每个数组必须代表我的numpy数组中的一行 - Python - How can i add arrays to an unique numpy array ? Each array must represent a row in my numpy array Python Numpy:向现有矩阵行添加向量 - Python Numpy: Adding vector to existing matrix row 使用python矩阵M(使用numpy),如何将该矩阵的每一列与所有其他列进行比较? - With a python matrix M (using numpy), how can I compare each column of that matrix with all other columns? 如何将 numpy 数组的每一行向量与其自身和每个元素进行比较 - How to compare each row of vectors of numpy array to itself and every element 用矩阵乘以numpy数组的每一行 - Multipy each row of numpy array with matrix 如何使用Numpy将矢量中的ith值沿着矩阵的ith行分布在向量中? - How can I distribute the ith value in a vector along the ith row of a matrix using Numpy? 如何从python矩阵的每一列中选择具有最多最小值的行? - How do I select a row with most number of minimum values out of each column from a matrix in python? 如何将矩阵的每一行与numpy相乘 - how to multiply each row of a matrix with numpy Numpy 运算符用于具有矩阵单独行乘法的每个向量元素 - Numpy operator for each vector element with matrix individual row multiplication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM