- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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 更好的解决方案是使用 cdist
和 cosine
度量。您正在有效地计算数据帧中的 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/
我有一个例程,它将接受 union 参数 d、theta、a 和 alpha 作为输入,并将生成相应的 4x4 齐次矩阵作为输出。我已经测试了我的矩阵乘法,它确实工作正常。我将从输入中得到 5 个矩阵
我有以下代码使用预先计算的内存表执行 Sin/Cos 函数。在下面的例子中,表格有 1024*128 个项目,涵盖了从 0 到 2pi 的所有 Sin/Cos 值。我知道我可以使用 Sin/Cos 对
问题是不言自明的。我看过几个 pi 的例子,但没有看到 trigo 函数。也许可以使用泰勒级数 as done here但我不完全确定如何在 python 中实现它。特别是如何存储这么多数字。我应该提
我开始学习 Python 中的数学模块,并试图围绕 Python 中的正弦、余弦和正切的三角函数。 我花了一些时间学习更多关于三角学的知识,并了解了直角三角形的基本公式是如何工作的: 正弦函数: si
我一个月前才开始学习这门 C++ 类(class)。现在我被分配去写一个程序来计算这个。我不知道我做错了什么。 #include #include float gatherl1(); float
这个问题在这里已经有了答案: Python cos(90) and cos(270) not 0 (3 个答案) 关闭 9 年前。 有没有办法获得角度(以弧度为单位)的精确正切/余弦/正弦? mat
这个问题在这里已经有了答案: Java Math.cos(Math.toRadians()) returns weird values (4 个答案) 关闭 10 年前。 我正在编写一个程序,我必须
我做了一个简单的计算器作为我的第一个android程序,现在我想给它添加trigonometry,log等函数。在 C 中,我们必须包含 math library 才能这样做,我似乎无法弄清楚你是如何
我正面临 objective-c 中 cos 函数的奇怪问题。我安装了带有 iOS 4.3 SDK 的 xcode 4.1.1。 我正在计算一个数的余弦值: y= cos(x*M_PI/180) 这将
尝试将以下 php 方法转换为在 .less 样式表中使用: 在 Less 中,如何在不使用特定语言的 cos()/sin() 函数的情况下实现正弦/余弦方法? .rotate(@deg) {
可以使用 iPhone 3GS 或 Pandora 的人请测试我刚刚编写的以下组装程序吗? 它应该在 NEON 矢量 FPU 上非常快速地计算正弦和余弦。我知道它编译得很好,但没有足够的硬件我无法测试
我为泰勒级数编写了以下函数来计算余弦。 double cosine(int x) { x %= 360; // make it less than 360 double rad = x
我是一名优秀的程序员,十分优秀!