我想在一个包含许多行的文件上使用TfidfVectorizer(),每个行都是一个短语。然后,我想获取一个包含一小部分短语的测试文件,执行 TfidfVectorizer(),然后获取原始文件和测试文件之间的余弦相似性,以便对于测试文件中的给定短语,我检索原始文件中的前 N 个匹配项。这是我的尝试:
corpus = tuple(open("original.txt").read().split('n'))
test = tuple(open("test.txt").read().split('n'))
from sklearn.feature_extraction.text import TfidfVectorizer
tf = TfidfVectorizer(analyzer='word', ngram_range=(1,3), min_df = 0, stop_words = 'english')
tfidf_matrix = tf.fit_transform(corpus)
tfidf_matrix2 = tf.fit_transform(test)
from sklearn.metrics.pairwise import linear_kernel
def new_find_similar(tfidf_matrix2, index, tfidf_matrix, top_n = 5):
cosine_similarities = linear_kernel(tfidf_matrix2[index:index+1], tfidf_matrix).flatten()
related_docs_indices = [i for i in cosine_similarities.argsort()[::-1] if i != index]
return [(index, cosine_similarities[index]) for index in related_docs_indices][0:top_n]
for index, score in find_similar(tfidf_matrix, 1234567):
print score, corpus[index]
但是我得到:
for index, score in new_find_similar(tfidf_matrix2, 1000, tfidf_matrix):
print score, test[index]
Traceback (most recent call last):
File "<ipython-input-53-2bf1cd465991>", line 1, in <module>
for index, score in new_find_similar(tfidf_matrix2, 1000, tfidf_matrix):
File "<ipython-input-51-da874b8d3076>", line 2, in new_find_similar
cosine_similarities = linear_kernel(tfidf_matrix2[index:index+1], tfidf_matrix).flatten()
File "C:UsersarronAppDataLocalContinuumAnaconda2libsite-packagessklearnmetricspairwise.py", line 734, in linear_kernel
X, Y = check_pairwise_arrays(X, Y)
File "C:UsersarronAppDataLocalContinuumAnaconda2libsite-packagessklearnmetricspairwise.py", line 122, in check_pairwise_arrays
X.shape[1], Y.shape[1]))
ValueError: Incompatible dimension for X and Y matrices: X.shape[1] == 66662 while Y.shape[1] == 3332088
我不介意合并两个文件然后进行转换,但我想确保我不会将测试文件中的任何短语与测试文件中其他短语进行比较。
有什么指示吗?
用语料库中的数据拟合TfidfVectorizer
,然后使用已经拟合的矢量化器转换测试数据(即,不要调用fit_transform
两次):
tfidf_matrix = tf.fit_transform(corpus)
tfidf_matrix2 = tf.transform(test)