使用 Amazon SageMaker Studio 建立機器學習流程
Amazon SageMaker Studio 是 AWS 於今年 re:invent 推出適用於機器學習的 整合式開發環境(IDE),讓使用者可以輕鬆 建立、訓練、偵錯、部署並監控機器學習模型 ,並專注於開發機器學習模型,而非環境的設置與開發工具的轉換。
- 在 Jupyter 筆記本中編寫和執行程式碼
- 建立和訓練機器學習模型
- 部署模型並監控模型預測的性能
- 調校並改進機器學習模型成效

目前 Amazon SageMaker Studio 僅在美國東部 (俄亥俄州) 地區 us-east-2 中可使用。
Amazon SageMaker Studio 有提供以下功能,透過這些服務可以有效建立機器學習模型並減少開發時間:
- Amazon SageMaker Studio Notebooks
- Amazon SageMaker Experiments
- Amazon SageMaker Autopilot
- Amazon SageMaker Debugger
- Amazon SageMaker Model Monitor
Amazon SageMaker Studio Notebooks
Amazon SageMaker Studio Notebooks 是 Amazon SageMaker Studio 內的筆記本,提供多人同時協作功能,並且依需求快速切換不同運算資源。即使訓練結束運算資源被關閉,依然可以查看實驗結果。
Amazon SageMaker Studio Notebooks 主要提供四種環境供使用者選擇:
- Data Science 環境:內建多種 Python 資料科學常用套件,如 NumPy、SciKit Learn⋯⋯等。
- 原始 Python 環境
- 基於 MXNet CPU 優化環境
- 基於 TensorFlow CPU 優化環境
- 基於 PyTorch CPU 優化環境
介紹完 Amazon SageMaker Studio Notebooks,想必許多用過 SageMaker 的老手會思考這與 AWS 原有的 Amazon SageMaker Notebooks 有什麼差異,而 Amazon SageMaker Studio Notebooks 與 Amazon SageMaker Notebooks 相比具有以下優點:
- 啟動速度比 Amazon SageMaker Notebooks 快 5-10 倍。
- 透過 URL 建立 snapshot 與團隊成員共享程式碼、程式開發環境與實驗結果。
- 內建最新版本的 Amazon SageMaker SDK,可以在 Studio 的 IDE 中直接使用並建立、訓練、調校和監控模型。
- 使用 AWS SSO 作為身份驗證,使用 AWS 為開發團隊所提供獨一無二的 URL 登入並運行筆記本,而無需登入 AWS 主控台。
- Amazon SageMaker Studio Notebooks 為了資料科學預配置一組環境,讓使用者可以更快地開始進行資料科學工作,如資料前處理、建模。
Amazon SageMaker Autopilot
Amazon SageMaker Autopilot 的推出讓對機器學習不熟練的使用者也可以輕易訓練出自己的機器學習模型,包含 分類模型 (Classification) 與 迴歸模型 (Regression) 。使用者僅需將資料集(須為 csv 格式)上傳並選定要預測之欄位, Autopilot 會探索不同演算法、超參數、資料前處理方式的組合,進而找到較為準確的機器學習模型。
在 Amazon SageMaker Autopilot 主要可應用於下列問題:
- Linear regression : 利用一函數與多個 features 的權重來預測的 target 的數值且預測欄位為一個連續型的數值,即為線性迴歸,如房價預測,在已有坪數、臥室數量、有無停車格等資訊後,藉此預測售出價格。
- Binary classification : 二元分類為將常見的分類問題,如信用卡詐欺偵測、癌症偵測等此種非 0 即 1 的分類問題。
- Multi-class classification : 多類別為模型可能做出的預測結果,如電影分類模型可能會有:劇情、動作、愛請、動畫等分類,此種模型不僅可以預測類別,同時會回傳每個類別的機率。
- Automatic problem type detection : 使用 AutoML API 設定問題類型時,可以選擇定義問題類型,或讓 Autopilot 自動偵測它。
當使用者利用 Autopilot 進行訓練時,會建立 experiment 與多個 trials,每個 trials 會儲存因不同演算法、超參數、資料前處理方式所產生的數據結果,藉此提供使用者更有效率的比較模型方法。
當我們建立 Autopilot 實驗時,會建立兩個 Notebook 並儲存在 S3,第一個為 Data Exploration Notebook,第二個為 Candidate Generation Notebook。
- Data Exploration Notebook 主要呈現對資料集的分析,這當中會去分析資料及是否有遺失值,是否該使用平均值或中位數進行替換,以及對於 String 的分類進行 one-hot encoding 轉換。若因分類過多而導致資料維度過高,則會應用 PCA 或其他降維技術進行 Data Reduction。
- Candidate Generation Notebook 則會提供建議的演算法並在給定參數範圍進行 Hyperparameter Optimization (HPO),,在此可選擇僅 (1) 產生此份 Notebook 或 (2) 產生並執行 AutoML,第一種可決定僅執行特定演算法組合後決定最優演算法,第二種則是直接顯示最優演算法為何。

Amazon SageMaker Experiments
在建立機器學習模型的過程中,利用紙本或 Excel 記錄每個參數對於模型的影響十分麻煩,而 Amazon SageMaker Experiments 可追蹤並且評估每次訓練模型的準確度與資料及改變對模型的影響,同時亦可記錄演算法與超參數對於此次實驗的影響。
Amazon SageMaker Experiments 中主要分為 experiment 與 trials, experiment 為本次要觀察之實驗, 而 trials 則為實驗中每次調整目標變數而有不同結果的試驗。

Amazon SageMaker Experiments 記錄與追蹤實驗主要分為兩種,一種為 Automated Tracking,一種則為 Manual Tracking 。Automated Tracking 是自動追蹤 Amazon SageMaker Autopilot 的實驗,並把每次嘗試不同演算法、參數、模型評估指標的訓練工作視為一個 trial,讓使用者可以追蹤每次試驗並管理機器學習模型。而 Manual Tracking
則是使用 Amazon SageMaker Python SDK 所提供的 API 記錄與追蹤在 Amazon SageMaker Notebooks 與 Amazon SageMaker Studio Notebooks 運行的機器學習模型與訓練工作。
Amazon SageMaker Experiments 將自動擷取模型輸入的參數、設定與實驗結果並儲存在實驗中,並且透過視覺化方式比較實驗結果,藉此找到最佳模型。藉由 AWS 所提供手寫字辨識的範例 – mnist-handwritten-digits-classification-experiment.ipynb,在此我們直接用此作為範例。
- 在筆記本安裝 Amazon SageMaker Experiments SDK。
!{sys.executable} -m pip install sagemaker-experiments
- 將 Amazon SageMaker 與 Experiments 套件匯入此筆記本。
import sagemaker
from sagemaker import get_execution_role
from sagemaker.session import Session
from sagemaker.analytics import ExperimentAnalytics
from smexperiments.experiment import Experiment
from smexperiments.trial import Trial
from smexperiments.trial_component import TrialComponent
from smexperiments.tracker import Tracker
- Tracker 是用來追蹤資料集的轉換工作,同時將正規化參數和 URI 記錄到 Amazon S3 中。
with Tracker.create(display_name="Preprocessing", sagemaker_boto_client=sm) as tracker:
tracker.log_parameters({
"normalization_mean": 0.1307,
"normalization_std": 0.3081,
})
tracker.log_input(name="mnist-dataset", media_type="s3/uri", value=inputs)
- 建立
mnist-hand-written-digits-classification-xxxxxxxx
的實驗並追蹤實驗。
mnist_experiment = Experiment.create(
experiment_name=f"mnist-hand-written-digits-classification-{int(time.time())}",
description="Classification of mnist hand-written digits",
sagemaker_boto_client=sm)
print(mnist_experiment)
- 之後建立各個試驗以測試使用不同的
hidden channels
(2, 5, 10, 20, 32)對實驗最後結果的影響,而其他參數均保持一樣,並且用train loss
、test loss
、test accuracy
作為衡量模型好壞的指標。
for i, num_hidden_channel in enumerate([2, 5, 10, 20, 32]):
# create trial
trial_name = f"cnn-training-job-{num_hidden_channel}-hidden-channels-{int(time.time())}"
cnn_trial = Trial.create(
trial_name=trial_name,
experiment_name=mnist_experiment.experiment_name,
sagemaker_boto_client=sm,
)
hidden_channel_trial_name_map[num_hidden_channel] = trial_name
# associate the proprocessing trial component with the current trial
cnn_trial.add_trial_component(preprocessing_trial_component)
# all input configurations, parameters, and metrics specified in estimator
# definition are automatically tracked
estimator = PyTorch(
entry_point='./mnist.py',
role=role,
sagemaker_session=sagemaker.Session(sagemaker_client=sm),
framework_version='1.1.0',
train_instance_count=1,
train_instance_type='ml.c4.xlarge',
hyperparameters={
'epochs': 2,
'backend': 'gloo',
'hidden_channels': num_hidden_channel,
'dropout': 0.2,
'optimizer': 'sgd'
},
metric_definitions=[
{'Name':'train:loss', 'Regex':'Train Loss: (.*?);'},
{'Name':'test:loss', 'Regex':'Test Average loss: (.*?),'},
{'Name':'test:accuracy', 'Regex':'Test Accuracy: (.*?)%;'}
],
enable_sagemaker_metrics=True,
)
cnn_training_job_name = "cnn-training-job-{}".format(int(time.time()))
# Now associate the estimator with the Experiment and Trial
estimator.fit(
inputs={'training': inputs},
job_name=cnn_training_job_name,
experiment_config={
"TrialName": cnn_trial.trial_name,
"TrialComponentDisplayName": "Training",
},
wait=True,
)
# give it a while before dispatching the next training job
time.sleep(2)
接下來我們可以利用 SageMaker Experiment List 將實驗結果以 視覺化 方式呈現,在此我們比較當 hidden channels
值為 2, 5, 10, 20, 32 時的測試的平均準確度。在右側選單欄提供 Time series 跟一般統計資料兩種類別供使用者繪製比較圖表。

Amazon SageMaker Debugger
Amazon SageMaker Debugger 藉由監控、記錄並分析機器學習模型中的 Tensor 與神經網路的狀態,
使用者可透過設定不同的 Rule 監控模型,當 SageMaker Debugger 偵測到 overfitting、vanishing gradient、class imbalance 等問題時,將及時發出警示給使用者。使用者可以利用 Amazon SageMaker Studio 視覺畫的介面查看 Tenosr 與神經網路在訓練過程的狀態,進而偵錯並改善模型。

當 Rule 被觸發時,Amazon SageMaker Studio 會顯示被觸發 Rule 的 Log 紀錄,藉此分析訓練異常原因。

Amazon SageMaker Debugger 的 Rule 分為兩種,分別為 Built-in Rules 與 Custom Rules
-
Built-in Rules 包含四種場景:
- 深度學習框架: 如 dead relu、vanishing gradient、權重更新比率、Tensor 是否有無限值或 NaN⋯⋯等。
- 深度學習框架與 XGBoost 演算法:分類不均、overfitting、overtraining、混淆矩陣⋯⋯等。
- 深度學習應用:檢查圖片輸入值是否有進行正規化、特定字詞在字串中出現的比率。
- XGBoost 演算法:分類樹的深度。
如下,直接在匯入 SageMaker Debugger 套件,並設定使用 ExplodingTensor、VanishingGradient 兩種 Rule。
from sagemaker.debugger import Rule, CollectionConfig, rule_configs exploding_tensor_rule = Rule.sagemaker( base_config=rule_configs.exploding_tensor(), rule_parameters={"collection_names": "weights,losses"}, collections_to_save=[ CollectionConfig("weights"), CollectionConfig("losses") ] ) vanishing_gradient_rule = Rule.sagemaker( base_config=rule_configs.vanishing_gradient() ) import sagemaker as sm sagemaker_estimator = sm.tensorflow.TensorFlow( entry_point='src/mnist.py', role=sm.get_execution_role(), base_job_name='smdebug-demo-job', train_instance_count=1, train_instance_type="ml.m4.xlarge", framework_version="1.15", py_version="py3", # smdebug-specific arguments below rules=[exploding_tensor_rule, vanishing_gradient_rule], ) sagemaker_estimator.fit()
- Custome Rule:由使用者自行定義監控的 Rule,如下設定要監控的指標為 gradients,取得每個步驟的 gradients 並取平均看是否大於 threshold。
custom_rule = Rule.custom( name='MyCustomRule', # used to identify the rule # rule evaluator container image image_uri='759209512951.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rule-evaluator:latest', instance_type='ml.t3.medium', # instance type to run the rule evaluation on source='rules/my_custom_rule.py', # path to the rule source file rule_to_invoke='CustomGradientRule', # name of the class to invoke in the rule source file volume_size_in_gb=30, # EBS volume size required to be attached to the rule evaluation instance collections_to_save=[CollectionConfig("gradients")], # collections to be analyzed by the rule. since this is a first party collection we fetch it as above rule_parameters={ "threshold": "20.0" # this will be used to intialize 'threshold' param in your constructor } ) estimator = TensorFlow( role=sagemaker.get_execution_role(), base_job_name='smdebug-custom-rule-demo-tf-keras', train_instance_count=1, train_instance_type='ml.p2.xlarge', entry_point=entrypoint_script, framework_version='1.15', py_version='py3', train_max_run=3600, script_mode=True, ## New parameter rules = [custom_rule] ) estimator.fit(wait=False)
Amazon SageMaker Model Monitor
在部署機器學習模型後,模型準確率會隨著時間而下降,可能是因為訓練資料與實際資料具有落差,SageMaker Model Monitor 透過不斷監控與分析預測的 Request,並利用內建的規則確認 Request 所傳送資料是否具有異常,如資料為異常值則會發出警示提醒使用者,藉此保持模型的準確性,以下為 SageMaker Model Monitor 實際運作流程圖。

SageMaker Model Monitor 主要可分為四個流程,分別為擷取資料、建立基準、設定監控排程以及解釋結果。
- 擷取資料:擷取 request 傳入機器學習模型的資料。
- 建立 Baseline:建立 Baseline 作為接收到新資料時的比較對象,並利用 Deequ 測量資料中的資料質量。
-
設定監控排程:可以按指定的時間頻率監控並分析期間內的資料,與 Baseline 進行比較,並設定產生哪種異常報告,在此可用 cron 的表達式 (
cron(0 17/12 ? * * *)
) 設定排程。 -
解釋結果:查看最終結果並將最新數據與 Baseline 進行比較,並把報告的異常情況傳送給 Amazon CloudWatch。
結論
過去開發機器學習從安裝環境到建立機器學習模型往往耗費許多時間,但 Amazon SageMaker Studio 免去了安裝環境的麻煩,同時又利用其他功能節省了建立一個有效機器學習模型的時間。Amazon SageMaker Autopilot 對於機器學習新手是一個很好的起點,只需要給資料及然後透過 Autopilot 設定好問題種類及可作預測。至於機器學習老手,Amazon SageMaker Debugger 讓我們在訓練模型期間可以即時了解遇到的問題,並且直接調整,不用等待模型訓練完成。與 Amazon SageMaker Model Monitor 相比,Amazon SageMaker Debugger 是監控模型的訓練過程,而 Amazon SageMaker Model Monitor 則是監控模型部署後是否需要調整,兩者皆可以設定 Rule 去觸發。另外 AWS 有提供這些服務的 Sample Notebook,有興趣的都可以到這個連結試玩看看。