【问题标题】:Django: Machine learning model in server side?Django:服务器端的机器学习模型?
【发布时间】:2017-08-27 09:54:55
【问题描述】:

我有一个Word2Vec 模型(机器学习模型之一),可以通过文件名获得这个预训练模型:

model = Word2Vec.load(fname)

所以,我可以通过使用这个模型得到一些预测:

预测 = model.predict(X)

我想要做的是从用户那里获取请求(包括查询词)并将这些数据查询到我的预训练模型并获取预测,以便服务器可以使用此预测数据发送响应。这个过程应该在每次用户发送查询时发生,所以这个预训练的模型应该总是在内存中。

要实现这一点,我想我必须使用RedisCelery 有点东西,但据我所知,CeleryDjango 网络应用程序异步工作,所以它不适合什么我想做...

如何在我的Django 应用程序中实现此功能?

谢谢。

【问题讨论】:

标签: django machine-learning redis celery


【解决方案1】:

其次,您不需要 Redis 和 celery。 Daniel Roseman 在this question 中概述了最简单的解决方案。

如果您有一个无法序列化/腌制的对象(这是利用 django 缓存所必需的),这种方法也很实用。

您需要做的就是在views.py 中的视图之前实例化model 对象,这样model 会被调用一次(当views.py 被导入时)并且基于类/函数的视图将能够访问model

这在您的问题中看起来像这样:

# views.py
model = Word2Vec.load(fname)

class WordView(View):
  def post(self, request, *args, **kwargs):

    # make a prediction based on request
    prediction = model.predict(self.request.something)

    return prediction

【讨论】:

    【解决方案2】:

    你实际上并不需要 Redis 或 celery。

    在我发布使用 Django 的解决方案之前,我应该提一下,如果您的 ML 项目只需要一个 Web 界面,也就是说,您不需要 Django 的花哨的 ORM、admin 等,您应该使用 Flask。它非常适合您的用例。


    使用 Flask 的解决方案:

    使用 Flask 将训练好的模型存储在内存中非常容易:

    # ...
    # your Flask application code
    # ...
    # ...
    
    if __name__ == '__main__':
        model = Word2Vec.load(fname)
        app.run()
    

    如果你有兴趣,完整的例子是here


    使用 Django 的解决方案:

    您可以利用 Django 的缓存框架来存储您的模型。首先,激活本地内存缓存后端。 Instructions are here.

    现在,您需要将模型存储在缓存中。

    from django.core.cache import cache
    
    model_cache_key = 'model_cache' 
    # this key is used to `set` and `get` 
    # your trained model from the cache
    
    model = cache.get(model_cache_key) # get model from cache
    
    if model is None:
        # your model isn't in the cache
        # so `set` it
        model = Word2Vec.load(fname) # load model
        cache.set(model_cache_key, model, None) # save in the cache
        # in above line, None is the timeout parameter. It means cache forever
    
    # now predict
    prediction = model.predict(...)
    

    您可以将上述代码保留在您的视图中,但我希望您为此创建一个单独的文件,然后将该文件导入您的视图中。

    你可以找到完整的例子是on this blog

    【讨论】:

    • 链接已过期,能否提供Django解决方案的示例?谢谢。
    • @ascetic652 您可以在this Wayback snapshot 中查看该博文。
    猜你喜欢
    • 1970-01-01
    • 2017-07-12
    • 2016-10-27
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多