python - 向量和 pandas 列(线性向量)之间的余弦相似度

标签 python python-3.x numpy scikit-learn array-broadcasting

我有一个 pandas 数据框,其中包含具有各自 Wine 属性的 Wine 列表。

然后我创建了一个新的列向量,其中包含来自这些属性的 numpy 向量。

def get_wine_profile(id):
wine = wines[wines['exclusiviId'] == id]
wine_vector = np.array(wine[wine_attrs].values.tolist()).flatten()

return wine_vector

wines['vector'] = wines.exclusiviId.apply(get_wine_profile)

因此向量列看起来像这样

vector

[1, 1, 1, 2, 2, 2, 2, 1, 1, 1]

[3, 1, 2, 1, 2, 2, 2, 0, 1, 3]

[1, 1, 2, 1, 3, 3, 3, 0, 1, 1]

.

.

现在我想在此列和另一个向量之间执行余弦相似度,该向量是用户输入的结果向量 这是我到目前为止尝试过的

from scipy.spatial.distance import cosine
cos_vec = wines.apply(lambda x: (1-cosine(wines["vector"],[1, 1, 1, 2, 2, 2, 2, 1, 1, 1]), axis=1)
Print(cos_vec)

这是抛出错误

ValueError: ('operands could not be broadcast together with shapes (63,) (10,) ', 'occurred at index 0')

我也尝试使用 sklearn,但它也有与 arrar 形状相同的问题

我想要作为最终输出的是一列,该列在该列和用户输入之间具有匹配分数

最佳答案

IMO 更好的解决方案是使用 cdistcosine 度量。您正在有效地计算数据帧中的 n 点与用户输入中的 1 点之间的成对距离,即总共 n 对。

如果您一次处理多个用户,效率会更高。

from scipy.spatial.distance import cdist

# make into 1x10 array
user_input = np.array([1, 1, 1, 2, 2, 2, 2, 1, 1, 1])[None]
df["cos_dist"] = cdist(np.stack(df.vector), user_input, metric="cosine")


# vector  cos_dist
# 0  [1, 1, 1, 2, 2, 2, 2, 1, 1, 1]   0.00000
# 1  [3, 1, 2, 1, 2, 2, 2, 0, 1, 3]   0.15880
# 2  [1, 1, 2, 1, 3, 3, 3, 0, 1, 1]   0.07613

顺便说一下,您似乎在使用 native Python 列表。我会将所有内容都切换到 numpy 数组。无论如何,当您调用 cosine 时,都会在后台发生向 np.array 的转换。

关于python - 向量和 pandas 列(线性向量)之间的余弦相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50698063/

相关文章:

python - 如何将数据附加到json文件?

python - Numpy 2d 直方图总和不为 1

python - 为包含深度嵌套 numpy 数组的 Python 对象实现 __eq__

python - 根据两个 pandas DataFrame 之间的条件为新列分配值

python - 如何从 shell 一个接一个地运行多个 python 脚本

python - 绘制回归线

python - 如何将 flask 和 flask_sockets 集成到一个运行在 uwsgi 下的应用程序中

python - 在 Python 中测试时间敏感的应用程序

python - 检查 python 3 支持的要求

json - Pandas:将 JSON 转换为 Pandas Dataframe