【发布时间】:2020-07-17 19:58:09
【问题描述】:
我有两个文件,file1.py 的 ML 模型大小为 1GB,file2.py 从 file1 调用 get_vec() 方法并接收向量作为回报。每次调用 file1 get_vec() 方法时,都会加载 ML model。这是从磁盘加载模型需要花费大量时间(大约 10 秒)的地方。
我想以某种方式告诉 file1 不要每次都重新加载模型,而是利用之前调用的加载模型。
示例代码如下
# File1.py
import spacy
nlp = spacy.load('model')
def get_vec(post):
doc = nlp(post)
return doc.vector
File2.py
from File1 import get_vec
df['vec'] = df['text'].apply(lambda x: get_vec(x))
所以在这里,每次调用需要 10 到 12 秒。这似乎是小代码,但它是大型项目的一部分,我不能将两者放在同一个文件中。
更新1:
我做了一些研究,发现我可以在第一次运行时使用 Redis 将模型存储在缓存中,然后我可以直接从缓存中读取模型。我尝试使用 Redis 进行如下测试
import spacy
import redis
nlp = spacy.load('en_core_web_lg')
r = redis.Redis(host = 'localhost', port = 6379, db = 0)
r.set('nlp', nlp)
会报错
DataError: Invalid input of type: 'English'. Convert to a bytes, string, int or float first.
看来,type(nlp) 是English(),它需要转换成合适的格式。所以我也尝试使用 pickle 来转换它。但同样,pickle 在编码和解码方面花费了大量时间。有没有办法将它存储在 Redis 中?
谁能建议我怎样才能让它更快?谢谢。
【问题讨论】:
-
这个链接没有太多帮助。感谢您的评论。
标签: python machine-learning redis nlp spacy