{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Fraud Detection for Automobile Claims: Train, Check Bias, Tune, Record Lineage, and Register a Model" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "This notebook's CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook. \n", "\n", "![This us-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-2/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Background\n", "\n", "This notebook is the third part of a series of notebooks that will demonstrate how to prepare, train, and deploy a model that detects fradulent auto claims. In this notebook, we will show how you can assess pre-training and post-training bias with SageMaker Clarify, Train the Model using XGBoost on SageMaker, and then finally deposit it in the Model Registry, along with the Lineage of Artifacts that were created along the way: data, code and model metadata. You can choose to run this notebook by itself or in sequence with the other notebooks listed below. Please see the [README.md](README.md) for more information about this use case implemented by this series of notebooks. \n", "\n", "\n", "1. [Fraud Detection for Automobile Claims: Data Exploration](./0-AutoClaimFraudDetection.ipynb)\n", "1. [Fraud Detection for Automobile Claims: Data Preparation, Process, and Store Features](./1-data-prep-e2e.ipynb)\n", "1. **[Fraud Detection for Automobile Claims: Train, Check Bias, Tune, Record Lineage, and Register a Model](./2-lineage-train-assess-bias-tune-registry-e2e.ipynb)**\n", "1. [Fraud Detection for Automobile Claims: Mitigate Bias, Train, Register, and Deploy Unbiased Model](./3-mitigate-bias-train-model2-registry-e2e.ipynb)\n", "\n", "## Contents\n", "\n", "1. [Architecture for the ML Lifecycle Stage: Train, Check Bias, Tune, Record Lineage, Register Model](#Architecture-for-the-ML-Lifecycle-Stage:-Train,-Check-Bias,-Tune,-Record-Lineage,-Register-Model)\n", "1. [Train a Model using XGBoost](#Train-a-Model-using-XGBoost)\n", "1. [Model Lineage with Artifacts and Associations](#Model-Lineage-with-Artifacts-and-Associations)\n", "1. [Evaluate Model for Bias with Clarify](#Evaluate-Model-for-Bias-with-Clarify)\n", "1. [Deposit Model and Lineage in SageMaker Model Registry](#Deposit-Model-and-Lineage-in-SageMaker-Model-Registry)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Architecture for the ML Lifecycle Stage: Train, Check Bias, Tune, Record Lineage, Register Model\n", "----\n", "\n", "![train-assess-tune-register](./images/e2e-2-pipeline-v3b.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Install required and/or update libraries" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python -m pip install -Uq pip\n", "!python -m pip install -q awswrangler==2.2.0 imbalanced-learn==0.7.0 sagemaker==2.41.0 boto3==1.17.70" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Import libraries" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import time\n", "import boto3\n", "import sagemaker\n", "import numpy as np\n", "import pandas as pd\n", "import awswrangler as wr\n", "\n", "from sagemaker.xgboost.estimator import XGBoost\n", "from model_package_src.inference_specification import InferenceSpecification" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set region, boto3 and SageMaker SDK variables" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# You can change this to a region of your choice\n", "import sagemaker\n", "\n", "region = sagemaker.Session().boto_region_name\n", "print(\"Using AWS Region: {}\".format(region))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "boto3.setup_default_session(region_name=region)\n", "\n", "boto_session = boto3.Session(region_name=region)\n", "\n", "s3_client = boto3.client(\"s3\", region_name=region)\n", "\n", "sagemaker_boto_client = boto_session.client(\"sagemaker\")\n", "\n", "sagemaker_session = sagemaker.session.Session(\n", " boto_session=boto_session, sagemaker_client=sagemaker_boto_client\n", ")\n", "\n", "sagemaker_role = sagemaker.get_execution_role()\n", "\n", "account_id = boto3.client(\"sts\").get_caller_identity()[\"Account\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# variables used for parameterizing the notebook run\n", "bucket = sagemaker_session.default_bucket()\n", "prefix = \"fraud-detect-demo\"\n", "\n", "estimator_output_path = f\"s3://{bucket}/{prefix}/training_jobs\"\n", "train_instance_count = 1\n", "train_instance_type = \"ml.m4.xlarge\"\n", "\n", "bias_report_1_output_path = f\"s3://{bucket}/{prefix}/clarify-output/bias_1\"\n", "\n", "\n", "xgb_model_name = \"xgb-insurance-claims-fraud-model\"\n", "train_instance_count = 1\n", "train_instance_type = \"ml.m4.xlarge\"\n", "predictor_instance_count = 1\n", "predictor_instance_type = \"ml.c5.xlarge\"\n", "batch_transform_instance_count = 1\n", "batch_transform_instance_type = \"ml.c5.xlarge\"\n", "claify_instance_count = 1\n", "clairfy_instance_type = \"ml.c5.xlarge\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Store Data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "train_data_uri = f\"s3://{bucket}/{prefix}/data/train/train.csv\"\n", "test_data_uri = f\"s3://{bucket}/{prefix}/data/test/test.csv\"\n", "\n", "\n", "s3_client.upload_file(\n", " Filename=\"data/train.csv\", Bucket=bucket, Key=f\"{prefix}/data/train/train.csv\"\n", ")\n", "s3_client.upload_file(Filename=\"data/test.csv\", Bucket=bucket, Key=f\"{prefix}/data/test/test.csv\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train a Model using XGBoost\n", "----\n", "\n", "Once the training and test datasets have been persisted in S3, you can start training a model by defining which SageMaker Estimator you'd like to use. For this guide, you will use the [XGBoost Open Source Framework](https://sagemaker.readthedocs.io/en/stable/frameworks/xgboost/xgboost.html) to train your model. This estimator is accessed via the SageMaker SDK, but mirrors the open source version of the [XGBoost Python package](https://xgboost.readthedocs.io/en/latest/python/index.html). Any functioanlity provided by the XGBoost Python package can be implemented in your training script." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set the hyperparameters\n", "These are the parameters which will be sent to our training script in order to train the model. Although they are all defined as \"hyperparameters\" here, they can encompass XGBoost's [Learning Task Parameters](https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters), [Tree Booster Parameters](https://xgboost.readthedocs.io/en/latest/parameter.html#parameters-for-tree-booster), or any other parameters you'd like to configure for XGBoost." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hyperparameters = {\n", " \"max_depth\": \"3\",\n", " \"eta\": \"0.2\",\n", " \"objective\": \"binary:logistic\",\n", " \"num_round\": \"100\",\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create and fit the estimator\n", "If you want to explore the breadth of functionailty offered by the SageMaker XGBoost Framework you can read about all the configuration parameters by referencing the inhereting classes. The XGBoost class inherets from the Framework class and Framework inherets from the EstimatorBase class:\n", "* [XGBoost Estimator documentation](https://sagemaker.readthedocs.io/en/stable/frameworks/xgboost/xgboost.html#sagemaker.xgboost.estimator.XGBoost)\n", "* [Framework documentation](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Framework)\n", "* [EstimatorBase documentation](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.EstimatorBase)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xgb_estimator = XGBoost(\n", " entry_point=\"xgboost_starter_script.py\",\n", " output_path=estimator_output_path,\n", " code_location=estimator_output_path,\n", " hyperparameters=hyperparameters,\n", " role=sagemaker_role,\n", " instance_count=train_instance_count,\n", " instance_type=train_instance_type,\n", " framework_version=\"1.0-1\",\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "if \"training_job_1_name\" not in locals():\n", " xgb_estimator.fit(inputs={\"train\": train_data_uri})\n", " training_job_1_name = xgb_estimator.latest_training_job.job_name\n", "\n", "else:\n", " print(f\"Using previous training job: {training_job_1_name}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Model Lineage with Artifacts and Associations\n", "----\n", "\n", "Amazon SageMaker ML Lineage Tracking creates and stores information about the steps of a machine learning (ML) workflow from data preparation to model deployment. With the tracking information you can reproduce the workflow steps, track model and dataset lineage, and establish model governance and audit standards. With SageMaker Lineage Tracking data scientists and model builders can do the following:\n", "* Keep a running history of model discovery experiments.\n", "* Establish model governance by tracking model lineage artifacts for auditing and compliance verification.\n", "* Clone and rerun workflows to experiment with what-if scenarios while developing models.\n", "* Share a workflow that colleagues can reproduce and enhance (for example, while collaborating on solving a business problem).\n", "* Clone and rerun workflows with additional debugging or logging routines, or new input variations for troubleshooting issues in production models.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Register artifacts" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although the `xgb_estimator` object retains much the data we need to learn about how the model was trained, it is, in fact, an ephermeral object which SageMaker does not persist and cannot be re-instantiated at a later time. Although we lose some of its convieneces once it is gone, we can still get back all the data we need by accessing the training jobs it once created." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "training_job_1_info = sagemaker_boto_client.describe_training_job(\n", " TrainingJobName=training_job_1_name\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Code artifact" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# return any existing artifact which match the our training job's code arn\n", "# ====>\n", "\n", "# extract the training code uri and check if it's an exisiting artifact\n", "code_s3_uri = training_job_1_info[\"HyperParameters\"][\"sagemaker_submit_directory\"]\n", "\n", "matching_artifacts = list(\n", " sagemaker.lineage.artifact.Artifact.list(\n", " source_uri=code_s3_uri, sagemaker_session=sagemaker_session\n", " )\n", ")\n", "\n", "# use existing arifact if it's already been created, otherwise create a new artifact\n", "if matching_artifacts:\n", " code_artifact = matching_artifacts[0]\n", " print(f\"Using existing artifact: {code_artifact.artifact_arn}\")\n", "else:\n", " code_artifact = sagemaker.lineage.artifact.Artifact.create(\n", " artifact_name=\"TrainingScript\",\n", " source_uri=code_s3_uri,\n", " artifact_type=\"Code\",\n", " sagemaker_session=sagemaker_session,\n", " )\n", " print(f\"Create artifact {code_artifact.artifact_arn}: SUCCESSFUL\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Training data artifact" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "training_data_s3_uri = training_job_1_info[\"InputDataConfig\"][0][\"DataSource\"][\"S3DataSource\"][\n", " \"S3Uri\"\n", "]\n", "\n", "matching_artifacts = list(\n", " sagemaker.lineage.artifact.Artifact.list(\n", " source_uri=training_data_s3_uri, sagemaker_session=sagemaker_session\n", " )\n", ")\n", "\n", "if matching_artifacts:\n", " training_data_artifact = matching_artifacts[0]\n", " print(f\"Using existing artifact: {training_data_artifact.artifact_arn}\")\n", "else:\n", " training_data_artifact = sagemaker.lineage.artifact.Artifact.create(\n", " artifact_name=\"TrainingData\",\n", " source_uri=training_data_s3_uri,\n", " artifact_type=\"Dataset\",\n", " sagemaker_session=sagemaker_session,\n", " )\n", " print(f\"Create artifact {training_data_artifact.artifact_arn}: SUCCESSFUL\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Model artifact" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trained_model_s3_uri = training_job_1_info[\"ModelArtifacts\"][\"S3ModelArtifacts\"]\n", "\n", "matching_artifacts = list(\n", " sagemaker.lineage.artifact.Artifact.list(\n", " source_uri=trained_model_s3_uri, sagemaker_session=sagemaker_session\n", " )\n", ")\n", "\n", "if matching_artifacts:\n", " model_artifact = matching_artifacts[0]\n", " print(f\"Using existing artifact: {model_artifact.artifact_arn}\")\n", "else:\n", " model_artifact = sagemaker.lineage.artifact.Artifact.create(\n", " artifact_name=\"TrainedModel\",\n", " source_uri=trained_model_s3_uri,\n", " artifact_type=\"Model\",\n", " sagemaker_session=sagemaker_session,\n", " )\n", " print(f\"Create artifact {model_artifact.artifact_arn}: SUCCESSFUL\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set artifact associations" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trial_component = sagemaker_boto_client.describe_trial_component(\n", " TrialComponentName=training_job_1_name + \"-aws-training-job\"\n", ")\n", "trial_component_arn = trial_component[\"TrialComponentArn\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Input artifacts" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "input_artifacts = [code_artifact, training_data_artifact]\n", "\n", "for a in input_artifacts:\n", " try:\n", " sagemaker.lineage.association.Association.create(\n", " source_arn=a.artifact_arn,\n", " destination_arn=trial_component_arn,\n", " association_type=\"ContributedTo\",\n", " sagemaker_session=sagemaker_session,\n", " )\n", " print(f\"Association with {a.artifact_type}: SUCCEESFUL\")\n", " except:\n", " print(f\"Association already exists with {a.artifact_type}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Output artifacts" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "output_artifacts = [model_artifact]\n", "\n", "for a in output_artifacts:\n", " try:\n", " sagemaker.lineage.association.Association.create(\n", " source_arn=a.artifact_arn,\n", " destination_arn=trial_component_arn,\n", " association_type=\"Produced\",\n", " sagemaker_session=sagemaker_session,\n", " )\n", " print(f\"Association with {a.artifact_type}: SUCCESSFUL\")\n", " except:\n", " print(f\"Association already exists with {a.artifact_type}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluate Model for Bias with Clarify\n", "----\n", "\n", "Amazon SageMaker Clarify helps improve your machine learning (ML) models by detecting potential bias and helping explain the predictions that models make. It helps you identify various types of bias in pretraining data and in posttraining that can emerge during model training or when the model is in production. SageMaker Clarify helps explain how these models make predictions using a feature attribution approach. It also monitors inferences models make in production for bias or feature attribution drift. The fairness and explainability functionality provided by SageMaker Clarify provides components that help AWS customers build less biased and more understandable machine learning models. It also provides tools to help you generate model governance reports which you can use to inform risk and compliance teams, and external regulators. \n", "\n", "You can reference the [SageMaker Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-fairness-and-explainability.html) for more information about SageMaker Clarify." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create model from estimator" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model_1_name = f\"{prefix}-xgboost-pre-smote\"\n", "model_matches = sagemaker_boto_client.list_models(NameContains=model_1_name)[\"Models\"]\n", "\n", "if not model_matches:\n", " model_1 = sagemaker_session.create_model_from_job(\n", " name=model_1_name,\n", " training_job_name=training_job_1_info[\"TrainingJobName\"],\n", " role=sagemaker_role,\n", " image_uri=training_job_1_info[\"AlgorithmSpecification\"][\"TrainingImage\"],\n", " )\n", "else:\n", " print(f\"Model {model_1_name} already exists.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Check for data set bias and model bias\n", "\n", "With SageMaker, we can check for pre-training and post-training bias. Pre-training metrics show pre-existing bias in that data, while post-training metrics show bias in the predictions from the model. Using the SageMaker SDK, we can specify which groups we want to check bias across and which metrics we'd like to show. \n", "\n", "To run the full Clarify job, you must un-comment the code in the cell below. Running the job will take ~15 minutes. If you wish to save time, you can view the results in the next cell after which loads a pre-generated output if no bias job was run." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "train_cols = wr.s3.read_csv(training_data_s3_uri).columns.to_list()\n", "\n", "clarify_processor = sagemaker.clarify.SageMakerClarifyProcessor(\n", " role=sagemaker_role,\n", " instance_count=1,\n", " instance_type=\"ml.c4.xlarge\",\n", " sagemaker_session=sagemaker_session,\n", ")\n", "\n", "bias_data_config = sagemaker.clarify.DataConfig(\n", " s3_data_input_path=train_data_uri,\n", " s3_output_path=bias_report_1_output_path,\n", " label=\"fraud\",\n", " headers=train_cols,\n", " dataset_type=\"text/csv\",\n", ")\n", "\n", "model_config = sagemaker.clarify.ModelConfig(\n", " model_name=model_1_name,\n", " instance_type=train_instance_type,\n", " instance_count=1,\n", " accept_type=\"text/csv\",\n", ")\n", "\n", "predictions_config = sagemaker.clarify.ModelPredictedLabelConfig(probability_threshold=0.5)\n", "\n", "bias_config = sagemaker.clarify.BiasConfig(\n", " label_values_or_threshold=[0],\n", " facet_name=\"customer_gender_female\",\n", " facet_values_or_threshold=[1],\n", ")\n", "\n", "# un-comment the code below to run the whole job\n", "\n", "# if 'clarify_bias_job_1_name' not in locals():\n", "\n", "# clarify_processor.run_bias(\n", "# data_config=bias_data_config,\n", "# bias_config=bias_config,\n", "# model_config=model_config,\n", "# model_predicted_label_config=predictions_config,\n", "# pre_training_methods='all',\n", "# post_training_methods='all')\n", "\n", "# clarify_bias_job_1_name = clarify_processor.latest_job.name\n", "# %store clarify_bias_job_1_name\n", "\n", "# else:\n", "# print(f'Clarify job {clarify_bias_job_name} has already run successfully.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Results will be stored in `/opt/ml/processing/output/report.pdf`\n", "Training to achieve over 90 percent classification accuracy, may be easily possible on an imbalanced classification problem.\n", "\n", "Thus, expectations developed regarding classification accuracy that are in reality contingent on balanced class distributions will lead to wrong, misleading assumptions and conclusions : misleading the data scientist and viewers into believing that a model has extremely performance when , actually, it does not." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### View results of Clarify job (shortcut)\n", "Running Clarify on your dataset or model can take ~15 minutes. If you don't have time to run the job, you can view the pre-generated results included with this demo. Otherwise, you can run the job by un-commenting the code in the cell above." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if \"clarify_bias_job_1_name\" in locals():\n", " s3_client.download_file(\n", " Bucket=bucket,\n", " Key=f\"{prefix}/clarify-output/bias_1/analysis.json\",\n", " Filename=\"clarify_output/bias_1/analysis.json\",\n", " )\n", " print(f\"Downloaded analysis from previous Clarify job: {clarify_bias_job_1_name}\")\n", "else:\n", " print(f\"Loading pre-generated analysis file...\")\n", "\n", "with open(\"clarify_output/bias_1/analysis.json\", \"r\") as f:\n", " bias_analysis = json.load(f)\n", "\n", "results = bias_analysis[\"pre_training_bias_metrics\"][\"facets\"][\"customer_gender_female\"][0][\n", " \"metrics\"\n", "][1]\n", "print(json.dumps(results, indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example dataset, the data is biased against females with only 38.9% of the data samples from female customers. We will address this in the next notebook where we show how we mitigate this class imbalance bias. Although we are only addressing Class Imbalance as an exemplar of bias statistics, you can also take into consideration many other factors of bias. For more detail, see : [Fairness Measures for Machine Learning in Finance](https://pages.awscloud.com/rs/112-TZM-766/images/Fairness.Measures.for.Machine.Learning.in.Finance.pdf)\n", "\n", "for a more detailed example look at [this](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-clarify/fairness_and_explainability/fairness_and_explainability.ipynb) github example." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For more detailed resulst let's look at the generated report, that can be found here: `s3://{bucket}/e2e-fraud-detect/clarify/bias-2/report.pdf`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# uncomment to copy report and view\n", "#!aws s3 cp s3://{bucket}/{prefix}/clarify-output/bias_1/report.pdf ./clarify_output" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Deposit Model and Lineage in SageMaker Model Registry\n", "----\n", "\n", "Once a useful model has been trained and its artifacts properly associated, the next step is to save the model in a registry for future reference and possible deployment.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create Model Package Group\n", "A Model Package Groups holds multiple versions or iterations of a model. Though it is not required to create them for every model in the registry, they help organize various models which all have the same purpose and provide automatic versioning." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if \"mpg_name\" not in locals():\n", " mpg_name = prefix\n", " print(f\"Model Package Group name: {mpg_name}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mpg_input_dict = {\n", " \"ModelPackageGroupName\": mpg_name,\n", " \"ModelPackageGroupDescription\": \"Insurance claim fraud detection\",\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "matching_mpg = sagemaker_boto_client.list_model_package_groups(NameContains=mpg_name)['ModelPackageGroupSummaryList']\n", "\n", "if matching_mpg:\n", " print(f'Using existing Model Package Group: {mpg_name}')\n", "else:\n", " mpg_response = sagemaker_boto_client.create_model_package_group(**mpg_input_dict)\n", " print(f'Create Model Package Group {mpg_name}: SUCCESSFUL')\n", " %store mpg_name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create Model Package for trained model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Create and upload a metrics report" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model_metrics_report = {\"binary_classification_metrics\": {}}\n", "for metric in training_job_1_info[\"FinalMetricDataList\"]:\n", " stat = {metric[\"MetricName\"]: {\"value\": metric[\"Value\"], \"standard_deviation\": \"NaN\"}}\n", " model_metrics_report[\"binary_classification_metrics\"].update(stat)\n", "\n", "with open(\"training_metrics.json\", \"w\") as f:\n", " json.dump(model_metrics_report, f)\n", "\n", "metrics_s3_key = (\n", " f\"{prefix}/training_jobs/{training_job_1_info['TrainingJobName']}/training_metrics.json\"\n", ")\n", "s3_client.upload_file(Filename=\"training_metrics.json\", Bucket=bucket, Key=metrics_s3_key)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Define the inference spec" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mp_inference_spec = InferenceSpecification().get_inference_specification_dict(\n", " ecr_image=training_job_1_info[\"AlgorithmSpecification\"][\"TrainingImage\"],\n", " supports_gpu=False,\n", " supported_content_types=[\"text/csv\"],\n", " supported_mime_types=[\"text/csv\"],\n", ")\n", "\n", "mp_inference_spec[\"InferenceSpecification\"][\"Containers\"][0][\"ModelDataUrl\"] = training_job_1_info[\n", " \"ModelArtifacts\"\n", "][\"S3ModelArtifacts\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Define model metrics\n", "Metrics other than model quality and bias can be defined. See the Boto3 documentation for [creating a model package](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_model_package)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model_metrics = {\n", " \"ModelQuality\": {\n", " \"Statistics\": {\n", " \"ContentType\": \"application/json\",\n", " \"S3Uri\": f\"s3://{bucket}/{metrics_s3_key}\",\n", " }\n", " },\n", " \"Bias\": {\n", " \"Report\": {\n", " \"ContentType\": \"application/json\",\n", " \"S3Uri\": f\"{bias_report_1_output_path}/analysis.json\",\n", " }\n", " },\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mp_input_dict = {\n", " \"ModelPackageGroupName\": mpg_name,\n", " \"ModelPackageDescription\": \"XGBoost classifier to detect insurance fraud.\",\n", " \"ModelApprovalStatus\": \"PendingManualApproval\",\n", " \"ModelMetrics\": model_metrics,\n", "}\n", "\n", "mp_input_dict.update(mp_inference_spec)\n", "mp1_response = sagemaker_boto_client.create_model_package(**mp_input_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Wait until model package is completed" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mp_info = sagemaker_boto_client.describe_model_package(\n", " ModelPackageName=mp1_response[\"ModelPackageArn\"]\n", ")\n", "mp_status = mp_info[\"ModelPackageStatus\"]\n", "\n", "while mp_status not in [\"Completed\", \"Failed\"]:\n", " time.sleep(5)\n", " mp_info = sagemaker_boto_client.describe_model_package(\n", " ModelPackageName=mp1_response[\"ModelPackageArn\"]\n", " )\n", " mp_status = mp_info[\"ModelPackageStatus\"]\n", " print(f\"model package status: {mp_status}\")\n", "print(f\"model package status: {mp_status}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### View model package in registry" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sagemaker_boto_client.list_model_packages(ModelPackageGroupName=mpg_name)[\"ModelPackageSummaryList\"]" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Notebook CI Test Results\n", "\n", "This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.\n", "\n", "![This us-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This us-east-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-2/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This us-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This ca-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ca-central-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This sa-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/sa-east-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This eu-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This eu-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-2/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This eu-west-3 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-3/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This eu-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-central-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This eu-north-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-north-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This ap-southeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This ap-southeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-2/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This ap-northeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This ap-northeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-2/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n", "\n", "![This ap-south-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-south-1/end_to_end|fraud_detection|2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (Data Science 2.0)", "language": "python", "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/sagemaker-data-science-38" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.13" } }, "nbformat": 4, "nbformat_minor": 4 }