gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:33:16 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com