如何使用 sklearn 管道转换项目?
How to transform items using sklearn Pipeline?
我有一个简单的 scikit-learn Pipeline
,分为两个步骤:一个 TfIdfVectorizer
然后是一个 LinearSVC
。
我已经使用我的数据安装了管道。一切顺利。
现在我想转换(不是预测!)一个项目,使用我的拟合 pipeline
。
我试过 pipeline.transform([item])
,但它给出的结果与 pipeline.named_steps['tfidf'].transform([item])
不同。甚至结果的形状和类型也不同:第一个是 1x3000 CSR 矩阵,第二个是 1x15000 CSC 矩阵。哪一个是正确的?他们为什么不同?
在使用 scikit-learn 的 Pipeline
时,如何转换项目,即在最终估计器之前获取项目的矢量表示?
您不能在最后一步包含 Non-transformer 的管道上调用转换方法。
如果你不想在这样的管道上调用 transfrom 最后一个估计器必须是一个转换器。
就连transform
method doc也这么说:
Applies transforms to the data, and the transform method of the
final estimator. Valid only if the final estimator implements
transform.
此外,除了最后一个之外,没有办法使用每个估计器。
您可以创建自己的管道,并从 scikit-learn 的管道继承所有内容,但添加一个方法,例如:
def just_transforms(self, X):
"""Applies all transforms to the data, without applying last
estimator.
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step of
the pipeline.
"""
Xt = X
for name, transform in self.steps[:-1]:
Xt = transform.transform(Xt)
return Xt
结果不同(以及为什么调用 transform
甚至有效)的原因是 LinearSVC
也有一个进行特征选择的转换(现已弃用)
如果您只想通过第一步进行转换,pipeline.named_steps['tfidf'].transform([item])
是正确的选择。
如果您想使用除最后一步以外的所有步骤进行转换,olologin 的答案提供了代码。
默认情况下,管道的所有步都会被执行,最后一步的变换也会被执行,这是LinearSVC执行的特征选择。
我有一个简单的 scikit-learn Pipeline
,分为两个步骤:一个 TfIdfVectorizer
然后是一个 LinearSVC
。
我已经使用我的数据安装了管道。一切顺利。
现在我想转换(不是预测!)一个项目,使用我的拟合 pipeline
。
我试过 pipeline.transform([item])
,但它给出的结果与 pipeline.named_steps['tfidf'].transform([item])
不同。甚至结果的形状和类型也不同:第一个是 1x3000 CSR 矩阵,第二个是 1x15000 CSC 矩阵。哪一个是正确的?他们为什么不同?
在使用 scikit-learn 的 Pipeline
时,如何转换项目,即在最终估计器之前获取项目的矢量表示?
您不能在最后一步包含 Non-transformer 的管道上调用转换方法。 如果你不想在这样的管道上调用 transfrom 最后一个估计器必须是一个转换器。
就连transform
method doc也这么说:
Applies transforms to the data, and the transform method of the final estimator. Valid only if the final estimator implements transform.
此外,除了最后一个之外,没有办法使用每个估计器。 您可以创建自己的管道,并从 scikit-learn 的管道继承所有内容,但添加一个方法,例如:
def just_transforms(self, X):
"""Applies all transforms to the data, without applying last
estimator.
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step of
the pipeline.
"""
Xt = X
for name, transform in self.steps[:-1]:
Xt = transform.transform(Xt)
return Xt
结果不同(以及为什么调用 transform
甚至有效)的原因是 LinearSVC
也有一个进行特征选择的转换(现已弃用)
如果您只想通过第一步进行转换,pipeline.named_steps['tfidf'].transform([item])
是正确的选择。
如果您想使用除最后一步以外的所有步骤进行转换,olologin 的答案提供了代码。
默认情况下,管道的所有步都会被执行,最后一步的变换也会被执行,这是LinearSVC执行的特征选择。