Twitter 航空公司情緒資料上的 TfIdf
現在你要使用 TfIdf 方法來建立特徵,並延續使用 tweets 資料集。
在這個練習中,你會運用前面課程所學,移除停用詞、使用權杖(token)樣式,並指定 n-grams。
最終輸出會是一個 DataFrame,其欄位是用 TfidfVectorizer() 產生的。這樣的 DataFrame 可以直接傳入監督式學習模型,而我們會在下一章實作這件事。
本練習屬於課程
Python 情感分析
練習說明
- 匯入建立 TfidfVectorizer 與
ENGLISH_STOP_WORDS所需的套件。 - 從
tweets資料集的text欄位建立一個 TfIdf 向量化器,指定 n-grams 為 uni- 與 bi-grams,使用提供的權杖樣式讓權杖只包含英數字元,並將停用詞設定為ENGLISH_STOP_WORDS。 - 對同一個你用來擬合的欄位進行向量化器的轉換(transform)。
- 在
DataFrame()函式中指定欄位名稱。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the required vectorizer package and stop words list
____
# Define the vectorizer and specify the arguments
my_pattern = r'\b[^\d\W][^\d\W]+\b'
vect = ____(____=(1, 2), max_features=100, ____=my_pattern, ____=ENGLISH_STOP_WORDS).fit(tweets.text)
# Transform the vectorizer
X_txt = vect.____(____.____)
# Transform to a data frame and specify the column names
X=pd.DataFrame(X_txt.toarray(), columns=____.____)
print('Top 5 rows of the DataFrame: ', X.head())