python - 在 sklearn 管道中使用 spacy 作为分词器

标签 python scikit-learn spacy

我正在尝试在更大的 scikit-learn 管道中使用 spacy 作为分词器,但一直遇到无法将任务 pickle 发送给工作人员的问题。

最小的例子:

from sklearn.linear_model import SGDClassifier
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import RandomizedSearchCV
from sklearn.datasets import fetch_20newsgroups
from functools import partial
import spacy


def spacy_tokenize(text, nlp):
    return [x.orth_ for x in nlp(text)]

nlp = spacy.load('en', disable=['ner', 'parser', 'tagger'])
tok = partial(spacy_tokenize, nlp=nlp)

pipeline = Pipeline([('vectorize', CountVectorizer(tokenizer=tok)),
                     ('clf', SGDClassifier())])

params = {'vectorize__ngram_range': [(1, 2), (1, 3)]}

CV = RandomizedSearchCV(pipeline,
                        param_distributions=params,
                        n_iter=2, cv=2, n_jobs=2,
                        scoring='accuracy')

categories = ['alt.atheism', 'comp.graphics']
news = fetch_20newsgroups(subset='train',
                          categories=categories,
                          shuffle=True,
                          random_state=42)

CV.fit(news.data, news.target)

运行这段代码我得到错误:

PicklingError: Could not pickle the task to send it to the workers.

让我困惑的是:

import pickle
pickle.dump(tok, open('test.pkl', 'wb'))

工作没有问题。

有人知道是否可以将 spacy 与 sklearn 交叉验证一起使用吗? 谢谢!

最佳答案

这不是解决方案,而是解决方法。看起来 spacy 和 joblib 之间存在一些问题:

如果您可以将分词器作为函数保存在目录中的单独文件中,然后将其导入当前文件,则可以避免此错误。像这样的东西:

  • 自定义文件.py

    import spacy
    nlp = spacy.load('en', disable=['ner', 'parser', 'tagger'])
    
    def spacy_tokenizer(doc):
        return [x.orth_ for x in nlp(doc)]
    
  • .py

    #Other code     
    ...
    ... 
    
    from custom_file import spacy_tokenizer
    
    pipeline = Pipeline([('vectorize', CountVectorizer(tokenizer=spacy_tokenizer)),
                         ('clf', SGDClassifier())])
    
    ...
    ...
    

关于python - 在 sklearn 管道中使用 spacy 作为分词器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53885198/

相关文章:

python - Matplotlib/Tkinter 错误 : exception when comparing collection3d objects

python - 如何下载使用 django-filebrowser 上传的文件?

Python 神经网络强化学习

python - 异构 DataFrame 上的 StratifiedKfold

python - 如何查看 spacy NER softmax 值?

anaconda - conda-forge::tqdm-4.19.4-py_0 - CondaError:无法链接不存在的源

python - 值错误: time data '140120 1520' does not match format '%Y-%m-%d %H:%M:%S'

python - 如何以正确的方式在 Ubuntu 上安装 numpy?

python - 如何处理导入错误?

python - RASA 和 Spacy 之间的区别或关系