我正在迁移到Azure Function App以使用Azure容器实例部署进行模型推断.下面的代码显示了我是如何将模型加载到Scotre.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)

我如何将模型加载到Azure功能应用程序中.也会是同样的方式吗?是def init(): 还需要全球模型吗?以下是azure函数python应用程序的代码

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
        )

推荐答案

我同意@Muhammad Pathan,您不需要在此函数中定义全局模型变量.您可以按如下方式更新代码:-

100

import logging
import azure.functions as func
from azureml.core import Workspace, Model
import joblib
import pandas as pd

def load_model(model_name):
    try:
        # Load the model from Azure ML
        model = Model(workspace=ws, name=model_name)
        model_path = model.download(exist_ok=True)  # Download the model
        loaded_model = joblib.load(model_path)
        return loaded_model
    except Exception as e:
        return None

# Load your Azure ML Workspace from a configuration file
ws = Workspace.from_config('./config.json')

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 the request.",
                status_code=400
            )
        dat = req.get_json()
    except ValueError:
        return func.HttpResponse(
            "Invalid JSON received.",
            status_code=400
        )

    model_name = "sample_model3"  # Replace with the model name in your workspace

    # Load the model
    model = load_model(model_name)
    if model is None:
        return func.HttpResponse(
            f"Model '{model_name}' not found.",
            status_code=404
        )

    # Perform inference using the loaded model
    try:
        result = model.predict(pd.DataFrame([dat]))
        return func.HttpResponse(f"Inference result: {result}")
    except Exception as e:
        return func.HttpResponse(f"An error occurred during inference: {str(e)}", status_code=500)

Output:-个个

enter image description here

100

{
    "sepal length (cm)": 5.1,
    "sepal width (cm)": 3.5,
    "petal length (cm)": 1.4,
    "petal width (cm)": 0.2
}

Postman Output:-

enter image description here As an alternative, In order to load your Azure ML model you can make use of the HttpTrigger code below:-

我有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个,下面是Azure Functions个:

确保你已经登录到你的Azure帐户,该帐户包含你的ML工作区和模型,并在你的VS代码终端中使用100命令,以使以下功能代码正常工作.

My HttpTrigger code:-

import os
import azure.functions as func
from azureml.core import Workspace, Model

# Function to load and download models
def load_and_download_models():
    try:
        ws = Workspace.from_config('./config.json')
        # Load your Azure ML Workspace. Replace with your own values.
        ws = Workspace(subscription_id="xxxxxxxxaxxxx",
                       resource_group="xxxx",
                       workspace_name="xxx")

        
        downloaded_models_path = "temp"

        loaded_and_downloaded_models = []

        for model_name in ws.models:
            # Iterate through model names in the workspace

            # Load the model using its name
            model = Model(ws, model_name)

            

            # Download the model to a specified directory
            model_path = model.download(target_dir=downloaded_models_path)

            loaded_and_downloaded_models.append(model_name)

        return loaded_and_downloaded_models

    except Exception as e:
        return str(e)

# Azure Function entry point with HTTP trigger
def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        loaded_and_downloaded_models = load_and_download_models()
        if isinstance(loaded_and_downloaded_models, list):
            return func.HttpResponse(f"Models loaded and downloaded successfully: {', '.join(loaded_and_downloaded_models)}", status_code=200)
        else:
            return func.HttpResponse(f"An error occurred: {loaded_and_downloaded_models}", status_code=500)
    except Exception as e:
        return func.HttpResponse(f"An error occurred: {str(e)}", status_code=500)

Output:-个个

enter image description here

enter image description here

Reference:-

Python Azure function timer trigger log info not showing when deployed - Stack Overflow

Python相关问答推荐

如何使用entry.bind(FocusIn,self.Method_calling)用于使用网格/列表创建的收件箱

jit JAX函数中的迭代器

将numpy数组存储在原始二进制文件中

对Numpy函数进行载体化

如何让剧作家等待Python中出现特定cookie(然后返回它)?

为什么符号没有按顺序添加?

Vectorize多个头寸的止盈/止盈回溯测试pythonpandas

什么相当于pytorch中的numpy累积ufunc

如何使用数组的最小条目拆分数组

如何使用它?

用SymPy在Python中求解指数函数

Discord.py -

如何使用正则表达式修改toml文件中指定字段中的参数值

Pandas—MultiIndex Resample—我不想丢失其他索引的信息´

如何根据rame中的列值分别分组值

提取数组每行的非零元素

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

为什么我的scipy.optimize.minimize(method=";newton-cg";)函数停留在局部最大值上?

如何将验证器应用于PYDANC2中的EACHY_ITEM?

如何在Polars中将列表中的新列添加到现有的数据帧中?