【问题标题】:Get features from sklearn feature union从 sklearn 特征联合中获取特征
【发布时间】:2018-06-08 21:47:22
【问题描述】:

我有一个功能联合,它使用一些自定义转换器来选择文本和部分数据框。我想了解它使用了哪些功能。

管道选择并转换列,然后选择 k 最佳。我可以使用以下代码从 k best 中提取功能:

mask = union.named_steps['select_features'].get_support()

但是我无法将此掩码应用于功能联合输出,因为我正在努力返回最终转换。我想我需要在自定义转换器中定义一个“get_feature_names”函数 - see related post

管道如下:

union = Pipeline([
('feature_union', FeatureUnion([

    ('pipeline_1', Pipeline([
        ('selector', TextSelector(key='notes_1')),
        ('vectorise', CountVectorizer())
    ])),

    ('pipeline_2', Pipeline([
        ('selector', TextSelector(key='notes_2')),
        ('vectorise', CountVectorizer())
    ])),

    ('pipeline_3', Pipeline([
        ('selector', TextSelector(key='notes_3')),
        ('vectorise', CountVectorizer())
    ])),

    ('pipeline_4', Pipeline([
        ('selector', TextSelector(key='notes_4')),
        ('vectorise', CountVectorizer())
    ])),

    ('tf-idf_pipeline', Pipeline([
        ('selector', TextSelector(key='notes_5')),
        ('Tf-idf', TfidfVectorizer())
    ])),

    ('categorical_pipeline', Pipeline([
        ('selector', DataFrameSelector(['area', 'type', 'age'], True)),
        ('one_hot_encoding', OneHotEncoder(handle_unknown='ignore'))
    ]))
], n_jobs=-1)),
('select_features', SelectKBest(k='all')),
('classifier', MLPClassifier())
])

自定义转换器如下注意我已经尝试在每个转换器中包含一个'get_feature_names'函数,但它不能正常工作:

class TextSelector(BaseEstimator, TransformerMixin):
   def __init__(self, key):
       self.key = key

   def fit(self, X, y=None):
       return self

   def transform(self, X):
       return X[self.key]

   def get_feature_names(self):
       return X[self.key].columns.tolist()


class DataFrameSelector(BaseEstimator, TransformerMixin):
   def __init__(self, attribute_names, factorize=False):
    self.attribute_names = attribute_names
    self.factorize = factorize

   def transform(self, X):
    selection = X[self.attribute_names]
    if self.factorize:
        selection = selection.apply(lambda p: pd.factorize(p)[0] + 1)
       return selection.values

   def fit(self, X, y=None):
       return self

   def get_feature_names(self):
       return X.columns.tolist()

感谢您的帮助。

【问题讨论】:

  • 从您链接的帖子中,还提到了对 Pipeline 进行子类化并添加 get_feature_names()。你也试过了吗?

标签: python-3.x scikit-learn


【解决方案1】:

到目前为止,获得嵌套功能的最佳方式(感谢 edesz):

pipeline = Pipeline(steps=[
     ("union", FeatureUnion(
      transformer_list=[
        ("descriptor", Pipeline(steps=[
            ("selector", ItemSelector(column="Description")),
            ("tfidf", TfidfVectorizer(min_df=5, analyzer=u'word'))
        ]))
    ],...

pvect= dict(pipeline.named_steps['union'].transformer_list).get('descriptor').named_steps['tfidf']

然后你让 TfidfVectorizer() 实例传入另一个函数:

Show_most_informative_features(pvect,
           pipeline.named_steps['classifier'], n=MostIF)

【讨论】:

    【解决方案2】:

    如果您知道步骤的名称(例如pipeline_1)和调用自定义转换器的子步骤的名称(例如vectorise),那么您可以直接参考这些步骤和子步骤名字

    fnames = dict(union.named_steps['feature_union']
                .transformer_list)
                .get('pipeline_1')
                .named_steps['vectorise']
                .get_feature_names()
    

    Source used

    【讨论】:

      【解决方案3】:

      这个对我有用。就像建议的那样

      union = Pipeline([
      ('feature_union', FeatureUnion([
      
      ('pipeline_1', MyPipeline([
          ('selector', TextSelector(key='notes_1')),
          ('vectorise', CountVectorizer())
      ])),
      ])
      
      class myPipeline(Pipeline):
          def get_feature_names(self):
              for name, step in self.steps:
                  if isinstance(step,TfidfVectorizer):
                      return step.get_feature_names()
      

      【讨论】:

        猜你喜欢
        • 2018-12-25
        • 2016-10-11
        • 1970-01-01
        • 2017-04-30
        • 2015-11-01
        • 1970-01-01
        • 2018-02-12
        • 2014-09-20
        • 2018-05-24
        相关资源
        最近更新 更多