0

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

4

1 回答 1

1

您通常只会在训练集上安装 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])

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

注意:代码未经测试

于 2021-05-12T14:03:16.403 回答