nグラムの機能を使用してsklearn
クラシファイアを使用したいと考えています。さらに、n-gramの最良の順序を見つけるためにクロスバリデーションを行いたい。しかし、私はどのように私は一緒にすべての部分を合わせることができますに固執しています。今のnグラムによる分類
、私は次のコードを持っている:私はすべてのループ内での列車試験スプリットを作成するので、これは、それを行うには間違った方法であるように
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
text = ... # This is the input text. A list of strings
labels = ... # These are the labels of each sentence
# Find the optimal order of the ngrams by cross-validation
scores = pd.Series(index=range(1,6), dtype=float)
folds = KFold(n_splits=3)
for n in range(1,6):
count_vect = CountVectorizer(ngram_range=(n,n), stop_words='english')
X = count_vect.fit_transform(text)
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.33, random_state=42)
clf = MultinomialNB()
score = cross_val_score(clf, X_train, y_train, cv=folds, n_jobs=-1)
scores.loc[n] = np.mean(score)
# Evaluate the classifier using the best order found
order = scores.idxmax()
count_vect = CountVectorizer(ngram_range=(order,order), stop_words='english')
X = count_vect.fit_transform(text)
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.33, random_state=42)
clf = MultinomialNB()
clf = clf.fit(X_train, y_train)
acc = clf.score(X_test, y_test)
print('Accuracy is {}'.format(acc))
をしかし、私は感じています。
事前に列車テスト分割を行うとclf.fit
とclf.score
を使用する際に問題が発生しており、これらの部品が異なるshape
秒を持っているよりも、個別の両方の部分にCountVectorizer
を適用した場合。
どうすればこの問題を解決できますか?
EDIT:私は最初の語彙を構築しようとした場合ユニグラムのための語彙がバイグラムとは異なっていることから、私はまだ、いくつかの語彙を構築する必要など
例を与える:
# unigram vocab
vocab = set()
for sentence in text:
for word in sentence:
if word not in vocab:
vocab.add(word)
len(vocab) # 47291
# bigram vocab
vocab = set()
for sentence in text:
bigrams = nltk.ngrams(sentence, 2)
for bigram in bigrams:
if bigram not in vocab:
vocab.add(bigram)
len(vocab) # 326044
これもまた、nグラムサイズごとにCountVectorizer
を適用する必要がある同じ問題につながります。
トレーニングセットからボキャブラリを作成します。同じ辞書に単語とバイグラム(とそれ以上)の両方を置くことはできません。 – alexis