如何使用sklearn管道转换项?

2024-06-16 11:47:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的scikit学习Pipeline,包括两个步骤:aTfIdfVectorizer,然后是LinearSVC。在

我用我的数据拟合了管道。一切都好。在

现在我要转变(不是预测!)一个项目,使用我的fittedpipeline。在

我尝试了pipeline.transform([item]),但它给出的结果与pipeline.named_steps['tfidf'].transform([item])不同。甚至结果的形状和类型也不同:第一个是1x3000个CSR矩阵,第二个是1x15000个CSC矩阵。哪一个是正确的?它们为什么不同?在

当使用scikit learn的Pipeline时,如何转换项,即在最终估计器之前获得项目的向量表示?在


Tags: 数据项目管道pipeline步骤transform矩阵scikit
2条回答

结果不同的原因(以及为什么调用transformeven workds)是因为LinearSVC也有一个转换(现在已弃用)来进行特征选择

如果只想使用第一步进行转换,pipeline.named_steps['tfidf'].transform([item])是正确的做法。 如果您想使用除最后一步以外的所有步骤进行转换,olologin的答案提供了代码。在

默认情况下,执行管道的所有步骤,最后一步的转换也是如此,即LinearSVC执行的特征选择。在

在最后一步中,不能对包含非转换器的管道调用转换方法。 如果您不想在这样的管道上调用transfrom,最后一个估计器必须是一个转换器。在

即使是方法医生也这么说:

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

相关问题 更多 >