I am migrating to Azure function app for model inference from using Azure container instance deployment. The code below shows how I was loading the model in score.py
import json
import pandas as pd
from joblib import load
import os
import pathlib
from azureml.core.model import Model
def init():
global model
def run(raw_data):
try:
# parse the features from the json doc
dat = json.loads(raw_data)
# deserialize the model file back into a sklearn model
model_name = "{0}_{1}_{2}_sfsw".format(
dat["MachineName"], dat["HeadNumber"], dat["ProductEDP"])
model_path = Model.get_model_path(model_name=model_name)
model = load(model_path)
How would I load the model in a azure function app. would in be in the same way? is def init(): global model still required? the following is code for azure function python app
import pandas as pd
import logging
import azure.functions as func
import joblib
from azureml.core.model import Model
def main(req: func.HttpRequest):
logging.info("Python HTTP trigger function processed a request.")
try:
# Check if request contains JSON
if not req.get_json():
return func.HttpResponse(
"JSON data expected in request.",
status_code=400
)
dat = req.get_json()
except ValueError:
return func.HttpResponse(
"Invalid JSON received.",
status_code=400
)
# Load the model
try:
# deserialize the model file back into a sklearn model
model_name = "{0}_{1}_{2}_sfsw".format(
dat["MachineName"], dat["HeadNumber"], dat["ProductEDP"])
model_path = Model.get_model_path(model_name=model_name)
model = joblib.load(model_path)
except FileNotFoundError:
return func.HttpResponse(
f"Model '{model_name}' not found.",
status_code=404
)
I agree with @Muhammad Pathan you are not required to define global model variable in this function. You can update your code like below:-
I tweaked your code to load my model and perform inference:-
Output:-
Postman request with JSON body:- Json request body according to my model:-
Postman Output:-
As an alternative, In order to load your Azure ML model you can make use of the HttpTrigger code below:-
I have loaded and downloaded the model in a folder called temp. This folder is also created by Function code in the same directory as my Function code with Azure Functions like below:-
Make sure you have logged into your Azure account which contains your ML workspace and model with
az login
command in your VS code Terminal for the below Function code to work.My HttpTrigger code:-
Output:-
Reference:-
Python Azure function timer trigger log info not showing when deployed - Stack Overflow