使用 tf/idf 向量進行文字分類
現在你已經把 volunteer 資料集的 title 欄位編碼成 tf/idf 向量,接下來要用這些向量來預測 category_desc 欄位。
本練習屬於課程
Python 的 Machine Learning 前處理
練習說明
- 將
text_tfidf向量與目標變數y切分為訓練集與測試集,並將stratify參數設為y,因為各類別的分布不平均。請注意,我們必須對 tf/idf 向量呼叫.toarray()方法,才能取得 scikit-learn 需要的正確格式。 - 將
X_train與y_train擬合到 Naive Bayes 模型nb。 - 列印測試集的準確率。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Split the dataset according to the class distribution of category_desc
y = volunteer["category_desc"]
X_train, X_test, y_train, y_test = ____(____.toarray(), ____, ____=____, random_state=42)
# Fit the model to the training data
nb.____(____, ____)
# Print out the model's accuracy
print(nb.____(____, ____))