python - 使用管道和网格搜索执行特征选择
问题描述
作为研究项目的一部分,我想选择预处理技术和文本特征的最佳组合,以优化文本分类任务的结果。为此,我使用的是 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, ...)
}
有没有更简单的方法来获得这个?
解决方案
推荐阅读
- c - 3 维 malloc 数组的分段错误
- javascript - 使用变量从 JSON 文件中获取数据 (JS/Discord.js)
- ios - 无法在 Swift 4 中将 UILabel 添加到 UIView
- c# - 如何将此 svg 路径转换为圆环图中的切片?
- apache-spark - 将时间戳字段从 Spark SQL 写入 Hive 时的时区更改
- ios - 警报上的 iOS 可访问性:如何限制警报内的焦点?
- java - Java - Netbeans 编译时错误,而没有代码错误
- constructor - 为什么在构造函数中执行我的重入攻击失败?
- c - 重新分配结构数组
- python - Python 3 自我。方法中的属性