我在处理基于文本的数据集时尝试使用词袋模型(BoW)进行机器学习。然而,我不希望训练集影响到测试集(即数据泄露)。我希望在测试集之前对训练集应用BoW。但是,这样一来,我的测试集就会有与训练集不同的特征(即单词),导致矩阵大小不一致。我尝试保留测试集中也出现在训练集中的列,但1)我的代码似乎有问题,2)我认为这不是最有效的方法。我还认为我需要添加填充列的代码?这是我目前的代码:
from sklearn.feature_extraction.text import CountVectorizerdef 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_modelX_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 CountVectorizerdef 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, cvecX_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])
这样当然会忽略训练集中未见过的单词,但这不应该成为问题,因为训练集和测试集应该或多或少有相同的分布,因此未知单词应该是罕见的。
注意:代码未经测试