我有一个如下所示的数据框:
question answerWhy did the chicken cross the road? to get to the other sideWho are you? a chatbotHello, how are you? Hi...
我想使用TF-IDF来训练这个数据集。当用户输入一个短语时,使用余弦相似度来选择与该短语最匹配的问题。我能够以这种方式为训练数据集中的句子创建TF-IDF值,但是如何使用这个来计算用户输入的新短语的余弦相似度得分呢?
from sklearn.feature_extraction.text import TfidfVectorizerv = TfidfVectorizer()x = v.fit_transform(intent_data["sentence"])
回答:
我想你需要这样的代码:
from sklearn.metrics.pairwise import cosine_similaritycosine_similarities = cosine_similarity(x, v.transform(['user input'])).flatten()best_match_index = cosine_similarities.argmax()