scikit学习:学习曲线没有信息泄漏?

时间:2019-12-18 17:33:55

标签: scikit-learn

我想为使用countVectorizer提取特征的LinearSVC估计器生成学习曲线。 countVectorizer还应用了一些功能选择步骤。

我可以执行以下操作:

  1. 使矢量化器适合所有数据,包括选择前N个特征

  2. 使用这些功能来拟合linearSVC

  3. 在sklearn.model_selection.learning_curve()中将linearSVC用作估计量

但是我认为这将导致信息泄漏:基于所有数据的信息将用于为学习曲线中使用的较小集合选择特征。

这是正确的吗? 有没有办法将内置的sklearn.model_selection.learning_curve()与countVectorizer一起使用而不会发生信息泄漏?

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要将管道与learning_curve结合使用。 训练时,管道将调用变压器的fit_transform,而测试时,管道将仅调用transformlearning_curve还将应用可由参数cv控制的交叉验证。

使用此管道,不会泄漏任何信息。这是在scikit-learn中使用集成玩具库的示例。

from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import learning_curve


categories = [
    'alt.atheism',
    'talk.religion.misc',
]
# Uncomment the following to do the analysis on all the categories
#categories = None

data = fetch_20newsgroups(subset='train', categories=categories)

pipeline = make_pipeline(
    CountVectorizer(), TfidfTransformer(), LinearSVC()
)

learning_curve(pipeline, data.data, data.target, cv=5)