![](/img/trans.png)
[英]String Matching Using TF-IDF, NGrams and Cosine Similarity in Python
[英]Python: MemoryError when computing tf-idf cosine similarity between two columns in Pandas
我正在尝试计算Pandas数据帧中两列之间的tf-idf向量余弦相似度。 一列包含搜索查询,另一列包含产品标题。 余弦相似度值旨在成为搜索引擎/排名机器学习算法的“特征”。
我在iPython笔记本中这样做,不幸的是遇到了MemoryErrors,并且在经过几个小时的挖掘后我不确定为什么。
我的设置:
我根据类似的stackoverflow问题在小玩具数据集上测试了我的代码/目标:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy import spatial
clf = TfidfVectorizer()
a = ['hello world', 'my name is', 'what is your name?', 'max cosine sim']
b = ['my name is', 'hello world', 'my name is what?', 'max cosine sim']
df = pd.DataFrame(data={'a':a, 'b':b})
clf.fit(df['a'] + " " + df['b'])
tfidf_a = clf.transform(df['a']).todense()
tfidf_b = clf.transform(df['b']).todense()
row_similarities = [1 - spatial.distance.cosine(tfidf_a[x],tfidf_b[x]) for x in range(len(tfidf_a)) ]
df['tfidf_cosine_similarity'] = row_similarities
print(df)
这给出了以下(好!)输出:
a b tfidf_cosine_similarity
0 hello world my name is 0.000000
1 my name is hello world 0.000000
2 what is your name? my name is what? 0.725628
3 max cosine sim max cosine sim 1.000000
但是,当我尝试将相同的方法应用于维度为186,154 x 5的数据框(df_all_export)时(查询(search_term)和文档(product_title)的5列中的2列如此:
clf.fit(df_all_export['search_term'] + " " + df_all_export['product_title'])
tfidf_a = clf.transform(df_all_export['search_term']).todense()
tfidf_b = clf.transform(df_all_export['product_title']).todense()
row_similarities = [1 - spatial.distance.cosine(tfidf_a[x],tfidf_b[x]) for x in range(len(tfidf_a)) ]
df_all_export['tfidf_cosine_similarity'] = row_similarities
df_all_export.head()
我得到了......(这里没有给出完整的错误,但是你明白了):
MemoryError Traceback (most recent call last)
<ipython-input-27-8308fcfa8f9f> in <module>()
12 clf.fit(df_all_export['search_term'] + " " + df_all_export['product_title'])
13
---> 14 tfidf_a = clf.transform(df_all_export['search_term']).todense()
15 tfidf_b = clf.transform(df_all_export['product_title']).todense()
16
绝对迷失在这一个,但我担心解决方案将非常简单和优雅:)
先感谢您!
您仍然可以使用sklearn.metrics.pairwise方法处理sparsed matrixes / arrays:
# I've executed your example up to (including):
# ...
clf.fit(df['a'] + " " + df['b'])
A = clf.transform(df['a'])
B = clf.transform(df['b'])
from sklearn.metrics.pairwise import *
paired_cosine_distances
将显示您的字符串有多远或多少不同(比较两列中的值“逐行”)
0
- 表示完全匹配
In [136]: paired_cosine_distances(A, B)
Out[136]: array([ 1. , 1. , 0.27437247, 0. ])
cosine_similarity
将比较列a
第一个字符串和列b
所有字符串( 第1行 ); 柱的第二串a
与列中的所有串b
( 第2行 )等等...
In [137]: cosine_similarity(A, B)
Out[137]:
array([[ 0. , 1. , 0. , 0. ],
[ 1. , 0. , 0.74162106, 0. ],
[ 0.43929881, 0. , 0.72562753, 0. ],
[ 0. , 0. , 0. , 1. ]])
In [141]: A
Out[141]:
<4x10 sparse matrix of type '<class 'numpy.float64'>'
with 12 stored elements in Compressed Sparse Row format>
In [142]: B
Out[142]:
<4x10 sparse matrix of type '<class 'numpy.float64'>'
with 12 stored elements in Compressed Sparse Row format>
注意:所有计算都是使用稀疏矩阵 - 我们没有在内存中解压缩它们!
通过上面MaxU发布的亲切帮助和解决方案,我在这里展示了完成我试图实现的任务的完整代码。 除了MemoryError
之外,当我尝试一些“hacky”变通方法时,它还会避免在余弦相似度计算中出现奇怪的nans。
注意下面的代码是一个部分片段,在这个意义上,已经在完整代码中构造了尺寸为186,134 x 5
的大数据帧df_all_export
。
我希望这有助于其他试图在搜索查询和匹配文档之间使用tf-idf向量计算余弦相似度的人。 对于这样一个常见的“问题”,我很难找到一个用SKLearn和Pandas实现的明确解决方案。
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import paired_cosine_distances as pcd
clf = TfidfVectorizer()
clf.fit(df_all_export['search_term'] + " " + df_all_export['product_title'])
A = clf.transform(df_all_export['search_term'])
B = clf.transform(df_all_export['product_title'])
cosine = 1 - pcd(A, B)
df_all_export['tfidf_cosine'] = cosine
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.