始める無料で始める

n-gramモデルの性能を比較する

テキストをさまざまなn-gram表現に変換して分類器に入力し、感情分析を行う方法を学びました。この演習では、前と同じ映画レビューに対して、2つのn-gramモデル(ユニグラムと、n=3までのn-gram)を使って感情分析を行います。

その後、3つの基準で性能を比較します。テストセットでの正解率、プログラムの実行時間、そして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]))
コードを編集して実行