python - Spacy 英语语言模型加载时间过长
问题描述
我正在尝试使用 python 制作一个聊天机器人,为此我使用 Spacy 进行实体识别,所以我安装了预构建的 Spacy 英语语言模型(中)来从用户话语中提取实体,但问题是当我加载模型时要从用户话语中提取实体,加载模型需要 31 秒,因为在我的情况下,聊天机器人的时间真的很重要。需要大家的指导,还有其他选择吗?任何帮助将非常感激
下面是从用户话语中提取实体的代码:
import spacy
import time
def extractEntity(userUtterance):
''' This funtion returns a list of tuple a tuple contain
(entity Name, Entity Type)
We use pre build spacy english language model to extract entities
'''
start_time = time.process_time()
nlp = spacy.load("en")
print(time.process_time() - start_time, "seconds") # prints the time taken to load the model
docx = nlp(userUtterance)
listOfTyples = [(word.text, spacy.explain(word.label_)) for word in docx.ents]
return listOfTyples
if __name__ == "__main__":
print(extractEntity("I want to go to London, can you book my flight for wednesday"))
输出:
31.0 seconds
[('London', 'Countries, cities, states'), ('wednesday', 'Absolute or relative dates or periods')]
解决方案
这真的很慢,因为它为每个句子加载模型:
import spacy
def dostuff(text):
nlp = spacy.load("en")
return nlp(text)
这并不慢,因为它会加载一次模型并为每个函数调用重新使用它:
import spacy
nlp = spacy.load("en")
def dostuff(text):
return nlp(text)
您应该将您的应用程序更改为类似于第二个示例。这不是 spaCy 特有的,但您选择使用的任何类型的模型都会出现这种情况。
推荐阅读
- spring - Spring Boot / MapStruct:构造函数的参数1需要一个bean......考虑定义一个类型的bean
- java - Android Studio 4.1.2 无法在模拟器或真机上运行android studio
- angular - 用于保存数据的 Angular 调用服务
- c++ - 如何旋转向量的特定子集?
- qt - 如何通过多级子线程保持 GUI 平稳运行
- python - Scipy b 样条基函数
- python - Matplotlib 图例不适用于三元散点图
- wordpress - 在 wordpress 页面模板中访问 Vue 应用程序中的字体资源
- django - 试图在模型中将 slug 添加到 get_absolute_url 函数的末尾(Django)
- amazon-web-services - 创建k8s资源并等待它完成继续下一个