Azure Machine Learning

機械学習プラットフォームMicrosoftクラウドMLOpsAutoMLAzureエンタープライズ

AI・機械学習プラットフォーム

Azure Machine Learning

概要

Azure Machine Learningは、Microsoftが提供するエンタープライズ向けクラウドベース機械学習プラットフォームです。データサイエンティストや機械学習エンジニアが、機械学習モデルのライフサイクル全体を管理できる包括的なソリューションを提供します。Azure Machine Learning StudioのWebベースUI、Python SDK v2、Azure CLIを通じて、AutoML、カスタムモデル開発、MLOps、デプロイメントまでを統一されたプラットフォームで実現できます。

詳細

Azure Machine LearningはMicrosoftのクラウドインフラストラクチャ上に構築された、機械学習プロジェクトの開発から運用までを支援するフルマネージドサービスです。2025年時点では、Python SDK v2による改良されたAPIエクスペリエンス、MLflowとの完全統合、強化されたAutoML機能、エンタープライズ級のセキュリティとガバナンス機能を提供しています。

主要な特徴として、Azure Machine Learning Studioと呼ばれるWebベースの統合開発環境、自動化された機械学習(AutoML)機能、MLOpsパイプライン、リアルタイム・バッチ推論エンドポイント、Azureエコシステムとの深い統合があります。

プラットフォームは多様な機械学習タスクをサポートし、分類、回帰、時系列予測、自然言語処理、コンピュータビジョンタスクに対応しています。また、Jupyter Notebook環境、VSCode統合、コラボレーション機能により、チーム開発を効率的に進められます。

メリット・デメリット

メリット

  • 包括的なMLOpsソリューション: モデル開発からデプロイ、監視まで一貫したワークフローを提供
  • AutoML機能: コーディング知識が少なくても高品質なモデルを自動生成
  • スケーラブルな計算リソース: 需要に応じたクラスタの自動スケーリング
  • Azureエコシステム統合: Azure Synapse Analytics、Azure DevOps、Power BIとのシームレスな連携
  • エンタープライズ級セキュリティ: Azure Active Directory、RBAC、VNet統合による堅牢なセキュリティ
  • MLflow完全サポート: オープンソース標準への準拠とベンダーロックイン回避
  • No-codeデプロイメント: MLflowモデルの簡単なエンドポイント展開

デメリット

  • 学習コストの高さ: 多機能であるが故の初期習得の複雑さ
  • コスト管理の複雑性: 計算リソースとストレージの課金体系の理解が必要
  • Azure依存: Microsoftエコシステム外での利用に制限
  • リージョン制限: 一部の高度な機能が特定のAzureリージョンでのみ利用可能
  • SDK v1からv2への移行: 既存プロジェクトの移行作業が必要(SDK v1は2026年6月終了予定)

参考ページ

書き方の例

基本的なワークスペース設定と接続

from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential

# Azure Machine Learningワークスペースへの接続
credential = DefaultAzureCredential()
ml_client = MLClient(
    credential=credential,
    subscription_id="your-subscription-id",
    resource_group_name="your-resource-group",
    workspace_name="your-workspace-name"
)

# ワークスペース詳細の取得
workspace = ml_client.workspaces.get(name="your-workspace-name")
print(f"ワークスペース: {workspace.name}")
print(f"場所: {workspace.location}")
print(f"リソースグループ: {workspace.resource_group}")

データ管理とデータセット

from azure.ai.ml.entities import Data
from azure.ai.ml.constants import AssetTypes

# データアセットの登録
data_asset = Data(
    name="customer-data",
    version="1",
    description="顧客分析用データセット",
    path="./data/customer_data.csv",
    type=AssetTypes.URI_FILE
)

# データアセットの作成
ml_client.data.create_or_update(data_asset)

# 既存データアセットの取得
customer_data = ml_client.data.get(name="customer-data", version="1")
print(f"データパス: {customer_data.path}")

# データストアからのデータ読み込み
import pandas as pd
df = pd.read_csv(customer_data.path)
print(f"データ形状: {df.shape}")
print(df.head())

AutoMLとカスタムモデル訓練

from azure.ai.ml import automl
from azure.ai.ml.entities import Model
from azure.ai.ml.constants import AssetTypes

# AutoML分類タスクの設定
classification_job = automl.classification(
    compute="cpu-cluster",
    experiment_name="customer-segmentation",
    training_data=customer_data,
    target_column_name="customer_segment",
    primary_metric="accuracy",
    n_cross_validations=5,
    enable_model_explainability=True
)

# AutoMLタスクの実行
classification_job = ml_client.create_or_update(classification_job)
print(f"AutoMLジョブID: {classification_job.name}")

# カスタムモデル訓練ジョブ
from azure.ai.ml.entities import Command, Environment

# 訓練スクリプトの実行環境定義
environment = Environment(
    name="sklearn-env",
    description="Scikit-learn環境",
    conda_file="./environment.yml",
    image="mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04"
)

# 訓練ジョブの定義
job = Command(
    code="./src",
    command="python train.py --data ${{inputs.training_data}} --output ${{outputs.model}}",
    environment=environment,
    compute="cpu-cluster",
    inputs={
        "training_data": customer_data
    },
    outputs={
        "model": "./outputs/model"
    }
)

# 訓練ジョブの実行
training_job = ml_client.create_or_update(job)

モデルデプロイとリアルタイム推論

from azure.ai.ml.entities import (
    ManagedOnlineEndpoint,
    ManagedOnlineDeployment,
    CodeConfiguration
)

# オンラインエンドポイントの作成
endpoint = ManagedOnlineEndpoint(
    name="customer-segmentation-endpoint",
    description="顧客セグメンテーションAPI",
    auth_mode="key"
)

ml_client.online_endpoints.begin_create_or_update(endpoint).result()

# モデルデプロイメント
deployment = ManagedOnlineDeployment(
    name="blue",
    endpoint_name="customer-segmentation-endpoint",
    model=best_model,
    instance_type="Standard_F2s_v2",
    instance_count=1
)

ml_client.online_deployments.begin_create_or_update(deployment).result()

# エンドポイントへのトラフィック割り当て
endpoint.traffic = {"blue": 100}
ml_client.online_endpoints.begin_create_or_update(endpoint).result()

# 推論テスト
import json
test_data = {
    "data": [
        [25, 50000, 2, 1],  # 年齢、収入、購入回数、プレミアム会員
        [45, 75000, 5, 0]
    ]
}

response = ml_client.online_endpoints.invoke(
    endpoint_name="customer-segmentation-endpoint",
    request_file=json.dumps(test_data)
)
print(f"予測結果: {response}")

MLOpsとAzure DevOps統合

from azure.ai.ml.entities import Pipeline, PipelineJob
from azure.ai.ml.dsl import pipeline

@pipeline(
    description="顧客セグメンテーションMLOpsパイプライン",
    default_compute="cpu-cluster"
)
def customer_segmentation_pipeline(pipeline_input_data):
    # データ前処理ステップ
    data_prep_step = data_prep_component(
        input_data=pipeline_input_data
    )
    
    # モデル訓練ステップ
    train_step = train_component(
        training_data=data_prep_step.outputs.processed_data
    )
    
    # モデル評価ステップ
    evaluate_step = evaluate_component(
        model=train_step.outputs.model,
        test_data=data_prep_step.outputs.test_data
    )
    
    # モデル登録ステップ(評価基準を満たした場合)
    register_step = register_component(
        model=train_step.outputs.model,
        evaluation_results=evaluate_step.outputs.metrics
    )
    
    return {
        "trained_model": register_step.outputs.registered_model
    }

# パイプラインの作成と実行
pipeline_job = customer_segmentation_pipeline(
    pipeline_input_data=customer_data
)

pipeline_job = ml_client.jobs.create_or_update(
    pipeline_job,
    experiment_name="customer-segmentation-mlops"
)

# Azure DevOpsとの統合(YAML設定例)
"""
# azure-pipelines.yml
trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: AzureCLI@2
  inputs:
    azureSubscription: 'Azure ML Service Connection'
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      az ml job create --file pipeline.yml --resource-group $(resourceGroup) --workspace-name $(workspaceName)
"""

高度な機能とAzure AI Services統合

# MLflowトラッキング統合
import mlflow
from azure.ai.ml import MLClient

# MLflowトラッキングの設定
mlflow.set_tracking_uri(ml_client.workspaces.get().mlflow_tracking_uri)
mlflow.set_experiment("customer-analysis")

with mlflow.start_run() as run:
    # モデル訓練
    model = train_model(X_train, y_train)
    
    # メトリクスのログ
    mlflow.log_metric("accuracy", accuracy_score(y_test, predictions))
    mlflow.log_metric("f1_score", f1_score(y_test, predictions, average='weighted'))
    
    # パラメータのログ
    mlflow.log_param("algorithm", "RandomForest")
    mlflow.log_param("n_estimators", 100)
    
    # モデルの登録
    mlflow.sklearn.log_model(
        model, 
        "model",
        registered_model_name="customer-segmentation-model"
    )

# Azure Cognitive Servicesとの統合
from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# テキスト分析の前処理
text_analytics_client = TextAnalyticsClient(
    endpoint="https://your-text-analytics.cognitiveservices.azure.com/",
    credential=AzureKeyCredential("your-key")
)

def preprocess_customer_feedback(feedback_texts):
    # 感情分析
    sentiment_results = text_analytics_client.analyze_sentiment(
        documents=feedback_texts
    )
    
    # キーフレーズ抽出
    key_phrases = text_analytics_client.extract_key_phrases(
        documents=feedback_texts
    )
    
    # 機械学習モデルの特徴量として統合
    processed_features = []
    for sentiment, phrases in zip(sentiment_results, key_phrases):
        features = {
            'sentiment_score': sentiment.confidence_scores.positive,
            'negative_score': sentiment.confidence_scores.negative,
            'key_phrase_count': len(phrases.key_phrases)
        }
        processed_features.append(features)
    
    return processed_features

# バッチ推論エンドポイントの活用
from azure.ai.ml.entities import BatchEndpoint, BatchDeployment

# バッチエンドポイントの作成
batch_endpoint = BatchEndpoint(
    name="customer-batch-scoring",
    description="大量顧客データのバッチ処理"
)

ml_client.batch_endpoints.begin_create_or_update(batch_endpoint).result()

# バッチ推論ジョブの実行
batch_job = ml_client.batch_endpoints.invoke(
    endpoint_name="customer-batch-scoring",
    input=large_customer_dataset,
    deployment_name="production"
)

# モデルの継続的監視
from azure.ai.ml.entities import DataDriftDetector

drift_detector = DataDriftDetector(
    name="customer-data-drift",
    baseline_data=training_data,
    target_data=production_data,
    compute="cpu-cluster",
    frequency="Day",
    alert_email="[email protected]"
)

ml_client.data_drift_detectors.create_or_update(drift_detector)