開始使用免費開始

探索文字向量,第 2 部分

使用你在上一個練習中撰寫的 return_weights() 函式,從文字向量中的每個文件擷取權重最高的單字,回傳單字索引的清單,並用該清單將文字向量篩選為只保留這些高權重單字。

本練習屬於課程

Python 的 Machine Learning 前處理

檢視課程

練習說明

  • 呼叫 return_weights(),回傳該文件中權重最高的單字。
  • 對回傳的 filter_list 呼叫 set(),以移除重複的數字。
  • 呼叫 words_to_filter,並傳入以下參數:vocab 作為 vocab 參數、tfidf_vec.vocabulary_ 作為 original_vocab 參數、text_tfidf 作為 vector 參數,以及 3 以自每個文件擷取 top_n 的 3 個高權重單字。
  • 最後,將這個 filtered_words 集合轉成清單,作為篩選文字向量的條件。

動手互動練習

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

def words_to_filter(vocab, original_vocab, vector, top_n):
    filter_list = []
    for i in range(0, vector.shape[0]):
    
        # Call the return_weights function and extend filter_list
        filtered = ____(vocab, original_vocab, vector, i, top_n)
        filter_list.extend(filtered)
        
    # Return the list in a set, so we don't get duplicate word indices
    return ____(filter_list)

# Call the function to get the list of word indices
filtered_words = ____(____, ____, ____, ____)

# Filter the columns in text_tfidf to only those in filtered_words
filtered_text = text_tfidf[:, list(____)]
編輯並執行程式碼