【问题标题】:Unable to add ML Model in Azure Function Python3无法在 Azure Function Python3 中添加 ML 模型
【发布时间】:2021-01-09 08:41:58
【问题描述】:

我正在尝试创建一个 azure 函数,该函数将从我的 ML 模型 (final_model.sav) 中返回数据。 通过这样做,ML 模型将在 Internet 上可用。

我的 Azure Function(init.py) 程序:

import azure.functions as func
import pickle


def main(req: func.HttpRequest) -> func.HttpResponse:
    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        
        var=name
        load_model = pickle.load(open('final_model.sav', 'rb'))
        prediction = load_model.predict([var])
        prob = load_model.predict_proba([var])
        
        return func.HttpResponse(f"{prediction[0]}&{prob[0][1]}.")
        
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

但每当我尝试通过 HTTP 端点 ("http://localhost:7071/api/News?name=HelloWorld") 触发此功能时,都会出现错误 500。 我在requirements.txt 中包含了“sklearn”包。

我遇到了这个错误:

Exception: FileNotFoundError: [Errno 2] No such file or directory: 'final_model.sav'

但我在同一目录中有final_model.sav 文件。我不知道为什么它没有检测到它。

当我尝试调试代码时,我发现我的程序在遇到load_model = pickle.load(open('final_model.sav', 'rb')) 程序行时停止工作。 我已将“final_model.sav”放在函数目录中(init.py 所在的同一位置)。

Function中的文件如下:

prediction.py 只是一个无用的文件。请忽略它。它没有对程序做出任何结论。

我认为绑定可能存在问题。请检查我的function.json 文件。

function.json:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

感谢您抽出宝贵的时间来解决我的问题。 非常感谢。

【问题讨论】:

  • 能否提供详细的错误信息?
  • 你好 @JimXu 先生,我已经用错误日志更新了这个问题。请再次查看。感谢您为我的问题付出宝贵的时间。如果它得到解决,那将是一个很大的帮助
  • 您发布的错误仅包含堆栈跟踪。你能发布完整的例外吗?
  • @KrishnenduGhosh-MSFT 我已经更新了错误日志,请再次检查,感谢您为我的问题付出宝贵的时间。
  • 将“final_model.sav”移动到函数宿主的根目录,即在“host.json”所在的同一级别。

标签: python azure azure-functions azure-blob-storage azure-http-trigger


【解决方案1】:

由于您使用 open('final_model.sav', 'rb') 从根路径加载文件,因此它正在函数应用主位置查找该文件。因此,将“final_model.sav”移到那里,即移到“host.json”所在的同一级别。

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 2016-12-24
    • 2019-03-13
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2021-02-08
    • 1970-01-01
    相关资源
    最近更新 更多