用語意相似度來分類文字
語意相似度的主要目標是衡量一對單字、片語、句子或文件之間語意的距離。例如,「car」和「bus」比起「car」和「cat」更相似。在這個練習中,你要從 Amazon Fine Food Reviews 的範例文字裡,找出和單字 sauce 最相近的句子。你可以用 spacy 計算單字 sauce 與給定 texts 字串中各句子的相似度分數,並回報最相似句子的分數。
已預先載入包含所有評論 Text 欄位資料的 texts 字串。這個練習將使用 English 模型 en_core_web_md,已經以 nlp 提供。
本練習屬於課程
使用 spaCy 的自然語言處理
練習說明
- 使用
nlp產生單字sauce與texts的Doc容器,並分別存到key和sentences。 - 計算單字
sauce與texts字串中每個句子的相似度分數(四捨五入到小數點後兩位)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Populate Doc containers for the word "sauce" and for "texts" string
key = ____
sentences = ____
# Calculate similarity score of each sentence and a Doc container for the word sauce
semantic_scores = []
for sent in sentences.____:
semantic_scores.append({"score": round(sent.____(____), 2)})
print(semantic_scores)