我正在尝试在基于文本的数据集上使用 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])