如何用词袋处理词汇外的单词

How to handle out of vocab words with bag of words

我正在尝试在基于文本的数据集上使用 BoW before ML。但是,我不希望我的训练集影响我的测试集(即数据泄漏)。我想在测试集之前在训练集上部署 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])

这当然会忽略在训练集上看不到的词,但这应该不是问题,因为训练和测试应该或多或少具有相同的分布,因此未知词应该很少见。

注:代码未测试