Skip to main content
 首页 » 编程设计

python之使用管道和网格搜索执行特征选择

2024年12月31日8小虾米

作为研究项目的一部分,我想选择预处理技术和文本特征的最佳组合,以优化文本分类任务的结果。为此,我使用 Python 3.6。

有很多方法可以组合特征和算法,但我想充分利用 sklearn 的管道并使用网格搜索测试所有不同(有效)的可能性以获得最终的特征组合。

我的第一步是构建如下所示的管道:

# Run a vectorizer with a predefined tweet tokenizer and a Naive Bayes 
 
pipeline = Pipeline([ 
    ('vectorizer', CountVectorizer(tokenizer = tweet_tokenizer)), 
    ('nb', MultinomialNB()) 
]) 
 
parameters = { 
'vectorizer__preprocessor': (None, preprocessor) 
} 
 
gs =  GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) 

在这个简单的示例中,矢量化器使用 tweet_tokenizer 对数据进行标记化,然后测试哪个预处理选项(无或预定义函数)结果更好。

这似乎是一个不错的开始,但我现在正在努力寻找一种方法来测试预处理器函数中的所有不同可能性,定义如下:

def preprocessor(tweet): 
    # Data cleaning 
    tweet = URL_remover(tweet) # Removing URLs 
    tweet = mentions_remover(tweet) # Removing mentions 
    tweet = email_remover(tweet) # Removing emails 
    tweet = irrelev_chars_remover(tweet) # Removing invalid chars 
    tweet = emojies_converter(tweet) # Translating emojies 
    tweet = to_lowercase(tweet) # Converting words to lowercase 
    # Others 
    tweet = hashtag_decomposer(tweet) # Hashtag decomposition 
    # Punctuation may only be removed after hashtag decomposition   
    # because it considers "#" as punctuation 
    tweet = punct_remover(tweet) # Punctuation  
    return tweet 

组合所有不同处理技术的“简单”解决方案是为每种可能性创建不同的函数(例如 funcA: proc1、funcB: proc1 + proc2、funcC: proc1 + proc3 等)并设置网格参数如下:

parameters = { 
   'vectorizer__preprocessor': (None, funcA, funcB, funcC, ...) 
} 

虽然这很可能会奏效,但对于这项任务来说,这不是一个可行或合理的解决方案,尤其是因为有 2^n_features 不同的组合,因此还有功能。

最终目标是在管道中结合预处理技术和功能,以便使用网格搜索优化分类结果:

pipeline = Pipeline([ 
    ('vectorizer', CountVectorizer(tokenizer = tweet_tokenizer)), 
    ('feat_extractor' , feat_extractor) 
    ('nb', MultinomialNB()) 
]) 
 
 parameters = { 
   'vectorizer__preprocessor': (None, funcA, funcB, funcC, ...) 
   'feat_extractor': (None, func_A, func_B, func_C, ...) 
 } 

有没有更简单的方法来获取这个?

请您参考如下方法:

根据您的描述,此解决方案非常粗略,并且根据所使用的数据类型提供特定的答案。在制作管道之前,让我们了解一下 CountVectorizer在 raw_documents 上工作在其中传递的。本质上,this is the line将字符串文档处理成标记,

return lambda doc: self._word_ngrams(tokenize(preprocess(self.decode(doc))), stop_words) 

然后对它们进行计数并转换为计数矩阵。

所以这里发生的是:

  1. decode : 只需决定如何从文件中读取数据(如果指定)。对我们没有用,我们已经将数据放入列表中。
  2. preprocess :如果 'strip_accents',它会执行以下操作和 'lowercase'是True在 CountVectorizer .别的什么都没有

    strip_accents(x.lower()) 
    

    同样,没有用,因为我们正在将小写功能移至我们自己的预处理器并且不需要去除重音符号,因为我们已经在字符串列表中有数据。

  3. tokenize : 将删除所有标点符号并仅保留长度为 2 或更长的字母数字单词,并返回单个文档的标记列表(列表的元素)

    lambda doc: token_pattern.findall(doc) 
    

    这一点应该牢记。如果您想自己处理标点符号和其他符号(决定保留一些并删除其他符号),那么最好也更改默认值 token_pattern=’(?u)\b\w\w+\b’的 CountVectorizer .

    1. _word_ngrams :此方法将首先从上一步的标记列表中删除停用词(作为上面的参数提供),然后计算由 ngram_range 定义的 n_grams参数 CountVectorizer .如果你想处理 "n_grams",也应该记住这一点。你的方式。

注意:如果分析器设置为'char' , 然后是 tokenizer step 将不会执行,n_grams 将由字符组成。

现在进入我们的管道。这是我认为可以在这里工作的结构:

X --> combined_pipeline, Pipeline 
            | 
            |  Raw data is passed to Preprocessor 
            | 
            \/ 
         Preprocessor  
                 | 
                 |  Cleaned data (still raw texts) is passed to FeatureUnion 
                 | 
                 \/ 
              FeatureUnion 
                      | 
                      |  Data is duplicated and passed to both parts 
       _______________|__________________ 
      |                                  | 
      |                                  |                          
      \/                                \/ 
   CountVectorizer                  FeatureExtractor 
           |                                  |    
           |   Converts raw to                |   Extracts numerical features 
           |   count-matrix                   |   from raw data 
           \/________________________________\/ 
                             | 
                             | FeatureUnion combines both the matrices 
                             | 
                             \/ 
                          Classifier 

现在开始写代码。这是管道的样子:

# Imports 
from sklearn.svm import SVC 
from sklearn.pipeline import FeatureUnion, Pipeline 
 
# Pipeline 
pipe = Pipeline([('preprocessor', CustomPreprocessor()),  
                 ('features', FeatureUnion([("vectorizer", CountVectorizer()), 
                                            ("extractor", CustomFeatureExtractor()) 
                                            ])) 
                 ('classifier', SVC()) 
                ]) 

在哪里CustomPreprocessor和 CustomFeatureExtractor定义为:

from sklearn.base import TransformerMixin, BaseEstimator 
 
class CustomPreprocessor(BaseEstimator, TransformerMixin): 
    def __init__(self, remove_urls=True, remove_mentions=True,  
                 remove_emails=True, remove_invalid_chars=True,  
                 convert_emojis=True, lowercase=True,  
                 decompose_hashtags=True, remove_punctuations=True): 
        self.remove_urls=remove_urls 
        self.remove_mentions=remove_mentions 
        self.remove_emails=remove_emails 
        self.remove_invalid_chars=remove_invalid_chars 
        self.convert_emojis=convert_emojis 
        self.lowercase=lowercase 
        self.decompose_hashtags=decompose_hashtags 
        self.remove_punctuations=remove_punctuations 
 
    # You Need to have all the functions ready 
    # This method works on single tweets 
    def preprocessor(self, tweet): 
        # Data cleaning 
        if self.remove_urls: 
            tweet = URL_remover(tweet) # Removing URLs 
 
        if self.remove_mentions: 
            tweet = mentions_remover(tweet) # Removing mentions 
 
        if self.remove_emails: 
            tweet = email_remover(tweet) # Removing emails 
 
        if self.remove_invalid_chars: 
            tweet = irrelev_chars_remover(tweet) # Removing invalid chars 
 
        if self.convert_emojis: 
            tweet = emojies_converter(tweet) # Translating emojies 
 
        if self.lowercase: 
            tweet = to_lowercase(tweet) # Converting words to lowercase 
 
        if self.decompose_hashtags: 
            # Others 
            tweet = hashtag_decomposer(tweet) # Hashtag decomposition 
 
        # Punctuation may only be removed after hashtag decomposition   
        # because it considers "#" as punctuation 
        if self.remove_punctuations: 
            tweet = punct_remover(tweet) # Punctuation  
 
        return tweet 
 
    def fit(self, raw_docs, y=None): 
        # Noop - We dont learn anything about the data 
        return self 
 
    def transform(self, raw_docs): 
        return [self.preprocessor(tweet) for tweet in raw_docs] 
 
from textblob import TextBlob 
import numpy as np 
# Same thing for feature extraction 
class CustomFeatureExtractor(BaseEstimator, TransformerMixin): 
    def __init__(self, sentiment_analysis=True, tweet_length=True): 
        self.sentiment_analysis=sentiment_analysis 
        self.tweet_length=tweet_length 
 
    # This method works on single tweets 
    def extractor(self, tweet): 
        features = [] 
 
        if self.sentiment_analysis: 
            blob = TextBlob(tweet) 
            features.append(blob.sentiment.polarity) 
 
        if self.tweet_length: 
            features.append(len(tweet)) 
 
        # Do for other features you want. 
 
        return np.array(features) 
 
    def fit(self, raw_docs, y): 
        # Noop - Again I am assuming that We dont learn anything about the data 
        # Definitely not for tweet length, and also not for sentiment analysis 
        # Or any other thing you might have here. 
        return self 
 
    def transform(self, raw_docs): 
        # I am returning a numpy array so that the FeatureUnion can handle that correctly 
        return np.vstack(tuple([self.extractor(tweet) for tweet in raw_docs])) 

最后,参数网格现在可以像这样轻松完成:

param_grid = ['preprocessor__remove_urls':[True, False], 
              'preprocessor__remove_mentions':[True, False], 
              ... 
              ... 
              # No need to search for lowercase or preprocessor in CountVectorizer  
              'features__vectorizer__max_df':[0.1, 0.2, 0.3], 
              ... 
              ... 
              'features__extractor__sentiment_analysis':[True, False], 
              'features__extractor__tweet_length':[True, False], 
              ... 
              ... 
              'classifier__C':[0.01, 0.1, 1.0] 
            ] 

以上代码是为了避免“to create a different function for each possibility (e.g. funcA: proc1, funcB: proc1 + proc2, funcC: proc1 + proc3, etc.)”。只需执行 True、False 和 GridSearchCV 即可处理。

更新: 如果你不想拥有 CountVectorizer ,然后您可以从管道和参数网格中删除它,新管道将是:

pipe = Pipeline([('preprocessor', CustomPreprocessor()),  
                 ("extractor", CustomFeatureExtractor()), 
                 ('classifier', SVC()) 
                ]) 

然后确保在 CustomFeatureExtractor 中实现您想要的所有功能.如果这变得太复杂,那么您总是可以制作更简单的提取器并将它们组合在 FeatureUnion 中而不是 CountVectorizer。