开始使用免费开始使用

预测电影评论的情感

在上一个练习中,您已经为训练集和测试集的电影评论生成了词袋表示。在本练习中,我们将用该表示来训练一个朴素贝叶斯分类器,用于识别电影评论的情感,并计算其准确率。请注意,这是一个二分类问题,模型只能将评论判为正面 (1) 或负面 (0),无法识别中性评论。

如果您需要回顾,训练集和测试集的 BoW 向量分别保存在 X_train_bowX_test_bow 中。对应的标签分别为 y_trainy_test。此外,供您参考,原始电影评论数据集保存在 df 中。

本练习是课程的一部分

Python 中的 NLP 特征工程

查看课程

练习说明

  • 实例化一个 MultinomialNB 对象,命名为 clf
  • 使用 X_train_bowy_train 拟合 clf
  • 使用 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))
编辑并运行代码