比較 n-gram 模型的效能
你現在已經知道如何把文字轉換成各種 n-gram 表示,並餵給分類器來做情感分析。這個練習中,我們會對同一批電影評論分別使用兩種 n-gram 模型進行情感分析:只用 unigram,以及 n 最多到 3 的 n-gram。
接著我們會用三個指標比較效能:模型在測試集上的準確率、程式執行所花的時間,以及在產生 n-gram 表示時建立的特徵數量。
本練習屬於課程
Python 中文本特徵工程
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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]))