開始使用免費開始

預測電影評論的情感極性

在上一個練習中,你已經為訓練與測試的電影評論資料產生了 bag-of-words 表示。這個練習中,我們會用這個模型來訓練一個 Naive Bayes 分類器,用於偵測電影評論的情感極性,並計算其準確率。請注意,因為這是二元分類問題,模型只能將評論分類為正面(1)或負面(0),無法偵測中立評論。

如果你不太記得,訓練與測試的 BoW 向量分別儲存在 X_train_bowX_test_bow。對應的標籤分別為 y_trainy_test。此外,供你參考,原始的電影評論資料集為 df

本練習屬於課程

Python 中文本特徵工程

檢視課程

練習說明

  • 建立一個 MultinomialNB 的物件,命名為 clf
  • 使用 X_train_bowy_trainclf 進行訓練(fit)。
  • 使用 X_test_bowy_test 來評估 clf 的準確率。

動手互動練習

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

# Create a MultinomialNB object
clf = ____

# Fit the classifier
clf.____(____, ____)

# Measure the accuracy
accuracy = clf.score(____, ____)
print("The accuracy of the classifier on the test set is %.3f" % accuracy)

# Predict the sentiment of a negative review
review = "The movie was terrible. The music was underwhelming and the acting mediocre."
prediction = clf.predict(vectorizer.transform([review]))[0]
print("The sentiment predicted by the classifier is %i" % (prediction))
編輯並執行程式碼