開始使用免費開始

使用 tf/idf 向量進行文字分類

現在你已經把 volunteer 資料集的 title 欄位編碼成 tf/idf 向量,接下來要用這些向量來預測 category_desc 欄位。

本練習屬於課程

Python 的 Machine Learning 前處理

檢視課程

練習說明

  • text_tfidf 向量與目標變數 y 切分為訓練集與測試集,並將 stratify 參數設為 y,因為各類別的分布不平均。請注意,我們必須對 tf/idf 向量呼叫 .toarray() 方法,才能取得 scikit-learn 需要的正確格式。
  • X_trainy_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.____(____, ____))
編輯並執行程式碼