比较 n-gram 模型的性能
您现在已经知道如何通过将文本转换为不同的 n-gram 表示并将其输入分类器来进行情感分析。在本练习中,我们将对同一组电影评论使用两种 n-gram 模型进行情感分析:仅使用 unigram,以及 n 最多为 3 的 n-gram。
随后,我们将从三个方面比较性能:模型在测试集上的准确率、程序的执行时间,以及在生成 n-gram 表示时创建的特征数量。
本练习是课程的一部分
Python 中的 NLP 特征工程
交互式实操练习
通过完成这段示例代码来试试这个练习。
start_time = time.time()
# Splitting the data into training and test sets
train_X, test_X, train_y, test_y = train_test_split(df['review'], df['sentiment'], test_size=0.5, random_state=42, stratify=df['sentiment'])
# Generating ngrams
vectorizer = ___
train_X = vectorizer.fit_transform(train_X)
test_X = vectorizer.transform(test_X)
# Fit classifier
clf = MultinomialNB()
clf.fit(train_X, train_y)
# Print accuracy, time and number of dimensions
print("The program took %.3f seconds to complete. The accuracy on the test set is %.2f. The ngram representation had %i features." % (time.time() - start_time, clf.score(test_X, test_y), train_X.shape[1]))