[英]How to handle out of vocab words with bag of words
我正在嘗試在基於文本的數據集上使用 ML 之前的 BoW。 但是,我不希望我的訓練集影響我的測試集(即數據泄漏)。 我想在測試集之前在訓練集上部署 BoW。 但是,我的測試集與我的訓練集具有不同的特征(即單詞),因此矩陣的大小不同。 我嘗試在測試集中保留也出現在訓練集中的列,但是 1)我的代碼不正確,2)我認為這不是最有效的過程。 我想我還需要代碼來添加填充列? 這是我所擁有的:
from sklearn.feature_extraction.text import CountVectorizer
def bow (tokens, data):
tokens = tokens.apply(nltk.word_tokenize)
cvec = CountVectorizer(min_df = .01, max_df = .99, ngram_range=(1,2), tokenizer=lambda doc:doc, lowercase=False)
cvec.fit(tokens)
cvec_counts = cvec.transform(tokens)
cvec_counts_bow = cvec_counts.toarray()
vocab = cvec.get_feature_names()
bow_model = pd.DataFrame(cvec_counts_bow, columns=vocab)
return bow_model
X_train = bow(train['text'], train)
X_test = bow(test['text'], test)
vocab = list(X_train.columns)
X_test = test.filter.columns([w for w in X_test if w in vocab])
您通常只會在訓練集上安裝 CountVectorizer 並在測試集上使用相同的 Vectorizer,例如:
from sklearn.feature_extraction.text import CountVectorizer
def bow (tokens, data, cvec=None):
tokens = tokens.apply(nltk.word_tokenize)
if cvec==None:
cvec = CountVectorizer(min_df = .01, max_df = .99, ngram_range=(1,2), tokenizer=lambda doc:doc, lowercase=False)
cvec.fit(tokens)
cvec_counts = cvec.transform(tokens)
cvec_counts_bow = cvec_counts.toarray()
vocab = cvec.get_feature_names()
bow_model = pd.DataFrame(cvec_counts_bow, columns=vocab)
return bow_model, cvec
X_train, cvec = bow(train['text'], train)
X_test, cvec = bow(test['text'], test, cvec=cvec)
vocab = list(X_train.columns)
X_test = test.filter.columns([w for w in X_test if w in vocab])
這當然會忽略在訓練集上沒有看到的單詞,但這應該不是問題,因為訓練和測試應該具有或多或少相同的分布,因此未知單詞應該很少見。
注意:代碼未經測試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.