開始使用免費開始

電影叢集中的熱門關鍵詞

現在你已經建立了稀疏矩陣,請產生叢集中心,並印出每個叢集中排名前 3 的關鍵詞。使用 .todense() 方法把稀疏矩陣 tfidf_matrix 轉成一般矩陣,讓 kmeans() 函式可以處理。接著,使用 .get_feature_names() 方法,從 tfidf_vectorizer 物件取得詞彙列表。Python 中的 zip() 函式可以把兩個列表配對在一起。

先前產生的 tfidf_vectorizer 物件與稀疏矩陣 tfidf_matrix 已在本練習中保留可用。kmeans 已從 SciPy 匯入。

如果資料點數量更多,形成的叢集會更清楚。不過這需要較多運算資源,在這裡的練習中較難完成。

本練習屬於課程

Python 中的叢集分析

檢視課程

練習說明

  • 使用 kmeans() 函式產生叢集中心。
  • tfidf_vectorizer 物件產生詞彙列表。
  • 印出每個叢集的前 3 個關鍵詞。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

num_clusters = 2

# Generate cluster centers through the kmeans function
cluster_centers, distortion = ____

# Generate terms from the tfidf_vectorizer object
terms = tfidf_vectorizer.____()

for i in range(num_clusters):
    # Sort the terms and print top 3 terms
    center_terms = dict(zip(____, ____))
    sorted_terms = sorted(____, key=center_terms.get, reverse=True)
    print(____)
編輯並執行程式碼