開始使用免費開始

探索文字向量(第 1 部分)

讓我們延伸剛學到的文字向量探索方法,使用 volunteer 資料集的 title tf/idf 向量。在這個文字向量探索的第一部分,我們要擴充投影片裡介紹的那個函式。這次會讓函式回傳一串數字清單。下一個練習中,我們會再寫一個函式,彙整所有文件的高權重字詞、擷取它們,然後用該清單來篩選 text_tfidf 向量。

本練習屬於課程

Python 的 Machine Learning 前處理

檢視課程

練習說明

  • 新增參數 original_vocab(對應 tfidf_vec.vocabulary_)與 top_n
  • 對壓成配對後的字典呼叫 pd.Series()。這會讓後續操作更容易。
  • 使用 .sort_values() 來排序該 Series,並將索引切片到前 top_n 個單字。
  • 呼叫該函式,將 original_vocab=tfidf_vec.vocabulary_,設定 vector_index=8 以取得第 9 列,並將 top_n=3 以取得權重最高的前 3 個單字。

動手互動練習

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

# Add in the rest of the arguments
def return_weights(vocab, ____, vector, vector_index, ____):
    zipped = dict(zip(vector[vector_index].indices, vector[vector_index].data))
    
    # Transform that zipped dict into a series
    zipped_series = ____({vocab[i]:zipped[i] for i in vector[vector_index].indices})
    
    # Sort the series to pull out the top n weighted words
    zipped_index = zipped_series.____(ascending=False)[:____].index
    return [original_vocab[i] for i in zipped_index]

# Print out the weighted words
print(return_weights(vocab, ____, text_tfidf, ____, ____))
編輯並執行程式碼