我正在尝试在sklearn中的NLP管道中添加词干处理。
from nltk.stem.snowball import FrenchStemmer
stop = stopwords.words('french')
stemmer = FrenchStemmer()
class StemmedCountVectorizer(CountVectorizer):
def __init__(self, stemmer):
super(StemmedCountVectorizer, self).__init__()
self.stemmer = stemmer
def build_analyzer(self):
analyzer = super(StemmedCountVectorizer, self).build_analyzer()
return lambda doc:(self.stemmer.stem(w) for w in analyzer(doc))
stem_vectorizer = StemmedCountVectorizer(stemmer)
text_clf = Pipeline([('vect', stem_vectorizer), ('tfidf', TfidfTransformer()), ('clf', SVC(kernel='linear', C=1)) ])
当使用此管道与sklearn的CountVectorizer时,它可以工作。如果我像这样手动创建特征,它也可以工作。vectorizer = StemmedCountVectorizer(stemmer)
vectorizer.fit_transform(X)
tfidf_transformer = TfidfTransformer()
X_tfidf = tfidf_transformer.fit_transform(X_counts)
编辑:
如果我在我的IPython笔记本上尝试这个流程,它会显示[*]并且什么都不会发生。当我查看我的终端时,它会给出以下错误:
Process PoolWorker-12:
Traceback (most recent call last):
File "C:\Anaconda2\lib\multiprocessing\process.py", line 258, in _bootstrap
self.run()
File "C:\Anaconda2\lib\multiprocessing\process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "C:\Anaconda2\lib\multiprocessing\pool.py", line 102, in worker
task = get()
File "C:\Anaconda2\lib\site-packages\sklearn\externals\joblib\pool.py", line 360, in get
return recv()
AttributeError: 'module' object has no attribute 'StemmedCountVectorizer'
例子
以下是完整的示例
from sklearn.pipeline import Pipeline
from sklearn import grid_search
from sklearn.svm import SVC
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from nltk.stem.snowball import FrenchStemmer
stemmer = FrenchStemmer()
analyzer = CountVectorizer().build_analyzer()
def stemming(doc):
return (stemmer.stem(w) for w in analyzer(doc))
X = ['le chat est beau', 'le ciel est nuageux', 'les gens sont gentils', 'Paris est magique', 'Marseille est tragique', 'JCVD est fou']
Y = [1,0,1,1,0,0]
text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', SVC())])
parameters = { 'vect__analyzer': ['word', stemming]}
gs_clf = grid_search.GridSearchCV(text_clf, parameters, n_jobs=-1)
gs_clf.fit(X, Y)
如果从参数中删除词干处理,它就有效,否则它无法工作。
更新:
问题似乎在并行化过程中,因为当删除 n_jobs=-1 时,问题消失了。
stemming
放在一个导入的模块中,它将更可靠地被解腌。 - joeln