Search code examples
pythonazureazure-functionsazure-blob-storageazure-http-trigger

Unable to add ML Model in Azure Function Python3


I am trying to create an azure function which will return data from my ML Model (final_model.sav). By doing so ML Model will be available on the internet.

My Azure Function(init.py) program:

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
        )

But whenever I tried to trigger this function via HTTP Endpoint ("http://localhost:7071/api/News?name=HelloWorld") it gives Error 500. I have included "sklearn" package in requirements.txt.

I encountered this error:

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

Error

but I have final_model.sav file in the same directory. I don't know why it is not detecting it.

when I tried to debug the code I came to know that my program stop working when it encounter load_model = pickle.load(open('final_model.sav', 'rb')) line of program. I have placed the 'final_model.sav' in the directory of function (same place where init.py is located).

The files in Function are as follows: Files In azure Function

prediction.py is just a useless file. please ignore it. It doesn't conclude anything about the program.

I think there maybe there is an issue in bindings. Please check my function.json file.

function.json:

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

Thank you for giving your valuable time towards my problem. Thank you very much.


Solution

  • Since you are loading the file from root path with open('final_model.sav', 'rb'), it is looking for that at the function app home location. So, move 'final_model.sav' to there i.e. to the same level where 'host.json' is.