Claude Code for Azure Machine Learning: ML Platform on Azure — Claude Skills 360 Blog
Blog / AI / Claude Code for Azure Machine Learning: ML Platform on Azure
AI

Claude Code for Azure Machine Learning: ML Platform on Azure

Published: September 4, 2027
Read time: 5 min read
By: Claude Skills 360

Azure Machine Learning is Microsoft’s cloud ML platform. pip install azure-ai-ml azure-identity. ml_client = MLClient(DefaultAzureCredential(), subscription_id, resource_group, workspace). CLI v2: az ml job create -f job.yaml. Training: command(code="./src", command="python train.py ${{inputs.train_data}}", environment="azureml:sklearn-env:1", compute="cpu-cluster", inputs={"train_data": Input(type="uri_folder", path="azureml:churn-train:1")}). Environment: Environment(name="sklearn-env", conda_file="conda.yaml", image="mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu22.04"). Compute: AmlCompute(name="cpu-cluster", size="STANDARD_DS3_V2", min_instances=0, max_instances=4). MLflow autolog: mlflow.sklearn.autolog() inside the training script logs params/metrics/model automatically. Model registration: ml_client.models.create_or_update(Model(path="./outputs/model", name="churn-model", type=AssetTypes.MLFLOW_MODEL)). Online Endpoint: ManagedOnlineEndpoint(name="churn-endpoint", auth_mode="key"), then ManagedOnlineDeployment(name="blue", endpoint_name="churn-endpoint", model="azureml:churn-model:1", instance_type="Standard_DS2_v2", instance_count=1). Traffic split: endpoint.traffic = {"blue": 80, "green": 20}. Batch endpoint: BatchEndpoint, BatchDeployment with min_instances/max_instances. ml_client.jobs.stream(job_name) tails logs. Pipeline job: pipeline_job = pipeline(train=train_step, evaluate=eval_step), ml_client.jobs.create_or_update(pipeline_job). Feature Store: fs_client = FeatureStoreClient(...), feature_set_spec.yaml with source and feature_transformation_code. Claude Code generates Azure ML job YAMLs, training scripts, endpoint configs, pipeline definitions, and TypeScript prediction clients.

CLAUDE.md for Azure ML

## Azure ML Stack
- SDK: azure-ai-ml >= 1.15 + azure-identity
- Client: MLClient(DefaultAzureCredential(), subscription_id, resource_group, workspace_name)
- Training: command(code, command, environment, compute, inputs) → ml_client.jobs.create_or_update()
- Environment: Environment(name, conda_file, image) → ml_client.environments.create_or_update()
- Compute: AmlCompute(name, size, min_instances=0, max_instances) → ml_client.compute.begin_create_or_update()
- Endpoint: ManagedOnlineEndpoint + ManagedOnlineDeployment → traffic split dict
- Model: ml_client.models.create_or_update(Model(path, name, type=AssetTypes.MLFLOW_MODEL))
- CLI: az ml job create -f job.yaml / az ml online-endpoint invoke --name ...

Training Script with MLflow

# src/train.py — Azure ML training script with MLflow autolog
from __future__ import annotations
import argparse
import json
import os

import mlflow
import mlflow.sklearn
import pandas as pd
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--train_data",    type=str, required=True)
    parser.add_argument("--test_data",     type=str, default="")
    parser.add_argument("--n_estimators",  type=int,   default=200)
    parser.add_argument("--learning_rate", type=float, default=0.05)
    parser.add_argument("--max_depth",     type=int,   default=4)
    parser.add_argument("--registered_model_name", type=str, default="churn-model")
    return parser.parse_args()


def main():
    args = parse_args()

    # Azure ML + MLflow integration — auto-connects when running in Azure ML job
    mlflow.sklearn.autolog()

    feature_cols = ["age", "tenure_days", "monthly_spend", "support_tickets", "last_login_days"]
    target_col   = "churned"

    train_df = pd.read_csv(os.path.join(args.train_data, "train.csv"))
    test_df  = (
        pd.read_csv(os.path.join(args.test_data, "test.csv"))
        if args.test_data
        else train_df.sample(frac=0.2, random_state=42)
    )

    X_train = train_df[feature_cols].values
    y_train = train_df[target_col].values
    X_test  = test_df[feature_cols].values
    y_test  = test_df[target_col].values

    with mlflow.start_run():
        pipeline = Pipeline([
            ("scaler", StandardScaler()),
            ("clf",    GradientBoostingClassifier(
                n_estimators=args.n_estimators,
                learning_rate=args.learning_rate,
                max_depth=args.max_depth,
                random_state=42,
            )),
        ])
        pipeline.fit(X_train, y_train)

        y_proba = pipeline.predict_proba(X_test)[:, 1]
        y_pred  = pipeline.predict(X_test)
        auc     = roc_auc_score(y_test, y_proba)

        mlflow.log_metric("auc", auc)
        mlflow.log_params({
            "n_estimators":  args.n_estimators,
            "learning_rate": args.learning_rate,
            "max_depth":     args.max_depth,
        })

        print(f"\nAUC-ROC: {auc:.4f}")
        print(classification_report(y_test, y_pred))

        # Register model in Azure ML Model Registry via MLflow
        mlflow.sklearn.log_model(
            sk_model=pipeline,
            artifact_path="model",
            registered_model_name=args.registered_model_name,
        )


if __name__ == "__main__":
    main()

Azure ML SDK v2 Workflow

# ml/azure_ml_workflow.py — training, registration, and endpoint deployment
from __future__ import annotations
import os
from azure.ai.ml import MLClient, Input, Output, command
from azure.ai.ml.entities import (
    AmlCompute,
    Environment,
    ManagedOnlineEndpoint,
    ManagedOnlineDeployment,
    Model,
    BuildContext,
)
from azure.ai.ml.constants import AssetTypes
from azure.identity import DefaultAzureCredential

SUBSCRIPTION   = os.environ.get("AZURE_SUBSCRIPTION_ID", "")
RESOURCE_GROUP = os.environ.get("AZURE_RESOURCE_GROUP", "ml-rg")
WORKSPACE      = os.environ.get("AZURE_ML_WORKSPACE", "ml-workspace")


def get_client() -> MLClient:
    return MLClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION,
        resource_group_name=RESOURCE_GROUP,
        workspace_name=WORKSPACE,
    )


# ── Compute ──────────────────────────────────────────────────────────────────

def ensure_compute(ml_client: MLClient, name: str = "cpu-cluster") -> None:
    """Create compute cluster if it doesn't exist."""
    try:
        ml_client.compute.get(name)
        print(f"Compute cluster '{name}' already exists")
    except Exception:
        cluster = AmlCompute(
            name=name,
            type="amlcompute",
            size="Standard_DS3_v2",
            min_instances=0,
            max_instances=4,
            idle_time_before_scale_down=120,
            tier="Dedicated",
        )
        ml_client.compute.begin_create_or_update(cluster).result()
        print(f"Created compute cluster: {name}")


# ── Environment ──────────────────────────────────────────────────────────────

def ensure_environment(ml_client: MLClient) -> str:
    """Register the training environment."""
    env = Environment(
        name="sklearn-mlflow-env",
        version="1",
        description="sklearn + MLflow for churn model training",
        conda_file={
            "name": "sklearn-env",
            "channels": ["defaults", "conda-forge"],
            "dependencies": [
                "python=3.11",
                "pip",
                {"pip": [
                    "scikit-learn>=1.2",
                    "pandas>=2.0",
                    "mlflow>=2.10",
                    "azure-ai-ml>=1.15",
                ]},
            ],
        },
        image="mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu22.04:latest",
    )
    env = ml_client.environments.create_or_update(env)
    return f"azureml:{env.name}:{env.version}"


# ── Training job ─────────────────────────────────────────────────────────────

def submit_training_job(
    ml_client:       MLClient,
    environment_id:  str,
    compute_name:    str = "cpu-cluster",
) -> str:
    """Submit a training command job and return the run name."""
    job = command(
        code="./src",
        command=(
            "python train.py "
            "--train_data ${{inputs.train_data}} "
            "--test_data ${{inputs.test_data}} "
            "--n_estimators 200 --learning_rate 0.05 --max_depth 4"
        ),
        environment=environment_id,
        compute=compute_name,
        display_name="churn-model-training",
        experiment_name="churn-classification",
        inputs={
            "train_data": Input(type="uri_folder", path="azureml:churn-train:1"),
            "test_data":  Input(type="uri_folder", path="azureml:churn-test:1"),
        },
    )
    returned_job = ml_client.jobs.create_or_update(job)
    ml_client.jobs.stream(returned_job.name)   # Tail logs
    print(f"Job completed: {returned_job.name}")
    return returned_job.name


# ── Online Endpoint ───────────────────────────────────────────────────────────

def deploy_online_endpoint(
    ml_client:    MLClient,
    model_name:   str = "churn-model",
    model_version: str = "1",
) -> str:
    """Create endpoint and deploy model with blue/green split."""
    endpoint = ManagedOnlineEndpoint(
        name="churn-endpoint",
        description="Churn prediction endpoint",
        auth_mode="key",
        tags={"env": "production"},
    )
    ml_client.online_endpoints.begin_create_or_update(endpoint).result()

    deployment = ManagedOnlineDeployment(
        name="blue",
        endpoint_name="churn-endpoint",
        model=f"azureml:{model_name}:{model_version}",
        instance_type="Standard_DS2_v2",
        instance_count=1,
        liveness_probe={"initial_delay": 10, "period": 10, "timeout": 2},
    )
    ml_client.online_deployments.begin_create_or_update(deployment).result()

    # Route 100% traffic to blue
    endpoint = ml_client.online_endpoints.get("churn-endpoint")
    endpoint.traffic = {"blue": 100}
    ml_client.online_endpoints.begin_create_or_update(endpoint).result()

    keys = ml_client.online_endpoints.get_keys("churn-endpoint")
    print(f"Endpoint deployed. API key: {keys.primary_key[:8]}...")
    return "churn-endpoint"

CLI v2 YAML Job

# jobs/train_job.yaml — Azure ML CLI v2 job definition
$schema: https://azuremlschemas.azureedge.net/latest/commandJob.schema.json
type: command

display_name: churn-model-training
experiment_name: churn-classification
description: Train churn classifier with MLflow tracking

code: ../src
command: >-
  python train.py
  --train_data ${{inputs.train_data}}
  --n_estimators 200
  --learning_rate 0.05
  --max_depth 4

environment: azureml:sklearn-mlflow-env:1
compute: azureml:cpu-cluster

inputs:
  train_data:
    type: uri_folder
    path: azureml:churn-train:1

resources:
  instance_count: 1

TypeScript Client

// lib/azure-ml/client.ts — invoke Azure ML Online Endpoint
const ENDPOINT_URL = process.env.AZURE_ML_ENDPOINT_URL ?? ""
const API_KEY      = process.env.AZURE_ML_API_KEY ?? ""

export type ChurnInput = {
  age:             number
  tenure_days:     number
  monthly_spend:   number
  support_tickets: number
  last_login_days: number
}

export type ChurnPrediction = {
  churn_probability: number
  risk_tier:         string
}

export async function predictChurn(records: ChurnInput[]): Promise<ChurnPrediction[]> {
  const res = await fetch(ENDPOINT_URL, {
    method:  "POST",
    headers: {
      "Content-Type":  "application/json",
      "Authorization": `Bearer ${API_KEY}`,
    },
    body: JSON.stringify({
      input_data: {
        columns: ["age", "tenure_days", "monthly_spend", "support_tickets", "last_login_days"],
        data:     records.map(r => [r.age, r.tenure_days, r.monthly_spend, r.support_tickets, r.last_login_days]),
      },
    }),
  })
  if (!res.ok) throw new Error(`Azure ML ${res.status}: ${await res.text()}`)
  const predictions: number[] = await res.json()
  return predictions.map(prob => ({
    churn_probability: Math.round(prob * 10000) / 10000,
    risk_tier: prob > 0.7 ? "HIGH" : prob > 0.3 ? "MEDIUM" : "LOW",
  }))
}

For the Vertex AI alternative when your data and infrastructure live on Google Cloud with BigQuery as the data warehouse — Vertex AI’s AutoML and BigQuery ML integration are natural while Azure ML is the right choice for Microsoft-ecosystem teams with Azure Data Factory pipelines, Azure Blob Storage data lakes, Active Directory authentication, and existing Azure Databricks or Synapse Analytics deployments. For the SageMaker alternative when your workloads are AWS-native with S3 data lakes and existing IAM — SageMaker’s deep AWS service integration contrasts with Azure ML’s enterprise Active Directory SSO and Azure DevOps CI/CD integration that makes it natural for organizations already invested in the Microsoft cloud stack. The Claude Skills 360 bundle includes Azure ML skill sets covering command jobs, environment management, online endpoint deployment, pipeline YAML specs, and TypeScript prediction clients. Start with the free tier to try Azure ML workflow generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free