用更高階的 n-gram 做情緒分析
和先前的練習類似,我們要建立一個分類器,判斷某部電影的評論是正面還是負面。不過這次,我們會使用 n-gram,最高到 n=2。
n-gram 的訓練評論已提供為 X_train_ng。對應的測試評論為 X_test_ng。最後,分別使用 y_train 和 y_test 取得訓練與測試的情緒類別。
本練習屬於課程
Python 中文本特徵工程
練習說明
- 建立一個 MultinomialNB 的實例,命名為
clf_ng。 - 以
X_train_ng和y_train來訓練分類器。 - 使用
score()方法,在X_test_ng與y_test上量測accuracy。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define an instance of MultinomialNB
clf_ng = ____
# Fit the classifier
clf_ng.____(____, ____)
# Measure the accuracy
accuracy = ____
print("The accuracy of the classifier on the test set is %.3f" % accuracy)
# Predict the sentiment of a negative review
review = "The movie was not good. The plot had several holes and the acting lacked panache."
prediction = clf_ng.predict(ng_vectorizer.transform([review]))[0]
print("The sentiment predicted by the classifier is %i" % (prediction))