我有两个文件,file1.py
包含大小为1GB的ML模型,file2.py
调用file1
中的get_vec()
方法并接收返回的向量。每当file1
的get_vec()
方法被调用时,MLmodel
都会被重新加载。这导致从磁盘加载模型需要很长时间(大约10秒)。
我想告诉file1
不要每次都重新加载模型,而是利用之前调用时已加载的模型。
示例代码如下
# File1.pyimport spacynlp = spacy.load('model')def get_vec(post): doc = nlp(post) return doc.vector
File2.pyfrom File1 import get_vecdf['vec'] = df['text'].apply(lambda x: get_vec(x))
因此,每次调用都需要10到12秒。这看起来代码量很小,但它是一个大型项目的组成部分,我无法将它们放在同一个文件中。
更新1:
我做了一些研究,发现我可以使用Redis在第一次运行时将模型存储在缓存中,此后我可以直接从缓存中读取模型。我尝试使用Redis进行测试,如下所示
import spacyimport redisnlp = 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中?
谁能建议我如何使它更快?谢谢。
回答:
以下是如何操作
步骤1)在Python中创建一个函数,并在该函数中加载您的模型
model=Nonedef load_model(): global model model = ResNet50(weights="imagenet")
如果你仔细观察,首先我将变量model
赋值为None。然后在load_model
函数中加载了一个模型。
我还确保变量model
是全局的,以便它可以从函数外部访问。这里的直觉是我们将模型对象加载到一个全局变量中。这样我们可以在代码中的任何地方访问这个变量。
现在我们已经准备好了工具(即我们可以在代码中的任何地方访问模型),让我们将模型冻结在计算机的RAM中。这样做的方法是:
if __name__ == "__main__": print(("* Loading Keras model and Flask starting server..." "please wait until server has fully started")) load_model() app.run()
现在,在不使用的情况下将模型冻结在RAM中有什么用呢?所以,为了使用它,我在Flask中使用POST请求
@app.route("/predict", methods=["POST"])def predict(): if flask.request.method == "POST": output=model.predict(data) #在这里放置你想对冻结模型做的操作
通过这个技巧,你可以将模型冻结在RAM中,使用全局变量访问它,然后在你的代码中使用它。