【问题标题】:Error while extracting sub-pipeline using index from sklearn Pipeline使用 sklearn Pipeline 中的索引提取子管道时出错
【发布时间】:2020-08-26 19:44:12
【问题描述】:

我有一个机器学习管道 --

logreg = Pipeline([('vect', CountVectorizer(ngram_range=(1,1))),
                   ('tfidf', TfidfTransformer(sublinear_tf=True, use_idf=True)),
                   ('clf', LogisticRegression(n_jobs=-1, C=1e2, multi_class='ovr', 
                                              solver='lbfgs', max_iter=1000))])

logreg.fit(X_train, y_train)

我想从管道的前两个步骤中提取特征矩阵。因此,我尝试在原始管道中使用前两个步骤提取子管道。以下代码给出错误:

logreg[:-1].fit(X)

TypeError:“管道”对象没有属性“getitem

如何在不构建新的数据转换管道的情况下提取Pipeline 的前两个步骤?

【问题讨论】:

    标签: python python-2.7 scikit-learn pipeline


    【解决方案1】:

    我只想执行可以在运行时创建管道的部分步骤。

    partial_pipe = Pipeline(logreg.steps[:-1])
    partial_pipe.fit(data)
    

    piple 的步骤将在 Pipeline 对象的steps 变量中可用。

    【讨论】:

      【解决方案2】:

      我认为您使用的是旧版本的 sklearn。使用版本>=0.21.3,应该可以使用您所做的方式对管道进行索引。

      您可以查看发行说明here

      例子:

      from sklearn.linear_model import LogisticRegression
      from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
      from sklearn.datasets import fetch_20newsgroups
      from sklearn.pipeline import Pipeline
      from sklearn.model_selection import train_test_split
      
      categories = ['alt.atheism', 'talk.religion.misc']
      newsgroups_train = fetch_20newsgroups(subset='train',
                                            categories=categories)
      
      X, y = newsgroups_train.data, newsgroups_train.target
      
      X_train, X_test, y_train, y_test = train_test_split(
          X, y, test_size=0.3, stratify=y)
      
      
      logreg = Pipeline([('vect', CountVectorizer(ngram_range=(1, 1))),
                         ('tfidf', TfidfTransformer(sublinear_tf=True, use_idf=True)),
                         ('clf', LogisticRegression(n_jobs=-1, C=1e2,
                                                    multi_class='ovr',
                                                    solver='lbfgs', max_iter=1000))])
      logreg.fit(X_train, y_train)
      
      
      logreg[:-1].fit_transform(X_train)
      
      # <599x15479 sparse matrix of type '<class 'numpy.float64'>'
      #   with 107539 stored elements in Compressed Sparse Row format>
      
      

      【讨论】:

        猜你喜欢
        • 2019-11-06
        • 1970-01-01
        • 2017-12-23
        • 2020-01-28
        • 2014-11-07
        • 2017-12-20
        • 2017-08-01
        • 2019-10-28
        • 2021-06-23
        相关资源
        最近更新 更多