python-3.x - 加速 SpaCy 分词器
问题描述
我正在使用 SpaCy 标记数以万计的文档。平均而言,每个文档大约需要 5 秒。关于如何加快标记器的任何建议?
一些附加信息:
- 输入文件是带有换行符的文本文件
- 文件平均大小约为 400KB
- 每个输入文件的标记都被写入输出文件中的新行(如果它有助于提高速度,我可以更改它)
- 有 1655 个停用词
- 输出文件提供给 fasttext
以下是我的代码:
from pathlib import Path, PurePath
from time import time
st = time()
nlp = en_core_web_sm.load(disable = ['ner', 'tagger', 'parser', 'textcat'])
p = Path('input_text/').glob('*.txt')
files = ['input_text/' + x.name for x in p if x.is_file()]
#nlp = spacy.load('en-core-web-sm')
stopwords_file = 'stopwords.txt'
def getStopWords():
f = open(stopwords_file, 'r')
stopWordsSet = f.read()
return stopWordsSet
stopWordsSet = getStopWords()
out_file = 'token_results.txt'
for file in files:
#print (out_file)
with open(file, encoding="utf8") as f:
st_doc = time()
for line in f:
doc = nlp(line)
for token in doc:
if (not token.text.lower() in stopWordsSet
and not token.is_punct and not token.is_space and not token.like_num
and len(token.shape_)>1):
tup = (token.text, '|', token.lemma_)
appendFile = open(out_file, 'a', encoding="utf-8")
appendFile.write(" " + tup[0])
print((time() -st_doc), 'seconds elasped for', file)
appendFile.write('\n')
appendFile.close()
print((time()-st)/60, 'minutes elasped')
解决方案
主要问题:打开一次输出文件并保持打开状态,直到脚本结束。反复关闭和重新打开并寻找更大的文本文件的末尾将非常缓慢。
将停用词读入实际的
set()
. 否则,您将在包含整个文件的长字符串中搜索每个标记,这会意外匹配部分单词并且比检查集合成员资格要慢得多。使用 nlp.pipe() 或仅用于标记化 nlp.tokenizer.pipe() 以加快 spacy 部分。对于一堆简短的单句文档,这似乎并没有太大的区别。标记一个大文档比将每一行视为一个单独的文档要快得多,但是您是否要这样做取决于您的数据的结构方式。如果您只是进行标记,则可以根据
nlp.max_length
需要增加最大文档大小 ( )。
texts = f.readlines()
docs = nlp.tokenizer.pipe(texts)
for doc in docs:
for token in doc:
...
推荐阅读
- python - 熊猫信息未显示所有列和数据类型
- java - 识别 Spring WebClient 使用的 UriBuilder 实现
- r - 在 fanplot 包中创建扇形图
- r - 微阵列元分析和跨平台
- azure - 如何从 azure 门户下载 json 格式而不是 csv 的活动日志
- java - 我无法使用 GSON 序列化表格 Java 表列表
- ibm-watson - 即使我低于 IBM Watson Machine Learning 的限制,也会出现部署限制错误
- javascript - Javascript:四舍五入到小数点后两位
- python - 使用 Flask-SQLAlchemy 的类声明模型时,为什么列变量不需要“self.”?
- c# - 实体框架核心:TPT