首页 > 解决方案 > 使用管道和网格搜索执行特征选择

问题描述

作为研究项目的一部分,我想选择预处理技术和文本特征的最佳组合,以优化文本分类任务的结果。为此,我使用的是 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, ...)
 }

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

标签: pythonscikit-learnpipelinefeature-selectiongrid-search

解决方案



推荐阅读