Amazon SageMaker AI と MLflow を用いた判別型機械学習モデルの監視
AWS Machine Learning Blog は、Amazon SageMaker AI と MLflow を活用して、分類・回帰モデルのデータドリフトとモデルドリフトを監視し、精度低下を防ぐ実践的な手法を解説している。
キーポイント
ドリフトの2大要因の定義
入力データの統計的性質の変化である「データドリフト」と、予測精度の低下を引き起こす「モデルドリフト」の明確な区別と原因を解説している。
SageMaker AI と MLflow の連携
トレーニング時のベースライン統計とプロダクション環境でのデータを比較することで、両者のドリフトを検出する具体的なアーキテクチャを示している。
予防的介入の重要性
精度が問題になる前に監視を行い、消費者行動の変化や経済状況の変動などに対処するための早期介入の必要性を強調している。
重要な引用
The effectiveness and accuracy of machine learning (ML) models decreases almost as soon as the training job finishes.
Data drift refers to changes in the statistical properties of the input data.
Model drift refers to changes in the accuracy of predictions produced by the model because the probabilistic patterns learned by the model no longer fit the data coming in.
影響分析・編集コメントを表示
影響分析
本記事は、生成系AI(LLM)の監視が注目される中、依然としてビジネスの根幹を支える分類・回帰モデルの運用課題に焦点を当てた実用的なガイダンスを提供しています。AWS のエコシステム内で標準的なツールを組み合わせて信頼性を高めるアプローチを示すことで、現場の ML エンジニアにとって即座に適用可能な価値があります。
編集コメント
生成系AIの監視が注目される中、従来型の予測モデルにおける運用課題への具体的な解決策を示しており、実務担当者にとって非常に有益な情報です。
機械学習(ML)モデルの有効性と精度は、トレーニングジョブが完了した直後からほぼ低下し始めます。消費者行動の変化、新製品のリリース、センサー技術のアップグレード、そして変化する経済・政治情勢など、モデルがトレーニング中に学習したパターンや確率を変化させる制御不能な要因の例が挙げられます。生産環境で展開されたモデルを精度と基本統計値の変化について積極的に監視することで、精度低下が問題となる前に介入することができます。モデル監視は、レイテンシ、アプリケーションの可用性、およびシステム全体の課題を特定するために使用されるその他の指標を追跡する AI 観測性ツール(AI observability tools)と組み合わせることができます。
本記事では、分類および回帰ユースケースに使用される判別型機械学習モデル(discriminative machine learning models)に焦点を当てます。生成 AI モデルについては、Amazon SageMaker AI エンドポイント推論における大規模言語モデル(LLM)の運用準備完了リアルタイム監視ソリューション を参照してください。判別型 ML モデルの品質低下を引き起こす要因は、おおまかに 2 つのカテゴリーに分類できます:
- データドリフトとは、入力データの統計的特性の変化を指します。これは、上流のデータソースにおける予期せぬ変化により列のデータ型が整数から浮動小数点に変化するといった単純なものから、全く新しい製品ラインがリリースされるような複雑なケースまで様々です。データドリフトは、トレーニングデータセットに対してベースライン統計量を計算し、これを時間経過とともに収集された生産環境のデータで計算した同じ統計量と比較することで測定できます。
- モデルドリフトとは、モデルが学習した確率的パターンが入力されるデータに適合しなくなったために、モデルが生み出す予測の精度が変化する現象を指します。例えば、経済の改善に伴う消費者行動の変化などが原因となり得ます。モデルドリフトは、正解ラベル(ground truth labels)を集めてモデル品質指標を計算し、これらの指標をモデルトレーニングプロセス中に計算された同じ指標と比較することで測定できます。

図 1: データドリフトとモデルドリフトが ML ワークフローにおいてどのように位置づけられるか
Amazon SageMaker AI は、組織が判別型および生成型の機械学習(ML)モデルを構築、トレーニング、デプロイ、管理するためのフルマネージド型サービスです。SageMaker AI はフルマネージドですが、よりカスタマイズ性の高いアプローチが必要な場合もあります。例えば、コスト効果の高い方法でモデルのライフサイクル全体を管理したい、マネージドサービスがサポートしていない独自のユースケースを監視したい、またはモデル監視を他の UI や観測パイプラインに統合したいといった要望があるかもしれません。そこで本記事では、データドリフトおよびモデルドリフトの計算のために、オープンソースの Evidently Python ライブラリ と Amazon SageMaker AI with MLflow を基盤としたモデル監視アーキテクチャをご紹介します。このモデル監視ソリューションの結果は、お好みのダッシュボードに統合したり、関連するステークホルダーへアラートを送信したり、自動的なモデル再トレーニングパイプラインをトリガーしたりするために使用できます。
ソリューションの概要
本ソリューションでは、モデルのトレーニングからデプロイに至るまでの機械学習ワークフローにおけるモデル監視の実装方法を示します。図 2 は、バッチ推論ユースケースにおけるワークフローを示しており、Slack へのアラート送信および MLflow でのモデル結果の可視化までを含みます。

図 2: バッチ推論用のモデル監視ワークフロー
ワークフローは以下の手順から構成されています:
- Amazon Simple Storage Service (Amazon S3) バケットから入力データを用いてモデルを学習させるトレーニングジョブ。同じトレーニングジョブはモデルメトリクスも計算し、これらは MLflow に保存できます。モデルの学習に使用されたベースラインデータセットは、本番環境でのモニタリングに利用できるよう、S3 内に別途保存されます。
- 本番ワークロードにおける推論のためのバッチトランスフォーム。バッチトランスフォームジョブの結果は S3 バケットに格納されます。
- バッチトランスフォームジョブの結果、および元のデータセットとモデルメトリクスを用いて、オープンソースの Evidently プリセット (Evidently presets) を使用し、データドリフトとモデル品質メトリクスを計算する処理ジョブが実行されます。なお、Evidently はモデルメトリクスを計算しますが、トレーニングランからの前回のメトリクスと比較して直接モデルドリフトを計算するわけではありません。ただし、カスタムコードを追加することで、この処理ジョブを拡張しモデルドリフトの計算を行うことが可能です。
バッチ変換および処理ジョブは、Amazon EventBridge Scheduler を使用してスケジュール管理可能なパイプラインにラップできます。
- すべての監視メトリクスと Evidently レポートは MLflow に保存され、ここでは実行履歴を時間経過とともに追跡し、実行間での結果を比較したり、レポートを可視化したりすることができます。
- 任意で、ドリフトが検出された場合、パイプラインは Amazon Simple Notification Service (Amazon SNS) を介してメールによりユーザーに通知を送信するトリガーを発動できます。
モデルデプロイに リアルタイムエンドポイント が使用されるユースケースでも、同様のアプローチを採用可能です。図 3 はリアルタイムエンドポイントのワークフローを示しています。重要な違いは、エンドポイントの入力と出力を S3 バケットにログ記録するために データキャプチャ が有効化されている必要がある点です。処理ジョブの代わりに、このアーキテクチャでは AWS Lambda 関数を使用して監視コードをデプロイします。どちらのアーキテクチャも、ご自身の好みに応じて処理ジョブまたは Lambda のいずれかを使用できます。データドリフトおよびモデルドリフトを計算する AWS Lambda 関数は、定期スケジュールで実行することも可能です。また、エンドポイントからのデータが S3 バケットに到着した際にトリガーして実行することもできます。

図 3: リアルタイムエンドポイントにおけるモデル監視ワークフロー
このリアルタイムエンドポイントのパターンは、Amazon SageMaker Hyperpod でも利用可能です。ここでは、モデル学習およびモデル推論に使用するためのクラスターをプロビジョニングできます。データキャプチャは、エンドポイントレベル、ロードバランサーレベル、またはモデルポッドレベルで有効化できます。推論リクエストとレスポンスは自動的に S3 バケットに書き込まれるため、そこからアクセスしてモデル監視を行うことができます。
上記の 2 つの図はいずれもモデル監視プロセスのみを対象としていますが、通常、モデル監視はより広範な MLOps ワークフローの一部として実装されます。図 4 は、このモデル監視ソリューションがエンドツーエンドの MLOps シナリオにどのように組み込まれるかを示しています。ここでは、ドリフト計算に使用される処理ジョブが、CI/CD ワークフローを通じてエンドポイントと共にデプロイされます。SageMaker AI を用いた MLOps の実装に関する詳細については、Amazon SageMaker AI を活用した企業向け MLOps 基盤ロードマップをご覧ください。

図 4: モデル監視が MLOps アーキテクチャとどのように統合されるか
ウォークスルー
このセクションでは、バッチトランスフォーム用のモデル監視ソリューションを設定するための手順を段階的に説明します。リアルタイムエンドポイント のサンプルを含む他の例については、完全なリポジトリ をご覧ください。
前提条件
このウォークスルーの手順に従う前に、以下の準備が必要です:
- このサービスが利用可能な AWS リージョン内の Amazon SageMaker AI ドメイン。
- SageMaker Studio 上の MLflow アプリ。
- SageMaker Studio 内の JupyterLab スペース(本ソリューションには ml.t3.medium インスタンスで十分です)。
- JupyterLab 上のソリューションリポジトリのコピー。スペースが起動した後、リポジトリをクローンしてください。
ウォークスルーを続けるには、ノートブック predictive_ml_experimentation_data_model_monitoring_evidently.ipynb を開いてください。なお、本ソリューションでは SageMaker Python SDK v3 を使用しています。DefaultMLFlowApp を使用する場合は、ノートブックコードが自動的に正しいアプリを識別します。それ以外の場合は、MLflow アプリの名前を指定してコードを編集してください。
モデルのトレーニングと推論
例示のノートブックでは、UCI Machine Learning Repository からの Bank Marketing dataset を使用しています。このデータセットには、ポルトガルの銀行を代表して行われたマーケティング電話に関する情報が含まれており、顧客が定期預金に加入するかどうかを予測することを目的としています。これは二値分類のユースケースであり、ターゲット変数は顧客が加入した場合に 1、加入しなかった場合に 0 の値を持ちます。
ノートブックの前半では、データのクリーニング、処理、およびトレーニング、バリデーション、テストセットへの分割が行われます。XGBoost モデルがトレーニングおよびバリデーションデータセット上で学習され、ログとメトリクスは MLflow に送信され、最終的なモデルオブジェクトは MLflow のモデルレジストリに登録されます。
このデータ処理およびモデル学習セクションにおける 2 つの重要なアクションが、後続のプロダクション環境でのモニタリングのためにモデルを準備します:
- トレーニングデータセットは、データドリフト(データ分布の変化)の計算に使用されるベースラインデータセットとして S3 バケットに保存されます。
- モデルメトリクスは MLflow に保存され、モデルドリフト(モデル性能の変化)の計算に利用できます。

図 5: MLflow で表示されるモデルメトリクス(精度、再現率、AUC)
次に、ノートブックはトレーニングジョブの出力からモデルオブジェクトを作成し、テスト用特徴量をモデルに通して推論を行うバッチトランスフォームジョブを設定します。
データドリフトとモデル品質の計算
Evidently には、さまざまな種類の データドリフト を計算するためのプリセットが用意されており、これらは特定の機械学習ユースケースに合わせてカスタマイズすることが可能です。サンプルノートブックでは DataDriftPreset と DataSummaryPreset を使用し、Evidently レポート(HTML 形式および JSON 形式)を MLflow に保存するヘルパー関数を作成するとともに、特定のドリフト値を抽出して MLflow のメトリクスとして個別に保存します。これにより、異なる実行結果の比較や、特定の数値に基づいたアラートの生成が可能になります。

図 6: MLflow のアーティファクトとしての Evidently データドリフトレポート

図 7: MLflow のデータドリフトメトリクスとパラメータ
各データドリフト計算を MLflow の実行(run)として保存するもう一つの利点は、モデル名やトレーニングジョブの名前、データセットのサイズなど、重要な情報をパラメータとして追加できることです。
Evidently は、モデル品質の計算用のプリセットも提供しています。このノートブックでは ClassificationPreset を使用しており、これはモデルの予測結果と正解データセットに基づいて、精度(accuracy)、適合率(precision)、再現率(recall)、F1 スコアなどを算出します。ClassificationPreset が持つ広範な指標群の代わりに、Evidently では カスタムレポート もサポートしており、特定のユースケースに最も関連性の高い指標を計算対象として指定できます。例えば、サンプルノートブックで使用されているマーケティングデータセットには不均衡なラベルが存在するため、精度よりも適合率、再現率、AUC(曲線下面積)の方がより関連性の高い指標となります。
データモニタリングと同様に、モデル品質に関する Evidently のレポートはアーティファクトとして MLflow に追加され、個々の指標は MLflow メトリクスとして抽出可能です。ただし、Evidently はモデルドリフト(元のトレーニングジョブから得られた指標と、予測結果から計算された指標との差)を算出するものではありません。しかし、モニタリングコードにドリフト計算を追加することは可能であり、その例については
原文を表示
The effectiveness and accuracy of machine learning (ML) models decreases almost as soon as the training job finishes. Changes in consumer behavior, releases of new products, upgrades in sensor technology, and a shifting economic and political landscape are all examples of uncontrollable factors that change the patterns and probabilities the model learned during training. By actively monitoring models deployed in production for changes in accuracy and baseline statistics, you can intervene before the drop in accuracy becomes problematic. Model monitoring can be combined with AI observability tools that track latency, application availability, and other metrics used to identify problems in the overall system.
This post focuses on discriminative machine learning models used for classification and regression use cases. For generative AI models, see Production-Ready Real-Time Monitoring Solution for LLMs on Amazon SageMaker AI Endpoint inference. The factors that cause a reduction in quality for discriminative ML models can be broadly split into two categories:
- Data drift refers to changes in the statistical properties of the input data. It can be as simple as an unexpected change in an upstream data source that changes a column from integer to float data type, or as complex as entirely new product lines being released. You can measure data drift by calculating baseline statistics for the training dataset and comparing these to the same statistics calculated on data gathered over time in production.
- Model drift refers to changes in the accuracy of predictions produced by the model because the probabilistic patterns learned by the model no longer fit the data coming in. This can be caused, for example, by changes in consumer behavior because of an improving economy. You can measure model drift by gathering the ground truth labels to calculate model quality metrics, and comparing these metrics to the same metrics calculated during the model training process.

Figure 1: How data drift and model drift fit in an ML workflow
Amazon SageMaker AI is a fully managed machine learning service that helps organizations build, train, deploy, and manage both discriminative and generative ML models. Although SageMaker AI is fully managed, you might need a more customizable approach. For example, you might want to manage the entire modeling life cycle cost-effectively, monitor unique use cases that managed services do not support, or integrate your model monitoring into other UI or observability pipelines. Therefore, this post introduces a model monitoring architecture based on the open source Evidently Python library and Amazon SageMaker AI with MLflow for calculating data and model drift. The results of this model monitoring solution can be integrated into your preferred dashboard, can be used to send alerts to relevant stakeholders, or can trigger automatic model retraining pipelines.
Solution overview
This solution demonstrates how to implement model monitoring in the machine learning workflow, from model training to model deployment. Figure 2 shows the workflow for a batch inference use case, up to and including alerting in Slack and visualizing the model results in MLflow.

Figure 2: Model monitoring workflow for batch inference
The workflow consists of the following steps:
- A training job to train the model on input data from an Amazon Simple Storage Service (Amazon S3) bucket. The same training job calculates model metrics, which can be stored in MLflow. The baseline dataset used to train the model is stored separately in S3 so it can be used to monitor the model in production.
- Batch transform for inference on production workloads. The results of a batch transform job are stored in an S3 bucket.
- The results of the batch transform job, and the original dataset and model metrics, are used in a processing job to calculate data drift and model quality metrics using open source Evidently presets. Note that Evidently calculates model metrics. It does not calculate model drift directly by comparing the metrics to the previous metrics from the training run. However, the processing job can be extended with custom code to calculate model drift. The batch transform and processing job can be wrapped in a pipeline for scheduling using Amazon EventBridge Scheduler.
- All monitoring metrics and Evidently reports are stored in MLflow where you can track runs over time, compare results between runs, and visualize the report.
- Optionally, if drift is detected, the pipeline can trigger an Amazon Simple Notification Service (Amazon SNS) notification to alert users by email.
You can take a similar approach for use cases where real-time endpoints are used for model deployment. Figure 3 shows the workflow for real-time endpoints. The key difference is that the endpoint must have data capture enabled, which logs the inputs and outputs of the endpoint to an S3 bucket. Instead of a processing job, this architecture uses AWS Lambda functions to deploy the monitoring code. Both architectures can use either processing jobs or Lambda, based on your preference. The AWS Lambda functions that calculate data and model drift can run on a regular schedule. You can also trigger them when data from the endpoint lands in the S3 bucket.

Figure 3: Model monitoring workflow for real-time endpoints
This pattern for real-time endpoints can also be used with Amazon SageMaker Hyperpod, where you can provision clusters to use for model training as well as model inference. You can enable data capture for Hyperpod at the endpoint level, at the load balancer level, or at the model pod level. Inference requests and responses are automatically written to an S3 bucket, where you can access them to perform model monitoring.
Both previous diagrams focus only on the model monitoring process. However, model monitoring is normally implemented as part of a larger MLOps workflow. Figure 4 shows how this model monitoring solution fits in an end-to-end MLOps scenario, where the processing job used to calculate drift is deployed alongside the endpoint through a CI/CD workflow. For more information on implementing MLOps with SageMaker AI, see MLOps foundation roadmap for enterprises with Amazon SageMaker AI.

Figure 4: How model monitoring integrates with an MLOps architecture
Walkthrough
This section provides a step-by-step explanation for setting up the model monitoring solution for batch transform. See the full repository for other examples, including a sample for real-time endpoints.
Prerequisites
Before following the steps in this walkthrough, you will need:
- An Amazon SageMaker AI domain in an AWS Region where this service is available.
- An MLflow App in SageMaker Studio.
- A JupyterLab space within SageMaker Studio (an ml.t3.medium instance is sufficient for this solution).
- A copy of the solution repository on JupyterLab. Clone the repository after the space has started.
To continue with the walkthrough, open the notebook predictive_ml_experimentation_data_model_monitoring_evidently.ipynb. Note that the solution uses the SageMaker Python SDK v3. If you use the DefaultMLFlowApp, the notebook code identifies the correct app automatically. Otherwise, edit the code with the name of your MLflow App.
Model training and inference
The example notebook uses the Bank Marketing dataset from the UCI Machine Learning Repository. This dataset contains information about marketing phone calls made on behalf of a Portuguese bank, with the goal of predicting if the customer will subscribe to a term deposit. It is a binary classification use case where the target variable has a value of 1 if the customer subscribed and 0 if a customer did not subscribe.
In the first half of the notebook, the data is cleaned, processed, and split into training, validation, and test sets. An XGBoost model is trained on the training and validation datasets, with logs and metrics sent to MLflow and the final model object registered in the MLflow model registry.
Two key actions in this data processing and model training section set up the model for monitoring later in production:
- The training dataset is stored as the baseline dataset in an S3 bucket, which you use to calculate data drift.
- The model metrics are stored in MLflow, which can be used for model drift calculations.

Figure 5: Model metrics (precision, recall, AUC) displayed in MLflow
Next, the notebook creates the model object from the training job output and sets up a batch transform job which runs the test features through the model for inference.
Calculating data drift and model quality
Evidently has various presets for calculating different types of data drift, all of which can be customized to suit the particular ML use case. The sample notebook uses the DataDriftPreset and DataSummaryPreset and creates a helper function to save the Evidently reports (both HTML and JSON) in MLflow and extracts specific drift values to save separately as metrics in MLflow. This enables you to compare different runs or generate alerts based on certain values.

Figure 6: An Evidently data drift report as an artifact in MLflow

Figure 7: Data drift metrics and parameters in MLflow
Another advantage of saving each data drift calculation as a run in MLflow is that it allows us to add parameters such as the model name, the name of the training job, the size of the dataset, and other important information.
Evidently also provides presets for calculating model quality. This notebook uses the ClassificationPreset, which calculates accuracy, precision, recall, F1 score, and more based on model predictions and the ground truth dataset. Instead of the ClassificationPreset with its broad range of metrics, Evidently also supports custom reports that you can target to calculate the metrics most relevant to a particular use case. For example, because of imbalanced labels in the marketing dataset used in the sample notebook, accuracy is a less relevant metric than precision, recall, and AUC.
Similar to data monitoring, the Evidently reports for model quality are added as artifacts to MLflow, and the individual metrics can be extracted into MLflow metrics. Note that Evidently does not calculate model drift, meaning the difference between metrics from the original training job and metrics calculated from the predictions. However, you can add drift calculations in the monitoring code, and we provide an example of this in the
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み