開始使用免費開始

你的第一個 BOW

Bag-of-words(詞袋模型)是一種把文字轉成數值形式的方法。

在這個練習中,你會先對清單 annak 套用 BOW,下一題再前往較大的資料集。

你的任務是用這個清單,搭配 CountVectorizer() 建立一個 BOW。這個轉換是理解文字情感的第一步。請留意可能帶有強烈情感的詞彙。

請記得,CountVectorizer() 的輸出是稀疏矩陣,只儲存非零的項目。若要檢視矩陣的實際內容,可以使用 .toarray() 方法把它轉成稠密陣列。

另外,這裡不需要指定 max_features 引數,因為文字很短。

本練習屬於課程

Python 情感分析

檢視課程

練習說明

  • sklearn.feature_extraction.text 匯入 count vectorizer 函式。
  • 在這個小型資料集上建構並擬合(fit)向量化器。
  • 呼叫 transform() 方法,建立名為 anna_bow 的 BOW 表示。
  • 以稠密陣列的形式列印 BOW 結果。

動手互動練習

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

# Import the required function
____

annak = ['Happy families are all alike;', 'every unhappy family is unhappy in its own way']

# Build the vectorizer and fit it
anna_vect = ____
____.____(annak)

# Create the bow representation
anna_bow = anna_vect.____(annak)

# Print the bag-of-words result 
print(anna_bow.toarray())
編輯並執行程式碼