【发布时间】:2016-08-14 16:04:54
【问题描述】:
在 SO 和网络上有几个问题描述了如何在两个字符串之间,甚至在以 TFIDF 作为权重的两个字符串之间获取cosine similarity。但是像 scikit 的 linear_kernel 这样的函数的输出让我有点困惑。
考虑以下代码:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
a = ['hello world', 'my name is', 'what is your name?']
b = ['my name is', 'hello world', 'my name is what?']
df = pd.DataFrame(data={'a':a, 'b':b})
df['ab'] = df.apply(lambda x : x['a'] + ' ' + x['b'], axis=1)
print(df.head())
a b ab
0 hello world my name is hello world my name is
1 my name is hello world my name is hello world
2 what is your name? my name is what? what is your name? my name is what?
问题:
我想有一列是a 中的字符串和b 中的字符串之间的余弦相似度。
我尝试了什么:
我在ab上训练了一个TFIDF分类器,以便包含所有单词:
clf = TfidfVectorizer(ngram_range=(1, 1), stop_words='english')
clf.fit(df['ab'])
然后我得到了a 和b 列的稀疏 TFIDF 矩阵:
tfidf_a = clf.transform(df['a'])
tfidf_b = clf.transform(df['b'])
现在,如果我使用其他人推荐的 scikit 的 linear_kernel,我会返回一个 (nfeatures,nfeatures) 的 Gram 矩阵,如他们的文档中所述。
from sklearn.metrics.pairwise import linear_kernel
linear_kernel(tfidf_a,tfidf_b)
array([[ 0., 1., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
但是我需要的是一个简单的向量,其中第一个元素是a的第一行和b的第一行之间的cosin_sim,第二个元素是cos_sim(a[1],b[ 1]),等等。
使用 python3,scikit-learn 0.17。
【问题讨论】:
标签: python tf-idf cosine-similarity