適用於:
適用於 Python 的 Azure Machine Learning SDK v1
重要事項
本文提供使用 Azure Machine Learning SDK v1 的相關信息。 SDK v1 自 2025 年 3 月 31 日起已被取代。 其支援將於 2026 年 6 月 30 日結束。 您可以在該日期之前安裝並使用 SDK v1。 您使用 SDK v1 的現有工作流程將在支援終止日期後繼續運作。 不過,如果產品發生架構變更,它們可能會面臨安全性風險或重大變更。
建議您在 2026 年 6 月 30 日之前轉換至 SDK v2。 如需 SDK v2 的詳細資訊,請參閱 什麼是 Azure Machine Learning CLI 和 Python SDK v2? 和 SDK v2 參考。
本文說明如何在 Azure Machine Learning 中撰寫特殊使用案例的專案腳本。 入口腳本,也稱為評分腳本,負責接受請求,使用模型對數據進行評分,並回應結果。
必要條件
您想要使用 Azure Machine Learning 部署的定型機器學習模型。 如需模型部署的詳細資訊,請參閱 將機器學習模型部署至 Azure。
自動產生 Swagger 結構描述
若要自動產生 Web 服務的架構,請在其中一個已定義型別物件的建構函式中提供輸入或輸出的範例。 類型和範例會用來自動建立結構描述。 Azure Machine Learning 接著會在部署期間為 Web 服務建立 OpenAPI 規格 (先前稱為 Swagger 規格)。
警告
請勿針對範例輸入或輸出使用敏感性或私人數據。 在 Azure Machine Learning 中,用於推斷的 Swagger 頁面會公開範例數據。
目前支援下列類型:
pandasnumpypyspark- 標準 Python 物件
若要使用架構產生,請在相依性檔案中包含開放原始 inference-schema 碼套件 1.1.0 版或更新版本。 如需此套件的詳細資訊,請參閱 GitHub 上的 InferenceSchema。 若要產生符合 Swagger 的自動化 Web 服務耗用量, run 評分腳本中的函式必須符合下列條件:
- 第一個參數必須具有類型
StandardPythonParameterType、命名Inputs為 ,而且是巢狀的。 - 必須有一個類型為
StandardPythonParameterType的選擇性第二個參數,名稱為GlobalParameters。 - 函式必須傳回字典,類型為巢狀
StandardPythonParameterType,且名稱為Results。
在 sample_input 和 sample_output 變數中定義輸入和輸出範例格式,這些格式代表 Web 服務的要求和回應格式。 在 run 函式的輸入和輸出函式裝飾項目中使用這些範例。
scikit-learn下一節中的範例會使用架構產生。
Power BI 相容端點
下列範例示範如何根據上一節中的指示來定義 run 函式。 當您從Power BI取用已部署的Web服務時,可以使用此腳本。
import os
import json
import pickle
import numpy as np
import pandas as pd
import azureml.train.automl
import joblib
from sklearn.linear_model import Ridge
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.standard_py_parameter_type import StandardPythonParameterType
from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType
from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType
def init():
global model
# Replace the file name if needed.
model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'sklearn_regression_model.pkl')
# Deserialize the model file back into a sklearn model.
model = joblib.load(model_path)
# Provide three sample inputs for schema generation.
numpy_sample_input = NumpyParameterType(np.array([[1,2,3,4,5,6,7,8,9,10],[10,9,8,7,6,5,4,3,2,1]],dtype='float64'))
pandas_sample_input = PandasParameterType(pd.DataFrame({'name': ['Sarah', 'John'], 'age': [25, 26]}))
standard_sample_input = StandardPythonParameterType(0.0)
# The following sample is a nested input sample. Any item wrapped by `ParameterType` is described by the schema.
sample_input = StandardPythonParameterType({'input1': numpy_sample_input,
'input2': pandas_sample_input,
'input3': standard_sample_input})
sample_global_parameters = StandardPythonParameterType(1.0) # This line is optional.
sample_output = StandardPythonParameterType([1.0, 1.0])
outputs = StandardPythonParameterType({'Results':sample_output}) # "Results" is case sensitive.
@input_schema('Inputs', sample_input)
# "Inputs" is case sensitive.
@input_schema('GlobalParameters', sample_global_parameters)
# The preceding line is optional. "GlobalParameters" is case sensitive.
@output_schema(outputs)
def run(Inputs, GlobalParameters):
# The parameters in the preceding line have to match those in the decorator. "Inputs" and
# "GlobalParameters" are case sensitive.
try:
data = Inputs['input1']
# The data gets converted to the target format.
assert isinstance(data, np.ndarray)
result = model.predict(data)
return result.tolist()
except Exception as e:
error = str(e)
return error
提示
腳本的傳回值可以是可串行化為 JSON 的任何 Python 物件。 例如,如果您的模型傳回包含多個資料行的 Pandas 資料框架,您可能會使用類似下列程式碼的輸出裝飾項目:
output_sample = pd.DataFrame(data=[{"a1": 5, "a2": 6}])
@output_schema(PandasParameterType(output_sample))
...
result = model.predict(data)
return result
二進位影像資料
如果您的模型接受二進位數據,例如映像,您必須修改部署所使用的 score.py 檔案,讓它接受原始 HTTP 要求。 若要接受未經處理資料,請在您的輸入指令碼中使用 AMLRequest 類別,並將 @rawhttp 裝飾項目新增至 run 函式。
下列 score.py 文稿接受二進位資料:
from azureml.contrib.services.aml_request import AMLRequest, rawhttp
from azureml.contrib.services.aml_response import AMLResponse
from PIL import Image
import json
def init():
print("This is init()")
@rawhttp
def run(request):
print("This is run()")
if request.method == 'GET':
# For this example, return the URL for GET requests.
respBody = str.encode(request.full_path)
return AMLResponse(respBody, 200)
elif request.method == 'POST':
file_bytes = request.files["image"]
image = Image.open(file_bytes).convert('RGB')
# For a real-world solution, load the data from the request body
# and send it to the model. Then return the response.
# For demonstration purposes, this example returns the size of the image as the response.
return AMLResponse(json.dumps(image.size), 200)
else:
return AMLResponse("bad request", 500)
重要事項
AMLRequest 類別位於 azureml.contrib 命名空間中。 此命名空間中的實體處於預覽狀態。 它們會隨著服務的改善頻繁變更。 Microsoft不提供這些實體的完整支援。
如果您需要在本機開發環境中測試使用此類別的程式代碼,您可以使用下列命令來安裝元件:
pip install azureml-contrib-services
附註
不建議使用 500 作為自定義狀態代碼。 在 Azure Machine Learning 推斷路由器 (azureml-fe) 端,狀態代碼會重寫為 502。
- 狀態代碼會通過
azureml-fe,然後傳送至用戶端。 - 程式代碼將模型端傳回的
azureml-fe重寫為500。 客戶收到的代碼是502。 - 如果
azureml-fe代碼本身傳回500, 用戶端仍會收到500代碼。
當您使用 類別 AMLRequest 時,只能存取 score.py 檔案中未經處理的數據。 沒有用戶端元件。 從用戶端,您可以像往常一樣張貼數據。 例如,下列 Python 程式碼會讀取影像檔案並張貼資料:
import requests
uri = service.scoring_uri
image_path = 'test.jpg'
files = {'image': open(image_path, 'rb').read()}
response = requests.post(uri, files=files)
print(response.json)
跨原始來源資源分享
跨來源資源分享(CORS)提供一個方法,讓網頁上的資源可以從另一個網域請求。 CORS 可透過 HTTP 標頭運作,這些標頭會隨用戶端要求一起傳送,並使用服務回應傳回。 如需 CORS 和有效標頭的詳細資訊,請參閱 跨原始來源資源分享。
若要將模型部署設定為支援 CORS,請在您的輸入指令碼中使用 AMLResponse 類別。 當您使用此類別時,可以在響應物件上設定標頭。
下列範例會針對來自輸入指令碼的回應設定 Access-Control-Allow-Origin 標頭:
from azureml.contrib.services.aml_request import AMLRequest, rawhttp
from azureml.contrib.services.aml_response import AMLResponse
def init():
print("This is init()")
@rawhttp
def run(request):
print("This is run()")
print("Request: [{0}]".format(request))
if request.method == 'GET':
# For this example, just return the URL for GET.
# For a real-world solution, you would load the data from URL params or headers
# and send it to the model. Then return the response.
respBody = str.encode(request.full_path)
resp = AMLResponse(respBody, 200)
resp.headers["Allow"] = "OPTIONS, GET, POST"
resp.headers["Access-Control-Allow-Methods"] = "OPTIONS, GET, POST"
resp.headers['Access-Control-Allow-Origin'] = "http://www.example.com"
resp.headers['Access-Control-Allow-Headers'] = "*"
return resp
elif request.method == 'POST':
reqBody = request.get_data(False)
# For a real-world solution, you would load the data from reqBody
# and send it to the model. Then return the response.
resp = AMLResponse(reqBody, 200)
resp.headers["Allow"] = "OPTIONS, GET, POST"
resp.headers["Access-Control-Allow-Methods"] = "OPTIONS, GET, POST"
resp.headers['Access-Control-Allow-Origin'] = "http://www.example.com"
resp.headers['Access-Control-Allow-Headers'] = "*"
return resp
elif request.method == 'OPTIONS':
resp = AMLResponse("", 200)
resp.headers["Allow"] = "OPTIONS, GET, POST"
resp.headers["Access-Control-Allow-Methods"] = "OPTIONS, GET, POST"
resp.headers['Access-Control-Allow-Origin'] = "http://www.example.com"
resp.headers['Access-Control-Allow-Headers'] = "*"
return resp
else:
return AMLResponse("bad request", 400)
重要事項
AMLRequest 類別位於 azureml.contrib 命名空間中。 此命名空間中的實體處於預覽狀態。 它們會隨著服務的改善頻繁變更。 Microsoft不提供這些實體的完整支援。
如果您需要在本機開發環境中測試使用此類別的程式代碼,您可以使用下列命令來安裝元件:
pip install azureml-contrib-services
警告
Azure Machine Learning 只會將 POST 和 GET 要求傳遞至執行評分服務的容器。 如果瀏覽器使用 OPTIONS 要求發出預檢要求,可能會導致錯誤。
載入已註冊的模型
有兩種方式可在您的輸入指令碼中尋找模型:
-
AZUREML_MODEL_DIR:包含模型位置路徑的環境變數 -
Model.get_model_path:使用已註冊的模型名稱傳回模型檔案路徑的 API
AZUREML_MODEL_DIR
AZUREML_MODEL_DIR 是服務部署期間所建立的環境變數。 您可以使用此環境變數來尋找已部署模型的位置。
下表描述了在不同數量的部署模型下,AZUREML_MODEL_DIR 的可能值:
| 部署 | 環境變數值 |
|---|---|
| 單一模型 | 包含模型的資料夾路徑。 |
| 多個模型 | 包含所有模型的資料夾路徑。 模型會根據資料夾中的名稱和版本定位,格式為<model-name>/<version>。 |
在模型註冊和部署期間,模型會放在路徑中 AZUREML_MODEL_DIR ,並保留其源檔名稱。
若要取得輸入指令碼中模型檔案的路徑,請將環境變數與您要尋找的檔案路徑結合。
單一模型
下列範例示範如何在您有單一模型時尋找路徑:
import os
# In the following example, the model is a file.
model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'sklearn_regression_model.pkl')
# In the following example, the model is a folder that contains a file.
file_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'my_model_folder', 'sklearn_regression_model.pkl')
多個模型
下列範例示範如何在有多個模型時尋找路徑。 在此案例中,會在工作區中註冊兩個模型:
-
my_first_model:此模型包含一個檔案,my_first_model.pkl,而且有一個版本。1 -
my_second_model:此模型包含一個檔案,my_second_model.pkl,並有兩個版本,1和2。
當您部署服務時,您會在部署作業中提供這兩個模型:
from azureml.core import Workspace, Model
# Get a handle to the workspace.
ws = Workspace.from_config()
first_model = Model(ws, name="my_first_model", version=1)
second_model = Model(ws, name="my_second_model", version=2)
service = Model.deploy(ws, "myservice", [first_model, second_model], inference_config, deployment_config)
在裝載服務的 Docker 映射中 AZUREML_MODEL_DIR ,環境變數包含模型所在的資料夾。 在此資料夾中,每個模型都位於<model-name>/<version>的資料夾路徑中。 在此路徑中, <model-name> 是已註冊模型的名稱,而 <version> 是模型的版本。 組成已註冊模型的檔案會儲存在這些資料夾中。
在這裡範例中,第一個模型的路徑是 $AZUREML_MODEL_DIR/my_first_model/1/my_first_model.pkl。 第二個模型的路徑是 $AZUREML_MODEL_DIR/my_second_model/2/my_second_model.pkl。
# In the following example, the model is a file, and the deployment contains multiple models.
first_model_name = 'my_first_model'
first_model_version = '1'
first_model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), first_model_name, first_model_version, 'my_first_model.pkl')
second_model_name = 'my_second_model'
second_model_version = '2'
second_model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), second_model_name, second_model_version, 'my_second_model.pkl')
get_model_path
當您註冊模型時,您會提供用來管理登錄中模型的模型名稱。 您可以使用這個名稱搭配 Model.get_model_path 方法來擷取本機文件系統上模型檔案或檔案的路徑。 如果您註冊資料夾或檔案集合,此 API 會傳回包含這些檔案的資料夾路徑。
當您註冊模型時,您會為其命名。 名稱會對應至放置模型的位置,不論是在本機或在服務部署期間。
特定架構範例
如需特定機器學習使用案例的更多輸入腳本範例,請參閱下列文章: