notebooks/official/pipelines/google_cloud_pipeline_components_automl_tabular.ipynb (701 lines of code) (raw):
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "copyright"
},
"outputs": [],
"source": [
"# Copyright 2021 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "title:generic"
},
"source": [
"# Vertex AI Pipelines: AutoML tabular regression pipelines using google-cloud-pipeline-components\n",
"\n",
"<table align=\"left\">\n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/pipelines/google_cloud_pipeline_components_automl_tabular.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Google Colaboratory logo\"><br> Open in Colab\n",
" </a>\n",
" </td>\n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/colab/import/https:%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fvertex-ai-samples%2Fmain%2Fnotebooks%2Fofficial%2Fpipelines%2Fgoogle_cloud_pipeline_components_automl_tabular.ipynb\">\n",
" <img width=\"32px\" src=\"https://cloud.google.com/ml-engine/images/colab-enterprise-logo-32px.png\" alt=\"Google Cloud Colab Enterprise logo\"><br> Open in Colab Enterprise\n",
" </a>\n",
" </td> \n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/official/pipelines/google_cloud_pipeline_components_automl_tabular.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\"><br> Open in Workbench\n",
" </a>\n",
" </td>\n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/pipelines/google_cloud_pipeline_components_automl_tabular.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\"><br> View on GitHub\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "overview:pipelines,automl"
},
"source": [
"## Overview\n",
"\n",
"This notebook shows how to use the components defined in [`google_cloud_pipeline_components`](https://github.com/kubeflow/pipelines/tree/master/components/google-cloud) to build an AutoML tabular regression workflow on Vertex AI Pipelines.\n",
"\n",
"Learn more about [Vertex AI Pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/introduction) and [AutoML components](https://cloud.google.com/vertex-ai/docs/pipelines/vertex-automl-component). Learn more about [Regression for tabular data](https://cloud.google.com/vertex-ai/docs/tabular-data/classification-regression/overview)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "objective:pipelines,automl"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn to use `Vertex AI Pipelines` and `Google Cloud Pipeline Components` to build an `AutoML` tabular regression model.\n",
"\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `Vertex AI Pipelines`\n",
"- `Google Cloud Pipeline Components`\n",
"- `Vertex AI AutoML`\n",
"- `Vertex AI Model` resource\n",
"- `Vertex AI Endpoint` resource\n",
"\n",
"The steps performed include:\n",
"\n",
"- Create a KFP pipeline that creates a `Dataset` resource.\n",
"- Add a component to the pipeline that trains an AutoML tabular regression `Model` resource.\n",
"- Add a component that creates an `Endpoint` resource.\n",
"- Add a component that deploys the `Model` resource to the `Endpoint` resource.\n",
"- Compile the KFP pipeline.\n",
"- Execute the KFP pipeline using `Vertex AI Pipelines`.\n",
"\n",
"Learn more about [Google Cloud Pipeline Components](https://google-cloud-pipeline-components.readthedocs.io/en/latest/google_cloud_pipeline_components.aiplatform.html#module-google_cloud_pipeline_components.aiplatform)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "77de5c53ac91"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [California Housing dataset from the 1990 Census](https://developers.google.com/machine-learning/crash-course/california-housing-data-description)\n",
"\n",
"The dataset predicts the median house price."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "costs"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
"pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
"Calculator](https://cloud.google.com/products/calculator/)\n",
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f0316df526f8"
},
"source": [
"## Get started"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_aip:mbsdk"
},
"source": [
"### Install Vertex AI SDK for Python and other required packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_aip:mbsdk"
},
"outputs": [],
"source": [
"! pip3 install --upgrade --quiet google-cloud-aiplatform \\\n",
" google-cloud-storage \\\n",
" kfp \\\n",
" google-cloud-pipeline-components"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ff555b32bab8"
},
"source": [
"### Restart runtime (Colab only)\n",
"\n",
"To use the newly installed packages, you must restart the runtime on Google Colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f09b4dff629a"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
"\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4a2b7b59bbf7"
},
"source": [
"<div class=\"alert alert-block alert-warning\">\n",
"<b>⚠️ The kernel is going to restart. Wait until it's finished before continuing to the next step. ⚠️</b>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f82e28c631cc"
},
"source": [
"### Authenticate your notebook environment (Colab only)\n",
"\n",
"Authenticate your environment on Google Colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "46604f70e831"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
"\n",
" from google.colab import auth\n",
"\n",
" auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### UUID\n",
"\n",
"If you're in a live tutorial session, to avoid name collisions between users on resources created, you create a UUID for each instance session and append the UUID onto the names of resources you create in this tutorial. This ensures that each resource is uniquely identified and avoids conflicts with resources created by other users during the session."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of length 8\n",
"def generate_uuid():\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=8))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c9973091a392"
},
"source": [
"### Set Google Cloud project information\n",
"\n",
"To get started using Vertex AI, you must have an existing Google Cloud project. Learn more about [setting up a project and a development environment](https://cloud.google.com/vertex-ai/docs/start/cloud-environment)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"LOCATION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zgPO1eR3CYjk"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"Create a storage bucket to store intermediate artifacts such as datasets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MzGDU7TWdts_"
},
"outputs": [],
"source": [
"BUCKET_URI = f\"gs://your-bucket-name-{PROJECT_ID}-unique\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-EcIXiGsCePi"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NIq7R4HZCfIc"
},
"outputs": [],
"source": [
"! gsutil mb -l {LOCATION} -p {PROJECT_ID} {BUCKET_URI}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account"
},
"source": [
"#### Service Account\n",
"\n",
"**If you don't know your service account**, try to get your service account using `gcloud` command by executing the second cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account"
},
"outputs": [],
"source": [
"SERVICE_ACCOUNT = \"[your-service-account]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_service_account"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"\n",
"if (\n",
" SERVICE_ACCOUNT == \"\"\n",
" or SERVICE_ACCOUNT is None\n",
" or SERVICE_ACCOUNT == \"[your-service-account]\"\n",
"):\n",
" # Get your service account from gcloud\n",
" if not IS_COLAB:\n",
" shell_output = !gcloud auth list 2>/dev/null\n",
" SERVICE_ACCOUNT = shell_output[2].replace(\"*\", \"\").strip()\n",
"\n",
" if IS_COLAB:\n",
" shell_output = ! gcloud projects describe $PROJECT_ID\n",
" project_number = shell_output[-1].split(\":\")[1].strip().replace(\"'\", \"\")\n",
" SERVICE_ACCOUNT = f\"{project_number}-compute@developer.gserviceaccount.com\"\n",
"\n",
" print(\"Service Account:\", SERVICE_ACCOUNT)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "set_service_account:pipelines"
},
"source": [
"#### Set service account access for Vertex AI Pipelines\n",
"\n",
"Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_service_account:pipelines"
},
"outputs": [],
"source": [
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_URI\n",
"\n",
"! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_vars"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_aip:mbsdk"
},
"outputs": [],
"source": [
"import google.cloud.aiplatform as aiplatform\n",
"import kfp"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pipeline_constants"
},
"source": [
"#### Vertex AI Pipelines constants\n",
"\n",
"Setup up the following constants for Vertex AI Pipelines:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pipeline_constants"
},
"outputs": [],
"source": [
"PIPELINE_ROOT = \"{}/pipeline_root/cal_housing\".format(BUCKET_URI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "init_aip:mbsdk"
},
"source": [
"## Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project and corresponding bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "init_aip:mbsdk"
},
"outputs": [],
"source": [
"aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "define_pipeline:gcpc,automl,cal_housing,lrg"
},
"source": [
"## Define AutoML Tabular Regression Model Pipeline \n",
"\n",
"Next, you define the pipeline to create and deploy an AutoML tabular regression `Model` resource using a `Dataset` resource. This pipeline leverages Google Cloud components for seamless integration and efficient management of resources."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "define_pipeline:gcpc,automl,cal_housing,lrg"
},
"outputs": [],
"source": [
"TRAIN_FILE_NAME = \"california_housing_train.csv\"\n",
"! gsutil cp gs://cloud-samples-data/vertex-ai/pipeline-deployment/datasets/california_housing/california_housing_train.csv {PIPELINE_ROOT}/data/\n",
"\n",
"gcs_csv_path = f\"{PIPELINE_ROOT}/data/{TRAIN_FILE_NAME}\"\n",
"\n",
"\n",
"@kfp.dsl.pipeline(name=\"automl-tab-training-v2\")\n",
"def pipeline(project: str = PROJECT_ID, region: str = LOCATION):\n",
" from google_cloud_pipeline_components.v1.automl.training_job import \\\n",
" AutoMLTabularTrainingJobRunOp\n",
" from google_cloud_pipeline_components.v1.dataset import \\\n",
" TabularDatasetCreateOp\n",
" from google_cloud_pipeline_components.v1.endpoint import (EndpointCreateOp,\n",
" ModelDeployOp)\n",
"\n",
" dataset_create_op = TabularDatasetCreateOp(\n",
" project=project, display_name=\"housing\", gcs_source=gcs_csv_path\n",
" )\n",
"\n",
" training_op = AutoMLTabularTrainingJobRunOp(\n",
" project=project,\n",
" display_name=\"train-automl-cal_housing\",\n",
" optimization_prediction_type=\"regression\",\n",
" optimization_objective=\"minimize-rmse\",\n",
" column_transformations=[\n",
" {\"numeric\": {\"column_name\": \"longitude\"}},\n",
" {\"numeric\": {\"column_name\": \"latitude\"}},\n",
" {\"numeric\": {\"column_name\": \"housing_median_age\"}},\n",
" {\"numeric\": {\"column_name\": \"total_rooms\"}},\n",
" {\"numeric\": {\"column_name\": \"total_bedrooms\"}},\n",
" {\"numeric\": {\"column_name\": \"population\"}},\n",
" {\"numeric\": {\"column_name\": \"households\"}},\n",
" {\"numeric\": {\"column_name\": \"median_income\"}},\n",
" {\"numeric\": {\"column_name\": \"median_house_value\"}},\n",
" ],\n",
" dataset=dataset_create_op.outputs[\"dataset\"],\n",
" target_column=\"median_house_value\",\n",
" )\n",
"\n",
" endpoint_op = EndpointCreateOp(\n",
" project=project,\n",
" location=region,\n",
" display_name=\"train-automl-cal_housing_endpoint\",\n",
" )\n",
"\n",
" _ = ModelDeployOp(\n",
" model=training_op.outputs[\"model\"],\n",
" endpoint=endpoint_op.outputs[\"endpoint\"],\n",
" dedicated_resources_machine_type=\"n1-standard-4\",\n",
" dedicated_resources_min_replica_count=1,\n",
" dedicated_resources_max_replica_count=1,\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "compile_pipeline"
},
"source": [
"## Compile the pipeline\n",
"\n",
"Next, compile the pipeline."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "compile_pipeline"
},
"outputs": [],
"source": [
"from kfp import compiler # noqa: F811\n",
"\n",
"compiler.Compiler().compile(\n",
" pipeline_func=pipeline,\n",
" package_path=\"tabular_regression_pipeline.yaml\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "run_pipeline:automl,tabular"
},
"source": [
"## Run the pipeline\n",
"\n",
"Next, run the pipeline."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "run_pipeline:automl,tabular"
},
"outputs": [],
"source": [
"DISPLAY_NAME = \"cal_housing_\" + UUID\n",
"\n",
"job = aiplatform.PipelineJob(\n",
" display_name=DISPLAY_NAME,\n",
" template_path=\"tabular_regression_pipeline.yaml\",\n",
" pipeline_root=PIPELINE_ROOT,\n",
" enable_caching=False,\n",
")\n",
"\n",
"job.run()\n",
"\n",
"! rm tabular_regression_pipeline.yaml"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "view_pipeline_run:automl,tabular"
},
"source": [
"Click on the generated link to see your run in the Cloud Console.\n",
"\n",
"<!-- It should look something like this as it's running:\n",
"\n",
"<a href=\"https://storage.googleapis.com/amy-jo/images/mp/automl_tabular_classif.png\" target=\"_blank\"><img src=\"https://storage.googleapis.com/amy-jo/images/mp/automl_tabular_classif.png\" width=\"40%\"/></a> -->\n",
"\n",
"In the UI, many of the pipeline DAG nodes expand or collapse when you click on them. Here is a partially-expanded view of the DAG (click the image to see a larger version).\n",
"\n",
"<a href=\"https://storage.googleapis.com/amy-jo/images/mp/automl_tabular_classif.png\" target=\"_blank\"><img src=\"https://storage.googleapis.com/amy-jo/images/mp/automl_tabular_classif.png\" width=\"40%\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cleanup:pipelines"
},
"source": [
"# Cleaning up\n",
"\n",
"To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cleanup:pipelines"
},
"outputs": [],
"source": [
"delete_bucket = True\n",
"\n",
"dataset_display_name = \"housing\"\n",
"pipeline_display_name = \"automl-tab-training-v2\"\n",
"model_display_name = \"train-automl-cal_housing\"\n",
"endpoint_display_name = \"train-automl-cal_housing_endpoint\"\n",
"\n",
"\n",
"endpoints = aiplatform.Endpoint.list(\n",
" filter=f\"display_name={endpoint_display_name}\", order_by=\"create_time\"\n",
")\n",
"if endpoints:\n",
" endpoint = endpoints[0]\n",
" endpoint.undeploy_all()\n",
" endpoint.delete()\n",
" print(\"Deleted endpoint:\", endpoint)\n",
"\n",
"models = aiplatform.Model.list(\n",
" filter=f\"display_name={model_display_name}\", order_by=\"create_time\"\n",
")\n",
"if models:\n",
" model = models[0]\n",
" model.delete()\n",
" print(\"Deleted model:\", model)\n",
"\n",
"datasets = aiplatform.TabularDataset.list(\n",
" filter=f\"display_name={dataset_display_name}\", order_by=\"create_time\"\n",
")\n",
"if datasets:\n",
" dataset = datasets[0]\n",
" dataset.delete()\n",
" print(\"Deleted dataset:\", dataset)\n",
"\n",
"\n",
"job.delete()\n",
"\n",
"\n",
"if delete_bucket:\n",
" ! gsutil rm -r $BUCKET_URI"
]
}
],
"metadata": {
"colab": {
"name": "google_cloud_pipeline_components_automl_tabular.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}