簡體   English   中英

使用 TF-IDF 和余弦相似度匹配短語

[英]Matching phrase using TF-IDF and cosine similarity

我有一個看起來像這樣的 dataframe:

question                                answer
Why did the chicken cross the road?     to get to the other side
Who are you?                            a chatbot
Hello, how are you?                     Hi
.
.
.  

我想做的是使用 TF-IDF 在這個數據集上進行訓練。 當用戶輸入一個短語時,將使用余弦相似度選擇與該短語最匹配的問題。 我能夠以這種方式為訓練數據集上的句子創建 TF-IDF 值,但是我如何想出使用它來查找用戶輸入的新短語的余弦相似度分數?

from sklearn.feature_extraction.text import TfidfVectorizer
v = TfidfVectorizer()
x = v.fit_transform(intent_data["sentence"])

我認為你需要類似的東西

from sklearn.metrics.pairwise import cosine_similarity
cosine_similarities = cosine_similarity(x, v.transform(['user input'])).flatten()
best_match_index = cosine_similarities.argmax()

嘗試這個:

輸入:

question    answer
0   Why did the chicken cross the road? to get to the other side
1   Who are you?    a chatbot
2   Hello, how are you? Hi

#Script

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

#data = Input dataframe as above
v = TfidfVectorizer()
sentence_input = ["hello, you"]
similarity_index_list = cosine_similarity(v.fit_transform(data["question"]), v.transform(sentence_input)).flatten()
output = data.loc[similarity_index_list.argmax(), "answer"]

建議:使用一些基於預測的詞嵌入方法來維護 output 向量中的上下文,在句子歧義的情況下會得到更准確的結果。 (例如:fasttext、word2vec)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM