【发布时间】:2018-11-15 05:47:57
【问题描述】:
我在 stackoverflow 和其他地方进行了广泛的研究,但似乎无法找到以下问题的答案。
我正在尝试修改函数的参数,该参数本身就是 GridSearchCV function of sklearn. More specifically, I want to change parameters (herepreserve_case = False) inside thecasual_tokenizefunction that is passed to the parametertokenizerof the functionCountVectorizer` 中的参数。
具体代码如下:
from sklearn.datasets import fetch_20newsgroups
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import GridSearchCV
from nltk import casual_tokenize
从 20newsgroup 生成虚拟数据
categories = ['alt.atheism', 'comp.graphics', 'sci.med',
'soc.religion.christian']
twenty_train = fetch_20newsgroups(subset='train',
categories=categories,
shuffle=True,
random_state=42)
创建分类管道。
请注意,可以使用lambda 修改标记器。我想知道是否还有其他方法可以做到这一点,因为它不适用于 GridSearchCV 。
text_clf = Pipeline([('vect',
CountVectorizer(tokenizer=lambda text:
casual_tokenize(text,
preserve_case=False))),
('tfidf', TfidfTransformer()),
('clf', MultinomialNB()),
])
text_clf.fit(twenty_train.data, twenty_train.target) # this works fine
然后我想将CountVectorizer 的默认标记器与 nltk 中的进行比较。请注意,我问这个问题是因为我想比较多个标记器,每个标记器都有需要指定的特定参数。
parameters = {'vect':[CountVectorizer(),
CountVectorizer(tokenizer=lambda text:
casual_tokenize(text,
preserve_case=False))]}
gs_clf = GridSearchCV(text_clf, parameters, n_jobs=-1, cv=5)
gs_clf = gs_clf.fit(twenty_train.data[:100], twenty_train.target[:100])
gs_clf.fit 给出以下错误:PicklingError: Can't pickle at 0x1138c5598>: attribute lookup on main failed
所以我的问题是:
1) 有谁知道如何专门用GridSearchCV 处理这个问题。
2)有没有更好的pythonic方法来处理将参数传递给也将是参数的函数?
【问题讨论】:
标签: python scikit-learn grid-search