語料庫的餘弦相似度矩陣
在本練習中,給你一個 corpus,它是包含 5 句話的清單。corpus 已在主控台列印。你需要計算餘弦相似度矩陣,其中包含每一對句子的成對餘弦相似度分數(使用 tf-idf 向量化)。
請記得,相似度矩陣中第 i 列與第 j 欄對應的值,表示第 i 與第 j 向量的相似度分數。
本練習屬於課程
Python 中文本特徵工程
練習說明
- 建立一個
TfidfVectorizer的實例,命名為tfidf_vectorizer。 - 使用
fit_transform()為corpus產生 tf-idf 向量,命名為tfidf_matrix。 - 使用
cosine_similarity(),傳入tfidf_matrix以計算餘弦相似度矩陣cosine_sim。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize an instance of tf-idf Vectorizer
tfidf_vectorizer = ____
# Generate the tf-idf vectors for the corpus
tfidf_matrix = tfidf_vectorizer.fit_transform(____)
# Compute and print the cosine similarity matrix
cosine_sim = ____(____, tfidf_matrix)
print(cosine_sim)