將機器學習模型部署到即時推論端點

教學

概觀

在本教學中,您將學習如何使用 Amazon SageMaker Studio 將經過訓練的機器學習 (ML) 模型部署到即時推論端點。

SageMaker Studio 是用於 ML 的整合開發環境 (IDE),它提供全受管的 Jupyter 筆記本介面,您可以在其中執行包括模型部署在內的端對端 ML 生命週期任務。

SageMaker 提供多種推論選項,可支援諸多使用案例

在本教學中,您將使用即時推論選項來部署二進制分類 XGBoost 模型,該模型已經過綜合的汽車保險索賠資料集訓練。該資料集由 claims (索賠) 和 customer (客戶) 表 (表中還包含指示索賠是否為詐騙的 fraud (詐騙) 欄) 的詳細資訊以及從中擷取的特徵組成。該模型會預測某個索賠為詐騙的機率。您將扮演機器學習工程師的角色,部署該模型並執行樣本推論。

要完成的內容

在本指南中,您將:

  • 從經過訓練模型的成品建立 SageMaker 模型
  • 設定並部署即時推論端點以用於該模型
  • 叫用端點以使用測試資料來執行樣本預測
  • 向端點關聯自動擴縮政策以處理流量變更

先決條件

在開始本指南之前,您需要具備:

  • AWS 帳戶:如果您還沒有,請按照設定您的環境快速入門指南進行操作。

 AWS 經驗

初階

 完成時間

25 分鐘

 完成成本

請參閱 SageMaker 定價以估算本教學的成本。

 要求

您必須登入 AWS 帳戶。

 使用的服務

Amazon SageMaker 即時推論、Amazon SageMaker Studio

 上次更新日期

2022 年 5 月 19 日

實作

步驟 1:設定 Amazon SageMaker Studio 網域

藉助 Amazon SageMaker,您可以使用主控台視覺化地部署模型,也可以使用 SageMaker Studio 或 SageMaker 筆記本以程式設計方式部署模型。在本教學中,您將使用 SageMaker Studio 筆記本以程式設計的方式部署模型,而該筆記本需要一個 SageMaker Studio 網域。

每個 AWS 帳戶在每個區域只能擁有一個 SageMaker Studio 網域。如果您在美國東部 (維吉尼亞北部) 區域已有 SageMaker Studio 網域,請按照 SageMaker Studio 設定指南將所需的 AWS IAM 政策連接到您的 SageMaker Studio 帳戶,然後略過步驟 1,並直接進行步驟 2。 

如果您沒有現有的 SageMaker Studio 網域,請繼續進行步驟 1 以執行 AWS CloudFormation 範本,該範本將建立 SageMaker Studio 網域,並新增本教學其餘部分所需的許可。

選擇 AWS CloudFormation 堆疊連結。此連結將開啟 AWS CloudFormation 主控台,並建立您的 SageMaker Studio 網域和名為 studio-user 的使用者。它還會向您的 SageMaker Studio 帳戶新增所需的許可。在 CloudFormation 主控台中,確認右上角顯示的 Region (區域) 是 US East (N. Virginia) (美國東部 (維吉尼亞北部))。 Stack name (堆疊名稱) 應為 CFN-SM-IM-Lambda-catalog,且不應變更。 此堆疊大約需要 10 分鐘來建立所有資源。

此堆疊假定您已經在您的帳戶中設定了公有 VPC。如果您沒有公有 VPC,請參閱具有單一公有子網路的 VPC,了解如何建立公有 VPC。 

選取 I acknowledge that AWS CloudFormation might create IAM resources (我認知 AWS CloudFormation 可能會建立 IAM 資源),然後選擇 Create stack (建立堆疊)。

CloudFormation 窗格中,選擇 Stacks (堆疊)。建立此堆疊約需要 10 分鐘。建立該堆疊後,堆疊狀態從 CREATE_IN_PROGRESS 變更為 CREATE_COMPLETE。 

步驟 2:設定 SageMaker Studio 筆記本

在此步驟中,您要啟動一個新的 SageMaker Studio 筆記本,安裝必要的開放原始碼程式庫,並設定從 Amazon Simple Storage Service (Amazon S3) 取得經過訓練模型的成品所需的 SageMaker 變數。但由於無法直接部署模型成品以用於推論,您需要首先從模型的成品建立 SageMaker 模型。所建立的模型將包含 SageMaker 將在模型部署時使用的訓練和推論程式碼。

在管理主控台搜尋列中輸入 SageMaker Studio,然後選擇 SageMaker Studio

從 SageMaker 主控台右上角的 Region (區域) 下拉式清單中選擇 US East (N. Virginia) (美國東部 (維吉尼亞北部))。對於 Launch app (啟動應用程式),選取 Studio 以開啟 SageMaker Studio 並使用 studio-user 設定檔。

開啟 SageMaker Studio 介面。在導覽列上,選擇 File (檔案)、New (新增)、Notebook (筆記本)。 

Set up notebook environment (設定筆記本環境) 對話方塊中的 Image (映像) 下,選取 Data Science (資料科學)。將自動選取 Python 3 核心。選擇 Select (選取)。

筆記本右上角上的核心現在應顯示 Python 3 (Data Science) (Python 3 (資料科學))。

複製以下程式碼片段並貼到筆記本的儲存格,按 Shift+Enter 執行當前儲存格以更新 aiobotocore 程式庫,它是與許多 AWS 服務互動的 API。忽略任何警告以重新啟動核心或任何相依性衝突錯誤。

%pip install --upgrade -q aiobotocore

您還需要具現化 S3 用戶端物件,以及預設 S3 儲存貯體中指標和模型成品上傳到的位置。為此,複製以下程式碼,將其貼到筆記本的儲存格中並執行。 注意,以下程式碼第 16 行中的 SageMaker 工作階段物件將自動建立寫入儲存貯體 sagemaker-<您的區域>-<您的帳戶 ID>。用於訓練的資料集存在於一個名為 sagemaker-sample-files 的公有 S3 儲存貯體中,該儲存貯體在第 29 行中被指定為讀取儲存貯體。儲存貯體中的位置透過讀取字首指定。

import pandas as pd
import numpy as np
import boto3
import sagemaker
import time
import json
import io
from io import StringIO
import base64
import pprint
import re

from sagemaker.image_uris import retrieve

sess = sagemaker.Session()
write_bucket = sess.default_bucket()
write_prefix = "fraud-detect-demo"

region = sess.boto_region_name
s3_client = boto3.client("s3", region_name=region)
sm_client = boto3.client("sagemaker", region_name=region)
sm_runtime_client = boto3.client("sagemaker-runtime")
sm_autoscaling_client = boto3.client("application-autoscaling")

sagemaker_role = sagemaker.get_execution_role()


# S3 locations used for parameterizing the notebook run
read_bucket = "sagemaker-sample-files"
read_prefix = "datasets/tabular/synthetic_automobile_claims" 
model_prefix = "models/xgb-fraud"

data_capture_key = f"{write_prefix}/data-capture"

# S3 location of trained model artifact
model_uri = f"s3://{read_bucket}/{model_prefix}/fraud-det-xgb-model.tar.gz"

# S3 path where data captured at endpoint will be stored
data_capture_uri = f"s3://{write_bucket}/{data_capture_key}"

# S3 location of test data
test_data_uri = f"s3://{read_bucket}/{read_prefix}/test.csv"

步驟 3:建立即時推論端點

SageMaker 中有多種方法可以將經過訓練的模型部署到即時推論端點:SageMaker 開發套件AWS 開發套件 - Boto3 和 SageMaker 主控台。如需詳細資訊,請參閱《Amazon SageMaker 開發人員指南》中的部署用於推論的模型。SageMaker 開發套件與 AWS 開發套件 - Boto3 相比有更多抽象,後者公開較低級別 API 並可更有力地控制模型部署。在本教學中,您要使用 AWS 開發套件 - Boto3 部署模型。若要部署模型,您需要按順序完成三個步驟:

  1. 從模型的成品建立 SageMaker 模型
  2. 建立端點組態以指定屬性 (包括執行個體類型和數量)
  3. 使用端點組態來建立端點

若要使用儲存在 S3 中經過訓練模型的成品建立 SageMaker 模型,複製並貼上以下程式碼。create_model 方法使用包含訓練映像的 Docker 容器 (對於此模型為 XGBoost 容器) 和模型成品的 S3 位置作為參數。 

# Retrieve the SageMaker managed XGBoost image
training_image = retrieve(framework="xgboost", region=region, version="1.3-1")

# Specify a unique model name that does not exist
model_name = "fraud-detect-xgb"
primary_container = {
                     "Image": training_image,
                     "ModelDataUrl": model_uri
                    }

model_matches = sm_client.list_models(NameContains=model_name)["Models"]
if not model_matches:
    model = sm_client.create_model(ModelName=model_name,
                                   PrimaryContainer=primary_container,
                                   ExecutionRoleArn=sagemaker_role)
else:
    print(f"Model with name {model_name} already exists! Change model name to create new")

您可以在 SageMaker 主控台的 Models (模型) 區段下方檢查已建立的模型。

在建立 SageMaker 模型後,複製並貼上以下程式碼,以使用 Boto3 create_endpoint_config 方法來設定端點。create_endpoint_config 方法的主要輸入為端點組態名稱和變體資訊,例如,推論執行個體類型和數量、要部署的模型的名稱,以及端點應處理的流量份額。除這些設定以外,您還可以透過指定 DataCaptureConfig 設定資料擷取。此功能允許您設定即時端點,以擷取請求和/或回應並將其儲存到 Amazon S3 中。資料擷取是設定模型監控的步驟之一。當與基準指標和監控任務結合時,它可以透過比較測試資料指標和基準來協助您監控模型效能。此類監控對於根據模型或資料漂移和稽核目的來安排模型的再訓練非常有幫助。在當前設定中,輸入 (傳入的測試資料) 和輸出 (模型預測) 會被擷取,並儲存在預設 S3 儲存貯體當中。

# Endpoint Config name
endpoint_config_name = f"{model_name}-endpoint-config"

# Endpoint config parameters
production_variant_dict = {
                           "VariantName": "Alltraffic",
                           "ModelName": model_name,
                           "InitialInstanceCount": 1,
                           "InstanceType": "ml.m5.xlarge",
                           "InitialVariantWeight": 1
                          }

# Data capture config parameters
data_capture_config_dict = {
                            "EnableCapture": True,
                            "InitialSamplingPercentage": 100,
                            "DestinationS3Uri": data_capture_uri,
                            "CaptureOptions": [{"CaptureMode" : "Input"}, {"CaptureMode" : "Output"}]
                           }


# Create endpoint config if one with the same name does not exist
endpoint_config_matches = sm_client.list_endpoint_configs(NameContains=endpoint_config_name)["EndpointConfigs"]
if not endpoint_config_matches:
    endpoint_config_response = sm_client.create_endpoint_config(
                                                                EndpointConfigName=endpoint_config_name,
                                                                ProductionVariants=[production_variant_dict],
                                                                DataCaptureConfig=data_capture_config_dict
                                                               )
else:
    print(f"Endpoint config with name {endpoint_config_name} already exists! Change endpoint config name to create new")

您可以在 SageMaker 主控台的 Endpoint configurations (端點組態) 區段下方檢查建立的端點組態。

 

 

複製並貼上以下程式碼,以建立端點。create_endpoint 方法使用端點組態作為參數,並將端點組態中指定的模型部署到運算執行個體。部署模型需要大約 6 分鐘。

endpoint_name = f"{model_name}-endpoint"

endpoint_matches = sm_client.list_endpoints(NameContains=endpoint_name)["Endpoints"]
if not endpoint_matches:
    endpoint_response = sm_client.create_endpoint(
                                                  EndpointName=endpoint_name,
                                                  EndpointConfigName=endpoint_config_name
                                                 )
else:
    print(f"Endpoint with name {endpoint_name} already exists! Change endpoint name to create new")

resp = sm_client.describe_endpoint(EndpointName=endpoint_name)
status = resp["EndpointStatus"]
while status == "Creating":
    print(f"Endpoint Status: {status}...")
    time.sleep(60)
    resp = sm_client.describe_endpoint(EndpointName=endpoint_name)
    status = resp["EndpointStatus"]
print(f"Endpoint Status: {status}")

若要檢查端點的狀態,選擇 SageMaker resources (SageMaker 資源) 圖示。在 SageMaker resources (SageMaker 資源) 中,選取 Endpoints (端點),然後選取 fraud-detect-xgb-endpoint 作為 Name (名稱)。

 

步驟 4:叫用推論端點

在端點狀態變更為 InService (服務中) 後,您可以使用 REST API、AWS 開發套件 - Boto3、SageMaker Studio、AWS CLI 或 SageMaker Python 開發套件來叫用該端點。在本教學中,您將使用 AWS 開發套件 - Boto3。在呼叫端點前,務必要利用序列化和還原序列化將測試資料格式化為適用於端點的格式。序列化是指將 .csv 等格式的原始資料轉換成端點可使用的位元組串流的過程。還原序列化是將位元組串流轉換為人類可讀格式的反向流程。在本教學中,您會透過傳送測試資料集中的前五個樣本來叫用端點。複製並貼上以下程式碼,以叫用端點並取得預測結果。由於向端點傳送的請求 (測試資料集) 使用 .csv 格式,因此要使用 csv 序列化程序來建立承載。然後,回應會被還原序列化為預測陣列。在儲存格執行完畢後,會返回測試樣本的模型預測和 true 標籤。請注意,XGBoost 模型會返回機率,而不是實際分類標籤。模型預測測試樣本為詐騙性索賠的可能性非常低,而且預測與 true 標籤相符。

 

# Fetch test data to run predictions with the endpoint
test_df = pd.read_csv(test_data_uri)

# For content type text/csv, payload should be a string with commas separating the values for each feature
# This is the inference request serialization step
# CSV serialization
csv_file = io.StringIO()
test_sample = test_df.drop(["fraud"], axis=1).iloc[:5]
test_sample.to_csv(csv_file, sep=",", header=False, index=False)
payload = csv_file.getvalue()
response = sm_runtime_client.invoke_endpoint(
                                             EndpointName=endpoint_name,
                                             Body=payload,
                                             ContentType="text/csv",
                                             Accept="text/csv"
                                            )

# This is the inference response deserialization step
# This is a bytes object
result = response["Body"].read()
# Decoding bytes to a string
result = result.decode("utf-8")
# Converting to list of predictions
result = re.split(",|\n",result)

prediction_df = pd.DataFrame()
prediction_df["Prediction"] = result[:5]
prediction_df["Label"] = test_df["fraud"].iloc[:5].values
prediction_df

若要使用 Amazon CloudWatch 監控端點叫用指標,開啟 SageMaker 主控台。在 Inference (推論) 下方,依次選取 Endpoints (端點) 和 fraud-detect-xgb-endpoint

 

Endpoint details (端點詳細資訊) 頁面的 Monitor (監控) 下方,選擇 View invocation metrics (檢視叫用指標)。剛開始時,您可能只會在指標圖表中看到單個點。但在多次叫用後,您將看到一條和樣本螢幕擷取畫面中類似的線。

Metrics (指標) 頁面顯示多項端點效能指標。您可以選擇不同的時間段 (例如,1 個小時內或 3 個小時內),以便視覺化端點效能。選取任何指標,以查看它在所選時間段內的趨勢。在下一步中,您將選擇其中一項指標來定義自動擴縮政策。

 

 

由於已在端點組態中設定資料擷取,您可以檢查什麼承載被傳送到端點及其回應。擷取的資料將需要一些時間才能被完全上傳到 S3。複製並貼上以下程式碼,以檢查資料擷取是否已完成。

from sagemaker.s3 import S3Downloader
print("Waiting for captures to show up", end="")
for _ in range(90):
    capture_files = sorted(S3Downloader.list(f"{data_capture_uri}/{endpoint_name}"))
    if capture_files:
        capture_file = S3Downloader.read_file(capture_files[-1]).split("\n")
        capture_record = json.loads(capture_file[0])
        if "inferenceId" in capture_record["eventMetadata"]:
            break
    print(".", end="", flush=True)
    time.sleep(1)
print()
print(f"Found {len(capture_files)} Data Capture Files:")

對於每次端點叫用,擷取的資料以 JSON Lines 格式 (一種以新行分隔的格式,用於儲存結構化資料,其中每行為一個 JSON 值) 作為單獨檔案儲存在 S3 中。複製並貼上以下程式碼,以擷取資料擷取檔案。 

capture_files = sorted(S3Downloader.list(f"{data_capture_uri}/{endpoint_name}"))
capture_file = S3Downloader.read_file(capture_files[0]).split("\n")
capture_record = json.loads(capture_file[0])
capture_record

複製並貼上以下程式碼,以便使用 base64 解碼擷取檔案中的資料。這段程式碼會擷取被作為承載傳送的五個測試樣本,以及它們的預測。此功能十分適用於檢查具有模型回應的端點負載,以及監控模型的效能。

input_data = capture_record["captureData"]["endpointInput"]["data"]
output_data = capture_record["captureData"]["endpointOutput"]["data"]
input_data_list = base64.b64decode(input_data).decode("utf-8").split("\n")
print(input_data_list)
output_data_list = base64.b64decode(output_data).decode("utf-8").split("\n")
print(output_data_list)

步驟 5:設定端點的自動擴縮

使用即時推論端點的工作負載通常有低延遲要求。此外,當流量激增時,即時推論端點可能發生 CPU 過載、高延遲或逾時。因此,對容量進行擴縮,從而高效地處理流量變動並實現低延遲顯得非常重要。SageMaker 推論自動擴縮會監控您的工作負載並動態調整執行個體數量,從而以低成本維持穩定而可預測的端點效能。當工作負載增加時,自動擴縮會啟動更多執行個體,而當工作負載減少時,它會移除不必要的執行個體,從而協助您降低運算成本。在本教學中,您將使用 AWS 開發套件 - Boto3 設定端點的自動擴縮。SageMaker 提供多種自動擴縮類型:目標追蹤擴縮、步進擴縮、隨需擴縮和排程擴縮。在本教學中,您將使用目標追蹤擴縮政策。當所選擴縮指標增加並超過所選目標閾值時,該政策會被觸發。

自動擴縮的設定分兩步。首先,您要設定一個擴縮政策,其中需包含每個端點的最小、所需和最大執行個體數量的詳細資訊。複製並貼上以下程式碼,以設定目標追蹤擴縮政策。當流量超過所選閾值 (您將在下一步中進行選擇) 時,將啟動指定最大數量的執行個體。

resp = sm_client.describe_endpoint(EndpointName=endpoint_name)

# SageMaker expects resource id to be provided with the following structure
resource_id = f"endpoint/{endpoint_name}/variant/{resp['ProductionVariants'][0]['VariantName']}"

# Scaling configuration
scaling_config_response = sm_autoscaling_client.register_scalable_target(
                                                          ServiceNamespace="sagemaker",
                                                          ResourceId=resource_id,
                                                          ScalableDimension="sagemaker:variant:DesiredInstanceCount", 
                                                          MinCapacity=1,
                                                          MaxCapacity=2
                                                        )

複製並貼上以下程式碼,以建立擴縮政策。所選的擴縮指標為 SageMakerVariantInvocationsPerInstance,它是某模型變體的每個推論執行個體每分鐘被叫用的平均次數。當此次數超過所選閾值 5 時,自動擴縮便會被觸發。

# Create Scaling Policy
policy_name = f"scaling-policy-{endpoint_name}"
scaling_policy_response = sm_autoscaling_client.put_scaling_policy(
                                                PolicyName=policy_name,
                                                ServiceNamespace="sagemaker",
                                                ResourceId=resource_id,
                                                ScalableDimension="sagemaker:variant:DesiredInstanceCount",
                                                PolicyType="TargetTrackingScaling",
                                                TargetTrackingScalingPolicyConfiguration={
                                                    "TargetValue": 5.0, # Target for avg invocations per minutes
                                                    "PredefinedMetricSpecification": {
                                                        "PredefinedMetricType": "SageMakerVariantInvocationsPerInstance",
                                                    },
                                                    "ScaleInCooldown": 600, # Duration in seconds until scale in
                                                    "ScaleOutCooldown": 60 # Duration in seconds between scale out
                                                }
                                            )

複製並貼上以下程式碼,以擷取擴縮政策的詳細資訊。

response = sm_autoscaling_client.describe_scaling_policies(ServiceNamespace="sagemaker")

pp = pprint.PrettyPrinter(indent=4, depth=4)
for i in response["ScalingPolicies"]:
    pp.pprint(i["PolicyName"])
    print("")
    if("TargetTrackingScalingPolicyConfiguration" in i):
        pp.pprint(i["TargetTrackingScalingPolicyConfiguration"])

複製並貼上以下程式碼,以對端點進行壓力測試。這段程式碼執行 250 秒,並透過傳送從測試資料集中隨機選取的樣本來重複叫用端點。

request_duration = 250
end_time = time.time() + request_duration
print(f"Endpoint will be tested for {request_duration} seconds")
while time.time() < end_time:
    csv_file = io.StringIO()
    test_sample = test_df.drop(["fraud"], axis=1).iloc[[np.random.randint(0, test_df.shape[0])]]
    test_sample.to_csv(csv_file, sep=",", header=False, index=False)
    payload = csv_file.getvalue()
    response = sm_runtime_client.invoke_endpoint(
                                                 EndpointName=endpoint_name,
                                                 Body=payload,
                                                 ContentType="text/csv"
                                                )

您可以使用 Amazon CloudWatch 來監控端點指標。如需包括叫用等的可用端點指標清單,請參閱 SageMaker 端點叫用指標。在 SageMaker 主控台的 Inference (推論) 下方,依次選擇 Endpoints (端點) 和 fraud-detect-xgb-endpoint。 在 Endpoint details (端點詳細資訊) 頁面上,導覽至 Monitor (監控) 區段,然後選擇 View invocation metrics (檢視叫用指標)。Metrics (指標) 頁面上,選取指標清單中的 InvocationsPerInstance (這是您在設定擴縮政策時選擇的監控指標) 和 Invocations (叫用),然後選擇 Graphed metrics (圖表化指標) 標籤。

Graphed metrics (圖表化指標) 頁面上,您可以視覺化的方式檢查端點所收到的流量模式,並變更時間粒度,例如,從預設的 5 分鐘變更為 1 分鐘。 自動擴縮可能需要幾分鐘才能新增第二個執行個體。在新增執行個體後,您將注意到每個執行個體的叫用次數是總叫用次數的一半。

當端點收到增加的承載,您可以透過執行以下程式碼檢查端點的狀態。此程式碼會檢查端點的狀態何時從 InService (服務中) 變更為 Updating (更新中),並追蹤執行個體數量。在幾分鐘後,您將看到狀態從 InService (服務中) 變更為 Updating (更新中),然後再度變回 InService (服務中),但執行個體數量增加。

# Check the instance counts after the endpoint gets more load
response = sm_client.describe_endpoint(EndpointName=endpoint_name)
endpoint_status = response["EndpointStatus"]
request_duration = 250
end_time = time.time() + request_duration
print(f"Waiting for Instance count increase for a max of {request_duration} seconds. Please re run this cell in case the count does not change")
while time.time() < end_time:
    response = sm_client.describe_endpoint(EndpointName=endpoint_name)
    endpoint_status = response["EndpointStatus"]
    instance_count = response["ProductionVariants"][0]["CurrentInstanceCount"]
    print(f"Status: {endpoint_status}")
    print(f"Current Instance count: {instance_count}")
    if (endpoint_status=="InService") and (instance_count>1):
        break
    else:
        time.sleep(15)

步驟 6:清除資源

最佳實務是刪除不再使用的資源,以免產生意外費用。

透過在您的筆記本中執行以下程式碼區塊,刪除您在本教學中建立的模型、端點組態和端點。 如果您不刪除端點,您的帳戶將因為在端點中執行的運算執行個體而持續產生費用。

# Delete model
sm_client.delete_model(ModelName=model_name)

# Delete endpoint configuration
sm_client.delete_endpoint_config(EndpointConfigName=endpoint_config_name)

# Delete endpoint
sm_client.delete_endpoint(EndpointName=endpoint_name)

若要刪除 S3 儲存貯體,請執行以下操作: 

  • 開啟 Amazon S3 主控台。在導覽列上,選擇 Buckets (儲存貯體)、sagemaker-<您的區域>-<您的帳戶 ID>,然後選取 fraud-detect-demo 旁邊的核取方塊。然後選擇 Delete (刪除)。
  • Delete objects (刪除物件) 對話方塊中,確認您已選取要刪除的物件,然後將 permanently delete (永久刪除) 輸入到 Permanently delete objects (永久刪除物件) 確認方塊。
  • 當此操作完成且儲存貯體為空時,您可以透過再次執行相同程序來刪除儲存貯體 sagemaker-<您的區域>-<您的帳戶 ID>

本教學中用於執行筆記本映像的資料科學核心將不斷產生費用,直到您停止核心或執行以下步驟刪除應用程式。 如需詳細資訊,請參閱《Amazon SageMaker 開發人員指南》中的關閉資源

若要刪除 SageMaker Studio 應用程式,請執行以下操作:在 SageMaker Studio 主控台中,選擇 studio-user,然後透過選擇 Delete app (刪除應用程式程式) 來刪除 Apps (應用程式) 下列出的所有應用程式。等待片刻直到 Status (狀態) 變更為 Deleted (已刪除)。

如果您在步驟 1 中使用了現有的 SageMaker Studio 網域,請略過步驟 6 的其餘部分並直接進入「結論」部分。 

如果您在步驟 1 中執行 CloudFormation 範本來建立新的 SageMaker Studio 網域,請繼續執行下列步驟以刪除由 CloudFormation 範本建立的網域、使用者和資源。  

若要開啟 CloudFormation 主控台,請在 AWS Console 搜尋列中輸入 CloudFormation,然後從搜尋結果中選擇 CloudFormation

CloudFormation 窗格中,選擇 Stacks (堆疊)。從狀態下拉式清單中,選取 Active (作用中)。在 Stack name (堆疊名稱) 下,選擇 CFN-SM-IM-Lambda-catalog 開啟堆疊詳細資訊頁面。

CFN-SM-IM-Lambda-catalog 堆疊詳細資訊頁面上,選擇 Delete (刪除) 以刪除在步驟 1 中建立的堆疊及資源。

結論

恭喜您! 您已完成將機器學習模型部署到即時推論端點教學。 

在本教學中,您建立了 SageMaker 模型,並將它部署到了即時推論端點。您使用 AWS 開發套件 - Boto3 API 叫用端點,透過執行樣本推論對端點進行了測試,同時利用資料擷取功能將端點承載和回應儲存到了 S3 中。最後,您使用目標端點叫用指標設定了自動擴縮,以便處理流量的波動。

您可以按照下面的「後續步驟」部分繼續使用 SageMaker 進行機器學習之旅。

本頁對您是否有幫助?

訓練深度學習模型

了解如何建置、訓練和調整 TensorFlow 深度學習模型。
下一步 »

自動建立 ML 模型

了解如何使用 AutoML 在不編寫程式碼的情況下開發 ML 模型。
下一步 »

尋找更多實作教學

探索其他機器學習教學以深入探究。
下一步 »