【问题标题】:Cosine similarity in TheanoTheano 中的余弦相似度
【发布时间】:2017-06-21 11:11:16
【问题描述】:

用 numpy 和 theano 计算余弦相似度的最简单方法是什么? 以 numpy 数组形式给出的向量。

我尝试仅使用 numpy 计算余弦相似度矩阵,但它的运行速度非常慢。但是,我对 theano 完全陌生,但假设这个库可以帮助我构建余弦相似度矩阵。

嗯,帮帮忙! :)

【问题讨论】:

  • 看看this是否有帮助。

标签: python numpy theano cosine-similarity trigonometry


【解决方案1】:

这是一篇关于 Python 中余弦相似度的帖子:Cosine Similarity between 2 Number Lists

我在 Numpy 和 Theano 中重写了 this answer

def cos_sim_numpy(v1, v2):
    numerator = sum(v1*v2)
    denominator = math.sqrt(sum(v1**2)*sum(v2**2))
    return numerator/denominator

def compile_cos_sim_theano():
    v1 = theano.tensor.vector(dtype=theano.config.floatX)
    v2 = theano.tensor.vector(dtype=theano.config.floatX)
    numerator = theano.tensor.sum(v1*v2)
    denominator = theano.tensor.sqrt(theano.tensor.sum(v1**2)*theano.tensor.sum(v2**2))
    return theano.function([v1, v2], numerator/denominator)

cos_sim_theano_fn = compile_cos_sim_theano()

v1 = numpy.asarray([3,45,7,2], dtype=np.float32)
v2 = numpy.asarray([2,54,13,15], dtype=np.float32)

print cos_sim_theano_fn(v1, v2), cos_sim_numpy(v1, v2)

Output: 0.972284251712 0.972284251712

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 2011-01-01
    • 2017-12-12
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2014-02-25
    相关资源
    最近更新 更多