Compare commits

..
Author SHA1 Message Date
ivanmkc 0968fb77db Improve download instructions 2022-07-21 19:33:17 -04:00
ivanmkc 471c57132a Fixed issue with numbers in replacement content 2022-07-21 19:29:13 -04:00
ivanmkc 72bad1f6ee Removed replacement of variable comparisons 2022-07-21 15:56:27 -04:00
290 changed files with 27270 additions and 104957 deletions
@@ -1,2 +1 @@
ratemate
google-cloud-aiplatform
@@ -68,12 +68,6 @@ parser.add_argument(
help="A service account. This is used to inject a variable value into the notebook before running. This is not the account that will run the notebook.",
required=True,
)
parser.add_argument(
"--variable_vpc_network",
type=str,
help="The full VPC network name. See https://cloud.google.com/compute/docs/networks-and-firewalls#networks. Format is projects/{project}/global/networks/{network}, where {project} is a project number, as in '12345', and {network} is network name. See <https://cloud.google.com/compute/docs/reference/rest/v1/networks/insert> for details. This is used to inject a variable value into the notebook before running.",
required=False,
)
parser.add_argument(
"--staging_bucket",
type=str,
@@ -120,11 +114,10 @@ execute_changed_notebooks_helper.process_and_execute_notebooks(
container_uri=args.container_uri,
staging_bucket=args.staging_bucket,
artifacts_bucket=args.artifacts_bucket,
should_parallelize=args.should_parallelize,
timeout=args.timeout,
variable_project_id=args.variable_project_id,
variable_region=args.variable_region,
variable_service_account=args.variable_service_account,
variable_vpc_network=args.variable_vpc_network,
private_pool_id=args.private_pool_id,
should_parallelize=args.should_parallelize,
timeout=args.timeout,
)
+27 -102
View File
@@ -17,16 +17,13 @@ import concurrent
import dataclasses
import datetime
import functools
import json
import git
import operator
import os
import pathlib
import re
import subprocess
import utils
from typing import List, Optional
from utils import util
import execute_notebook_helper
import execute_notebook_remote
@@ -38,7 +35,6 @@ from utils import NotebookProcessors, util
# A buffer so that workers finish before the orchestrating job
WORKER_TIMEOUT_BUFFER_IN_SECONDS: int = 60 * 60
PYTHON_VERSION = "3.9" # Set default python version
def format_timedelta(delta: datetime.timedelta) -> str:
@@ -70,23 +66,14 @@ class NotebookExecutionResult:
log_url: str
output_uri: str
build_id: str
logs_bucket: str
error_message: Optional[str]
@property
def output_uri_web(self) -> Optional[str]:
if self.output_uri.startswith("gs://"):
return f"https://storage.googleapis.com/{self.output_uri[5:]}"
else:
return None
def _process_notebook(
notebook_path: str,
variable_project_id: str,
variable_region: str,
variable_service_account: str,
variable_vpc_network: Optional[str],
):
# Read notebook
with open(notebook_path) as f:
@@ -99,7 +86,6 @@ def _process_notebook(
"PROJECT_ID": variable_project_id,
"REGION": variable_region,
"SERVICE_ACCOUNT": variable_service_account,
"VPC_NETWORK": variable_vpc_network,
},
)
@@ -115,33 +101,6 @@ def _process_notebook(
nbformat.write(nb, new_file)
def _get_notebook_python_version(notebook_path: str) -> str:
"""
Get the python version for running the notebook if it is specified in
the notebook.
"""
python_version = PYTHON_VERSION
# Load the notebook
file = open(notebook_path)
src = file.read()
nb_json = json.loads(src)
#Iterate over the cells in the ipynb
for cell in nb_json['cells']:
if cell['cell_type'] == 'markdown':
markdown = str.join('', cell['source'])
# Look for the python version specification pattern
re_match = re.search('python version = (\d\.\d)', markdown, flags=re.IGNORECASE)
if re_match:
# get the version number
python_version = re_match.group(1)
break
return python_version
def _create_tag(filepath: str) -> str:
tag = os.path.basename(os.path.normpath(filepath))
tag = re.sub("[^0-9a-zA-Z_.-]+", "-", tag)
@@ -162,9 +121,8 @@ def process_and_execute_notebook(
variable_project_id: str,
variable_region: str,
variable_service_account: str,
variable_vpc_network: Optional[str],
private_pool_id: Optional[str],
deadline: datetime.datetime,
deadline: datetime,
notebook: str,
should_get_tail_logs: bool = False,
) -> NotebookExecutionResult:
@@ -172,13 +130,6 @@ def process_and_execute_notebook(
print(f"Running notebook: {notebook}")
# Handle empty strings
if not variable_vpc_network:
variable_vpc_network = None
if not private_pool_id:
private_pool_id = None
# Create paths
notebook_output_uri = "/".join([artifacts_bucket, pathlib.Path(notebook).name])
@@ -192,7 +143,6 @@ def process_and_execute_notebook(
output_uri=notebook_output_uri,
log_url="",
build_id="",
logs_bucket="",
error_message=None,
)
@@ -200,17 +150,12 @@ def process_and_execute_notebook(
time_start = datetime.datetime.now()
operation = None
try:
# Get the python version for running the notebook if specified
notebook_exec_python_version = _get_notebook_python_version(notebook_path=notebook)
print(f"Running notebook with python {notebook_exec_python_version}")
# Pre-process notebook by substituting variable names
_process_notebook(
notebook_path=notebook,
variable_project_id=variable_project_id,
variable_region=variable_region,
variable_service_account=variable_service_account,
variable_vpc_network=variable_vpc_network,
)
# Upload the pre-processed code to a GCS bucket
@@ -230,13 +175,11 @@ def process_and_execute_notebook(
private_pool_id=private_pool_id,
private_pool_region=variable_region,
timeout_in_seconds=timeout_in_seconds,
python_version=notebook_exec_python_version
)
operation_metadata = BuildOperationMetadata(mapping=operation.metadata)
result.build_id = operation_metadata.build.id
result.log_url = operation_metadata.build.log_url
result.logs_bucket = operation_metadata.build.logs_bucket
# Block and wait for the result
operation_result = operation.result()
@@ -316,8 +259,8 @@ def get_changed_notebooks(
notebooks = []
else:
print(f"Looking for all notebooks.")
notebooks_str = subprocess.check_output(["git", "ls-files"] + test_paths)
notebooks = notebooks_str.decode("utf-8").split("\n")
notebooks = subprocess.check_output(["git", "ls-files"] + test_paths)
notebooks = notebooks.decode("utf-8").split("\n")
notebooks = [notebook for notebook in notebooks if notebook.endswith(".ipynb")]
notebooks = [notebook for notebook in notebooks if len(notebook) > 0]
@@ -336,13 +279,12 @@ def process_and_execute_notebooks(
container_uri: str,
staging_bucket: str,
artifacts_bucket: str,
should_parallelize: bool,
timeout: int,
variable_project_id: str,
variable_region: str,
variable_service_account: str,
variable_vpc_network: Optional[str] = None,
private_pool_id: Optional[str] = None,
private_pool_id: Optional[str],
should_parallelize: bool,
timeout: int,
):
"""
Run the notebooks that exist under the folders defined in the test_paths_file.
@@ -378,7 +320,7 @@ def process_and_execute_notebooks(
seconds=max(timeout - WORKER_TIMEOUT_BUFFER_IN_SECONDS, 0)
)
if len(notebooks) >= 1:
if len(notebooks) > 1:
notebook_execution_results: List[NotebookExecutionResult] = []
print(f"Found {len(notebooks)} modified notebooks: {notebooks}")
@@ -400,7 +342,6 @@ def process_and_execute_notebooks(
variable_project_id,
variable_region,
variable_service_account,
variable_vpc_network,
private_pool_id,
deadline,
),
@@ -416,7 +357,6 @@ def process_and_execute_notebooks(
variable_project_id=variable_project_id,
variable_region=variable_region,
variable_service_account=variable_service_account,
variable_vpc_network=variable_vpc_network,
private_pool_id=private_pool_id,
deadline=deadline,
notebook=notebook,
@@ -442,47 +382,13 @@ def process_and_execute_notebooks(
format_timedelta(result.duration),
result.log_url,
result.output_uri,
result.output_uri_web,
result.logs_bucket
]
for result in results_sorted
],
headers=[
"build_tag",
"status",
"duration",
"log_url",
"output_uri",
"output_uri_web",
"logs_bucket"
],
headers=["build_tag", "status", "duration", "log_url", "output_url"],
)
)
if len(notebooks) == 1:
print("="*100)
print("The notebook execution build log:\n")
print("="*100)
build_id = results_sorted[0].build_id
logs_bucket_name = (results_sorted[0].logs_bucket).removeprefix("gs://")
log_file_name = f"log-{build_id}.txt"
log_contents = util.download_blob_into_memory(
bucket_name=logs_bucket_name,
blob_name=log_file_name,
download_as_text=True
)
# Remove extra steps from the log
match = re.search("starting Step #4", log_contents, flags=re.IGNORECASE)
if match is not None:
match_index = match.span()[0]
print(log_contents[match_index:])
else:
print(log_contents)
print("\n=== END RESULTS===\n")
total_notebook_duration = functools.reduce(
@@ -498,5 +404,24 @@ def process_and_execute_notebooks(
# Raise error if any notebooks failed
if not all([result.is_pass for result in results_sorted]):
raise RuntimeError("Notebook failures detected. See logs for details")
elif len(notebooks) == 1:
notebook = notebooks[0]
# Pre-process notebook by substituting variable names
_process_notebook(
notebook_path=notebook,
variable_project_id=variable_project_id,
variable_region=variable_region,
variable_service_account=variable_service_account,
)
execute_notebook_helper.execute_notebook(
notebook_source=notebook,
output_file_or_uri="/".join(
[artifacts_bucket, pathlib.Path(notebook).name]
),
should_log_output=True,
)
else:
print("No notebooks modified in this pull request.")
+4 -15
View File
@@ -26,9 +26,6 @@ from utils import util
# This script is used to execute a notebook and write out the output notebook.
# This is used to force papermill to use this kernel to run the notebook instead of any defined inside the notebook itself
DEFAULT_KERNEL_NAME = "python3"
def execute_notebook(
notebook_source: str,
@@ -53,17 +50,6 @@ def execute_notebook(
execution_exception = None
print("\n=== DOWNLOAD EXECUTED NOTEBOOK ===\n")
print(f"Please debug the executed notebook by downloading the executed notebook:")
print("Option 1. Using gsutil. Run the following command in your terminal.")
print(f'\tgsutil cp "{output_file_or_uri}" .')
print("Option 2. Using this link.")
print(f"\thttps://storage.googleapis.com/{output_file_or_uri[5:]}")
print("\n======\n")
# Execute notebook
try:
# Execute notebook
@@ -72,7 +58,6 @@ def execute_notebook(
output_path=notebook_source,
progress_bar=should_log_output,
request_save_on_cell_execute=should_log_output,
kernel_name=DEFAULT_KERNEL_NAME,
log_output=should_log_output,
stdout_file=sys.stdout if should_log_output else None,
stderr_file=sys.stderr if should_log_output else None,
@@ -86,6 +71,10 @@ def execute_notebook(
util.upload_file(notebook_source, remote_file_path=output_file_or_uri)
print("\n=== EXECUTION FINISHED ===\n")
print(
f"Please debug the executed notebook by downloading: {output_file_or_uri}"
)
print("\n======\n")
else:
# Create directories if they don't exist
if not os.path.exists(os.path.dirname(output_file_or_uri)):
-5
View File
@@ -40,7 +40,6 @@ def execute_notebook_remote(
private_pool_region: Optional[str],
tag: Optional[str],
timeout_in_seconds: Optional[int] = None,
python_version: Optional[str] = None
) -> operation.Operation:
"""Create and execute a single notebook on Google Cloud Build"""
# Load build steps from YAML
@@ -51,12 +50,8 @@ def execute_notebook_remote(
"_PYTHON_IMAGE": container_uri,
"_NOTEBOOK_GCS_URI": notebook_uri,
"_NOTEBOOK_OUTPUT_GCS_URI": notebook_output_uri,
"_PYTHON_VERSION" : f"python{python_version}"
}
if python_version is not None:
substitutions["_PYTHON_VERSION"] = "python" + python_version
build = cloudbuild_v1.Build()
options: Optional[client_options.ClientOptions] = None
@@ -4,35 +4,43 @@ steps:
entrypoint: /bin/sh
args:
- -c
- 'gcloud config list --quiet'
- 'gcloud config list'
# Check the Python version
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- ${_PYTHON_VERSION} .cloud-build/CheckPythonVersion.py -q
- python3 .cloud-build/CheckPythonVersion.py
# Create a virtual environment
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- ${_PYTHON_VERSION} -m venv workspace/env
- python3 -m venv workspace/env
# Install Python dependencies
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- -c
- . workspace/env/bin/activate &&
python -m pip -q install -U pip &&
python -m pip -q install -U -r .cloud-build/requirements.txt
# Install Python dependencies and run testing script
python3 -m pip install -U pip &&
python3 -m pip install -U -r .cloud-build/requirements.txt
# pip freeze
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- |
. workspace/env/bin/activate &&
python .cloud-build/execute_notebook_cli.py --notebook_source "${_NOTEBOOK_GCS_URI}" --output_file_or_uri "${_NOTEBOOK_OUTPUT_GCS_URI}"
python3 -m pip freeze
# Install Python dependencies and run testing script
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- |
. workspace/env/bin/activate &&
python3 .cloud-build/execute_notebook_cli.py --notebook_source "${_NOTEBOOK_GCS_URI}" --output_file_or_uri "${_NOTEBOOK_OUTPUT_GCS_URI}"
env:
- 'IS_TESTING=1'
timeout: 86400s
timeout: 86400s
@@ -4,16 +4,16 @@ steps:
entrypoint: /bin/sh
args:
- -c
- gcloud config list --quiet
- gcloud config list
# Check the Python version
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- python3 .cloud-build/CheckPythonVersion.py -q
- python3 .cloud-build/CheckPythonVersion.py
# Fetch full repo for diff purposes
- name: gcr.io/cloud-builders/git
args: [fetch, --unshallow, --quiet]
args: [fetch, --unshallow]
# Create a virtual environment
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
@@ -24,22 +24,30 @@ steps:
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- -c
- . workspace/env/bin/activate &&
python3 -m pip -q install -U pip &&
python3 -m pip -q install -U -r .cloud-build/requirements.txt
# Install Python dependencies and run testing script
# TODO: Only pass in private_pool_id if it is set
python3 -m pip install -U pip &&
python3 -m pip install -U -r .cloud-build/requirements.txt
# pip freeze
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- |
. workspace/env/bin/activate &&
python3 .cloud-build/execute_changed_notebooks_cli.py --test_paths_file "${_TEST_PATHS_FILE}" --base_branch "${_FORCED_BASE_BRANCH}" --container_uri ${_PYTHON_IMAGE} --staging_bucket ${_GCS_STAGING_BUCKET} --artifacts_bucket ${_GCS_STAGING_BUCKET}/executed_notebooks/PR_${_PR_NUMBER}/BUILD_${BUILD_ID} --variable_project_id ${PROJECT_ID} --variable_region ${_GCP_REGION} --variable_service_account ${_GCP_SERVICE_ACCOUNT} --variable_vpc_network "${_GPC_VPC_NETWORK_NAME}" `if [ ! -z "${_PRIVATE_POOL_NAME}" ]; then echo "--private_pool_id ${_PRIVATE_POOL_NAME}"; fi`
python3 -m pip freeze
# Install Python dependencies and run testing script
# TODO: Only pass in private_pool_id if it is set
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- |
. workspace/env/bin/activate &&
python3 .cloud-build/execute_changed_notebooks_cli.py --test_paths_file "${_TEST_PATHS_FILE}" --base_branch "${_FORCED_BASE_BRANCH}" --container_uri ${_PYTHON_IMAGE} --staging_bucket ${_GCS_STAGING_BUCKET} --artifacts_bucket ${_GCS_STAGING_BUCKET}/executed_notebooks/PR_${_PR_NUMBER}/BUILD_${BUILD_ID} --variable_project_id ${PROJECT_ID} --variable_region ${_GCP_REGION} --variable_service_account ${_GCP_SERVICE_ACCOUNT} `if [ ! -z "${_PRIVATE_POOL_NAME}" ]; then echo "--private_pool_id ${_PRIVATE_POOL_NAME}"; fi`
env:
- 'IS_TESTING=1'
timeout: 86400s
options:
pool:
name: ${_PRIVATE_POOL_NAME}
name: ${_PRIVATE_POOL_NAME}
+2 -3
View File
@@ -1,6 +1,5 @@
notebooks/official/vizier/gapic-vizier-multi-objective-optimization.ipynb
notebooks/official/pipelines/lightweight_functions_component_io_kfp.ipynb
notebooks/official/matching_engine/intro-swivel.ipynb
notebooks/official/ml_metadata/sdk-metric-parameter-tracking-for-locally-trained-models.ipynb
notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb
notebooks/official/matching_engine/sdk_matching_engine_for_indexing.ipynb
.cloud-build/tests/python_version_test.ipynb
notebooks/official/pipelines/metrics_viz_run_compare_kfp.ipynb
-1
View File
@@ -1 +0,0 @@
notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb
@@ -1,61 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "57a3d44ed8a8"
},
"source": [
"### Set up your Google Cloud project\n",
"\n",
"**_NOTE_**: This notebook has been tested in the following environment:\n",
"\n",
"* Python version = 3.7\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component).\n",
"\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c6516f90311b"
},
"outputs": [],
"source": [
"# test if the right python version is being used\n",
"import sys\n",
"\n",
"actual_python_version = f\"{sys.version_info.major}.{sys.version_info.minor}\"\n",
"print(f\"Runtime python version: {actual_python_version}\")\n",
"\n",
"assert actual_python_version == \"3.7\", \"Wrong python version!\""
]
}
],
"metadata": {
"colab": {
"name": "python_version_test.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
+1 -32
View File
@@ -3,7 +3,7 @@ import subprocess
import tarfile
import uuid
from datetime import datetime
from typing import Optional, Union
from typing import Optional
from google.auth import credentials as auth_credentials
from google.cloud import storage
@@ -58,34 +58,3 @@ def archive_code_and_upload(staging_bucket: str):
print(f"Uploaded source code archive to {source_archived_file_gcs}")
return source_archived_file_gcs
def download_blob_into_memory(
bucket_name: str,
blob_name: str,
download_as_text: Optional[bool]=False
) -> Union[bytes, str]:
"""
Downloads a blob into memory as byte or as text if
download_as_text is set to True.
"""
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
# Construct a client side representation of a blob.
blob = bucket.blob(blob_name)
# Download the blob content
if download_as_text:
contents = blob.download_as_text()
else:
contents = blob.download_as_bytes()
print(
f"Downloaded storage object {blob_name} from bucket {bucket_name}."
)
return contents
+3 -13
View File
@@ -1,11 +1,4 @@
**REQUIRED:** Add a summary of your PR here, typically including why the change is needed and what was changed. Include any design alternatives for discussion purposes.
<br>
--- YOUR PR SUMMARY GOES HERE ---
<br><br><br>
**REQUIRED:** Fill out the below checklists or remove if irrelevant
1. If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
If you are opening a PR for `Official Notebooks` under the [notebooks/official](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/official) folder, follow this mandatory checklist:
- [ ] Use the [notebook template](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb) as a starting point.
- [ ] Follow the style and grammar rules outlined in the above notebook template.
- [ ] Verify the notebook runs successfully in Colab since the automated tests cannot guarantee this even when it passes.
@@ -14,15 +7,12 @@
- [ ] This notebook has been added to the [CODEOWNERS](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/CODEOWNERS) file under the `Official Notebooks` section, pointing to the author or the author's team.
- [ ] The Jupyter notebook cleans up any artifacts it has created (datasets, ML models, endpoints, etc) so as not to eat up unnecessary resources.
<br>
2. If you are opening a PR for `Community Notebooks` under the [notebooks/community](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community) folder:
If you are opening a PR for `Community Notebooks` under the [notebooks/community](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community) folder:
- [ ] This notebook has been added to the [CODEOWNERS](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/CODEOWNERS) file under the `Community Notebooks` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
<br>
3. If you are opening a PR for `Community Content` under the [community-content](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/community-content) folder:
If you are opening a PR for `Community Content` under the [community-content](https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/community-content) folder:
- [ ] Make sure your main `Content Directory Name` is descriptive, informative, and includes some of the key products and attributes of your content, so that it is differentiable from other content
- [ ] The main content directory has been added to the [CODEOWNERS](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/community-content/CODEOWNERS) file under the `Community Content` section, pointing to the author or the author's team.
- [ ] Passes all the required formatting and linting checks. You can locally test with these [instructions](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/CONTRIBUTING.md#code-quality-checks).
-20
View File
@@ -1,20 +0,0 @@
# To use this image, run this command with the desired notebook args from the top-level vertex-ai-samples directory:
# 1. To lint all changed notebooks:
# docker run -v ${PWD}:/setup/app gcr.io/python-docs-samples-tests/notebook_linter:latest
# 2. To lint specific notebooks:
# docker run -v ${PWD}:/setup/app gcr.io/python-docs-samples-tests/notebook_linter:latest notebooks/1.ipynb notebooks/2.ipynb
FROM python:3.10
WORKDIR setup
COPY ./requirements.txt .
COPY ./run_linter.sh .
# Install dependencies.
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
WORKDIR app
ENTRYPOINT ["/setup/run_linter.sh"]
+1 -1
View File
@@ -2,7 +2,7 @@ git+https://github.com/tensorflow/docs
ipython
jupyter
nbconvert
black==22.6.0
black==22.3.0
pyupgrade==2.34.0
isort==5.10.1
flake8==4.0.1
+4 -14
View File
@@ -47,22 +47,12 @@ done
echo "Test mode: $is_test"
# Read in user-provided notebooks
notebooks=()
for arg in "$@"; do
if [[ $arg == *.ipynb ]]; then
notebooks+=("$arg")
fi
done
# Only check notebooks in test folders modified in this pull request.
# Note: Use process substitution to persist the data in the array
if [ ${#notebooks[@]} -eq 0 ]; then
echo "Checking for changed notebooked using git"
while read -r file || [ -n "$line" ]; do
notebooks+=("$file")
done < <(git diff --name-only main... | grep '\.ipynb$')
fi
notebooks=()
while read -r file || [ -n "$line" ]; do
notebooks+=("$file")
done < <(git diff --name-only main... | grep '\.ipynb$')
problematic_notebooks=()
if [ ${#notebooks[@]} -gt 0 ]; then
-1
View File
@@ -1,6 +1,5 @@
* @vertex-ai-samples-contributors @GoogleCloudPlatform/cloudml-samples-owners
/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk @yinghsienwu
/pytorch_pre_built_images_deployment @googleapis/vertex-prediction-team
/pytorch_text_classification_using_vertex_sdk_and_gcloud @RajeshThallam
/pytorch_text_classification_using_vertex_sdk_and_gcloud @RajeshThallam @ultrons
/sklearn_text_classification_from_script_using_vertex_sdk @maxhardt
@@ -2,5 +2,4 @@ cpr_model_server.py
entrypoint.py
state_dict.pth
config.json
**/__pycache__
!testdata/**
**/__pycache__
@@ -2,7 +2,7 @@
## About CPR
CPR ([custom prediction routines](https://github.com/googleapis/python-aiplatform/blob/main/google/cloud/aiplatform/prediction/README.md)) is a framework designed by Google Cloud developers to make it easier to combine machine learning models with custom preprocessing and postprocessing logic in a real-time serving application.
CPR ([custom prediction routines](https://github.com/googleapis/python-aiplatform/blob/custom-prediction-routine/google/cloud/aiplatform/prediction/README.md)) is a framework designed by Google Cloud developers to make it easier to combine machine learning models with custom preprocessing and postprocessing logic in a real-time serving application.
## Using this example
@@ -34,23 +34,6 @@ Finally, install the Python modules required to build and run the model server:
pip install -r requirements.txt
```
### Auth
This example uses Google Cloud Storage for hosting model artifacts and Artifact Registry to store the container image.
You'll need to authorize yourself before you can interact with these.
First, log in to GCP with application default credentials:
```sh
gcloud auth application-default login
```
Next, if you haven't done so already, set up the [gcloud credential helper](https://cloud.google.com/artifact-registry/docs/docker/authentication)
for the Artifact Registry region where you intend to host the image.
```
gcloud auth configure-docker <region>-docker.pkg.dev
```
### Predictor
The `TimmPredictor` class in `timm_serving/predictor.py` implements most of the important logic for the server.
@@ -60,9 +60,9 @@ class CPRConfig(object):
image: str = "timm_predictor:latest"
artifact_local_dir: str = ""
region: str = "us-central1"
project_id: str = "<your project ID here>"
project_id: str = "samthrasher-experimental"
repository: str = "cpr-images"
artifact_gcs_dir: str = "gs://<your bucket ID here>/timm-vit224/"
artifact_gcs_dir: str = "gs://samthrasher-cpr-example/timm-vit224/"
model_name: str = ""
endpoint_name: str = ""
machine_type: str = "n1-standard-2"
@@ -5,4 +5,4 @@ timm==0.5.4
smart_open==6.0.0
google-cloud-storage>=1.26.0,<2.0.0dev
google-cloud-aiplatform[prediction]>=1.16.0
google-cloud-aiplatform[prediction] @ git+https://github.com/googleapis/python-aiplatform.git@custom-prediction-routine
@@ -70,10 +70,7 @@ class PredictorUnitTests(absltest.TestCase):
def setUp(self):
super().setUp()
self.config = CPRConfig()
try:
self.config.load()
except FileNotFoundError:
logging.info("No saved config file found, using default values.")
self.config.load()
self.predictor = predictor.TimmPredictor()
def test_load_from_saved_state_dict_ok(self):
@@ -173,10 +170,7 @@ class ServerEndToEndTests(absltest.TestCase):
def setUp(self):
super().setUp()
self.config = CPRConfig()
try:
self.config.load()
except FileNotFoundError:
logging.info("No saved config file found, using default values.")
self.config.load()
self.local_model = cpr.LocalModel(
serving_container_spec=aiplatform.gapic.ModelContainerSpec(
image_uri=self.config.image
@@ -1 +0,0 @@
blah
@@ -0,0 +1,474 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a6b56b1c7b76"
},
"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": "c414a395a19b"
},
"source": [
"# PyTorch Image Classification Multi-Node Distributed Data Parallel Training on CPU using Vertex Training with Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b98238e32cf7"
},
"source": [
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/community-content/pytorch_image_classification_distributed_data_parallel_training_with_vertex_sdk/multi_node_ddp_gloo_vertex_training_with_custom_container.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "03d216c7f7b1"
},
"source": [
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c5ac73516218"
},
"outputs": [],
"source": [
"PROJECT_ID = \"YOUR PROJECT ID\"\n",
"BUCKET_NAME = \"gs://YOUR BUCKET NAME\"\n",
"REGION = \"YOUR REGION\"\n",
"SERVICE_ACCOUNT = \"YOUR SERVICE ACCOUNT\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0b5ae674177e"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_NAME"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "19a9b3bdd553"
},
"outputs": [],
"source": [
"content_name = \"pt-img-cls-multi-node-ddp-cust-cont\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "57bf6f8b4361"
},
"source": [
"## Local Training"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e5d8a3443da0"
},
"outputs": [],
"source": [
"! ls trainer"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "07f79309472d"
},
"outputs": [],
"source": [
"! cat trainer/requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e16cd8bb7483"
},
"outputs": [],
"source": [
"! pip install -r trainer/requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0b8a210718c4"
},
"outputs": [],
"source": [
"! cat trainer/task.py"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c0c6e7dfb3c6"
},
"outputs": [],
"source": [
"%run trainer/task.py --epochs 5 --no-cuda --local-mode"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "31dfdeede587"
},
"outputs": [],
"source": [
"! ls ./tmp"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "48d56ec621cc"
},
"outputs": [],
"source": [
"! rm -rf ./tmp"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8f3ea1210749"
},
"source": [
"## Vertex Training using Vertex SDK and Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "93002a20a2a6"
},
"source": [
"### Build Custom Container"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4130ce43fd08"
},
"outputs": [],
"source": [
"hostname = \"gcr.io\"\n",
"image_name = content_name\n",
"tag = \"latest\"\n",
"\n",
"custom_container_image_uri = f\"{hostname}/{PROJECT_ID}/{image_name}:{tag}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2f1fc5b05240"
},
"outputs": [],
"source": [
"! cd trainer && docker build -t $custom_container_image_uri -f Dockerfile ."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b4f274f499ac"
},
"outputs": [],
"source": [
"! docker run --rm $custom_container_image_uri --epochs 5 --no-cuda --local-mode"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ee1a0a06d0b4"
},
"outputs": [],
"source": [
"! docker push $custom_container_image_uri"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cb763be12fc9"
},
"outputs": [],
"source": [
"! gcloud container images list --repository $hostname/$PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "10c8cc6b3334"
},
"source": [
"### Initialize Vertex SDK"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1a12348169fa"
},
"outputs": [],
"source": [
"! pip install -r requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "42e981cefe41"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(\n",
" project=PROJECT_ID,\n",
" staging_bucket=BUCKET_NAME,\n",
" location=REGION,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "73c92c9298e9"
},
"source": [
"### Create a Vertex Tensorboard Instance"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bde509558cd5"
},
"outputs": [],
"source": [
"content_name = content_name + \"-cpu\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6d7908c0083c"
},
"outputs": [],
"source": [
"tensorboard = aiplatform.Tensorboard.create(\n",
" display_name=content_name,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a1f0a4f54037"
},
"source": [
"#### Option: Use a Previously Created Vertex Tensorboard Instance\n",
"\n",
"```\n",
"tensorboard_name = \"Your Tensorboard Resource Name or Tensorboard ID\"\n",
"tensorboard = aiplatform.Tensorboard(tensorboard_name=tensorboard_name)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a4cac84e04ac"
},
"source": [
"### Run a Vertex SDK CustomContainerTrainingJob"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f92e8fdd44ee"
},
"outputs": [],
"source": [
"display_name = content_name\n",
"gcs_output_uri_prefix = f\"{BUCKET_NAME}/{display_name}\"\n",
"\n",
"replica_count = 4\n",
"machine_type = \"n1-standard-4\"\n",
"\n",
"args = [\n",
" \"--backend\",\n",
" \"gloo\",\n",
" \"--no-cuda\",\n",
" \"--batch-size\",\n",
" \"128\",\n",
" \"--epochs\",\n",
" \"25\",\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ae4c57df7e07"
},
"outputs": [],
"source": [
"custom_container_training_job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=display_name,\n",
" container_uri=custom_container_image_uri,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "35cf3ecdf0df"
},
"outputs": [],
"source": [
"custom_container_training_job.run(\n",
" args=args,\n",
" base_output_dir=gcs_output_uri_prefix,\n",
" replica_count=replica_count,\n",
" machine_type=machine_type,\n",
" tensorboard=tensorboard.resource_name,\n",
" service_account=SERVICE_ACCOUNT,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "49d10dded73b"
},
"outputs": [],
"source": [
"print(f\"Custom Training Job Name: {custom_container_training_job.resource_name}\")\n",
"print(f\"GCS Output URI Prefix: {gcs_output_uri_prefix}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "78398f52807b"
},
"source": [
"### Training Output Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fc74422de1d1"
},
"outputs": [],
"source": [
"! gsutil ls $gcs_output_uri_prefix"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5e99a6a05b10"
},
"source": [
"## Clean Up Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b0c1b3f7466b"
},
"outputs": [],
"source": [
"! gsutil rm -rf $gcs_output_uri_prefix"
]
}
],
"metadata": {
"colab": {
"name": "multi_node_ddp_gloo_vertex_training_with_custom_container.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,347 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a6b56b1c7b76"
},
"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": "20a5ea0081d0"
},
"source": [
"# PyTorch Image Classification Multi-Node Distributed Data Parallel Training on GPU using Vertex Training with Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8752d4a255fb"
},
"source": [
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/community-content/pytorch_image_classification_distributed_data_parallel_training_with_vertex_sdk/multi_node_ddp_nccl_vertex_training_with_custom_container.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "03d216c7f7b1"
},
"source": [
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c5ac73516218"
},
"outputs": [],
"source": [
"PROJECT_ID = \"YOUR PROJECT ID\"\n",
"BUCKET_NAME = \"gs://YOUR BUCKET NAME\"\n",
"REGION = \"YOUR REGION\"\n",
"SERVICE_ACCOUNT = \"YOUR SERVICE ACCOUNT\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0b5ae674177e"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_NAME"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "19a9b3bdd553"
},
"outputs": [],
"source": [
"content_name = \"pt-img-cls-multi-node-ddp-cust-cont\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5307fe28b633"
},
"source": [
"## Vertex Training using Vertex SDK and Custom Container"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "46cb58c7fbf9"
},
"source": [
"### Built Custom Container"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "97e66e9f9bab"
},
"outputs": [],
"source": [
"hostname = \"gcr.io\"\n",
"image_name = content_name\n",
"tag = \"latest\"\n",
"\n",
"custom_container_image_uri = f\"{hostname}/{PROJECT_ID}/{image_name}:{tag}\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ae9b29c4773f"
},
"source": [
"### Initialize Vertex SDK"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dc1e84d5dec2"
},
"outputs": [],
"source": [
"! pip install -r requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6964be27b98e"
},
"outputs": [],
"source": [
"from google.cloud import aiplatform\n",
"\n",
"aiplatform.init(\n",
" project=PROJECT_ID,\n",
" staging_bucket=BUCKET_NAME,\n",
" location=REGION,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "594a91f438f2"
},
"source": [
"### Create a Vertex Tensorboard Instance"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "93134273261e"
},
"outputs": [],
"source": [
"content_name = content_name + \"-gpu\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c2bd82dbcd9b"
},
"outputs": [],
"source": [
"tensorboard = aiplatform.Tensorboard.create(\n",
" display_name=content_name,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ebc593c6472e"
},
"source": [
"#### Option: Use a Previously Created Vertex Tensorboard Instance\n",
"\n",
"```\n",
"tensorboard_name = \"Your Tensorboard Resource Name or Tensorboard ID\"\n",
"tensorboard = aiplatform.Tensorboard(tensorboard_name=tensorboard_name)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0769e8e34c2f"
},
"source": [
"### Run a Vertex SDK CustomContainerTrainingJob"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "023f33ece826"
},
"outputs": [],
"source": [
"display_name = content_name\n",
"gcs_output_uri_prefix = f\"{BUCKET_NAME}/{display_name}\"\n",
"\n",
"replica_count = 1\n",
"machine_type = \"n1-standard-4\"\n",
"accelerator_count = 4\n",
"accelerator_type = \"NVIDIA_TESLA_K80\"\n",
"\n",
"args = [\n",
" \"--backend\",\n",
" \"nccl\",\n",
" \"--batch-size\",\n",
" \"128\",\n",
" \"--epochs\",\n",
" \"25\",\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d4b599e726ef"
},
"outputs": [],
"source": [
"custom_container_training_job = aiplatform.CustomContainerTrainingJob(\n",
" display_name=display_name,\n",
" container_uri=custom_container_image_uri,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "81321e3bdf7f"
},
"outputs": [],
"source": [
"custom_container_training_job.run(\n",
" args=args,\n",
" base_output_dir=gcs_output_uri_prefix,\n",
" replica_count=replica_count,\n",
" machine_type=machine_type,\n",
" accelerator_count=accelerator_count,\n",
" accelerator_type=accelerator_type,\n",
" tensorboard=tensorboard.resource_name,\n",
" service_account=SERVICE_ACCOUNT,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5100712c2c4c"
},
"outputs": [],
"source": [
"print(f\"Custom Training Job Name: {custom_container_training_job.resource_name}\")\n",
"print(f\"GCS Output URI Prefix: {gcs_output_uri_prefix}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f9b77676e5a6"
},
"source": [
"### Training Output Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0e171ce95ace"
},
"outputs": [],
"source": [
"! gsutil ls $gcs_output_uri_prefix"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cf1b74a12b87"
},
"source": [
"## Clean Up Artifact"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a0b15089c341"
},
"outputs": [],
"source": [
"! gsutil rm -rf $gcs_output_uri_prefix"
]
}
],
"metadata": {
"colab": {
"name": "multi_node_ddp_nccl_vertex_training_with_custom_container.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -1,30 +0,0 @@
# PyTorch Deployment on Google Cloud: Text Classification
**This is an Experimental release**, covered by the Pre-GA Offerings Terms of your Google Cloud Platform [Terms of Service](https://cloud.google.com/terms).
Experiments are focused on validating a prototype and are not guaranteed to be released. They are not intended for production use or covered by any SLA, support obligation, or deprecation policy and might be subject to backward-incompatible changes.
**Kindly drop us a note before you run any scale tests.**
**Do not hesitate to contact vertexai-prediction-preview-feedback@google.com if you have any questions or run into any issues.**
The projects need to be added to the allowlist in order to deploy PyTorch models using Vertex AI Prediction pre-built PyTorch images. If you are interested in the feature, please send an email to vertexai-prediction-preview-feedback@google.com to provide your project numbers OR project ids.
## Overview
In the PyTorch on Google Cloud series of blog posts, we aim to share how to deploy PyTorch models at scale on [Vertex AI](https://cloud.google.com/vertex-ai).
This tutorial on text classification shows how to deploy a PyTorch based text classification model on [Vertex AI](https://cloud.google.com/vertex-ai/docs/start/client-libraries#python) using Vertex SDK and [`gcloud ai`](https://cloud.google.com/sdk/gcloud/reference/beta/ai).
## Notebooks
| <h4>Notebook</h4> | <h4>Description</h4> |
| :-------- | :------- |
| [pytorch-text-classification-vertex-ai-deploy.ipynb](./pytorch-text-classification-vertex-ai-deploy.ipynb) | Notebook to show deploying a PyTorch model on Vertex AI |
## Folders
| <h4>Folder Name</h4> | <h4>Description</h4> |
| :-------- | :------- |
| [`predictor`](./predictor) | Folder with custom prediction handler to deploy a PyTorch model to Vertex Prediction. In the [notebook](./pytorch-text-classification-vertex-ai-deploy.ipynb), this folder is used for deploying a PyTorch model on Vertex AI using Vertex Prediction pre-built PyTorch images |
@@ -1,91 +0,0 @@
import os
import json
import logging
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from ts.torch_handler.base_handler import BaseHandler
logger = logging.getLogger(__name__)
class TransformersClassifierHandler(BaseHandler):
"""
The handler takes an input string and returns the classification text
based on the serialized transformers checkpoint.
"""
def __init__(self):
super(TransformersClassifierHandler, self).__init__()
self.initialized = False
def initialize(self, ctx):
""" Loads the model.pt file and initialized the model object.
Instantiates Tokenizer for preprocessor to use
Loads labels to name mapping file for post-processing inference response
"""
self.manifest = ctx.manifest
properties = ctx.system_properties
model_dir = properties.get("model_dir")
self.device = torch.device("cuda:" + str(properties.get("gpu_id")) if torch.cuda.is_available() else "cpu")
# Read model serialize/pt file
serialized_file = self.manifest["model"]["serializedFile"]
model_pt_path = os.path.join(model_dir, serialized_file)
if not os.path.isfile(model_pt_path):
raise RuntimeError("Missing the model.pt or pytorch_model.bin file")
# Load model
self.model = AutoModelForSequenceClassification.from_pretrained(model_dir)
self.model.to(self.device)
self.model.eval()
logger.debug('Transformer model from path {0} loaded successfully'.format(model_dir))
# Ensure to use the same tokenizer used during training
self.tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')
# Read the mapping file, index to object name
mapping_file_path = os.path.join(model_dir, "index_to_name.json")
if os.path.isfile(mapping_file_path):
with open(mapping_file_path) as f:
self.mapping = json.load(f)
else:
logger.warning('Missing the index_to_name.json file. Inference output will default.')
self.mapping = {"0": "Negative", "1": "Positive"}
self.initialized = True
def preprocess(self, data):
""" Preprocessing input request by tokenizing
Extend with your own preprocessing steps as needed
"""
text = data[0].get("data")
if text is None:
text = data[0].get("body")
sentences = text.decode('utf-8')
logger.info("Received text: '%s'", sentences)
# Tokenize the texts
tokenizer_args = ((sentences,))
inputs = self.tokenizer(*tokenizer_args,
padding='max_length',
max_length=128,
truncation=True,
return_tensors = "pt")
return inputs
def inference(self, inputs):
""" Predict the class of a text using a trained transformer model.
"""
prediction = self.model(inputs['input_ids'].to(self.device))[0].argmax().item()
if self.mapping:
prediction = self.mapping[str(prediction)]
logger.info("Model predicted: '%s'", prediction)
return [prediction]
def postprocess(self, inference_output):
return inference_output
@@ -1,5 +0,0 @@
{
"0": "Negative",
"1": "Positive"
}
@@ -658,8 +658,8 @@
},
"outputs": [],
"source": [
"dataset = load_dataset(\"imdb\")\n",
"dataset"
"datasets = load_dataset(\"imdb\")\n",
"datasets"
]
},
{
@@ -668,7 +668,7 @@
"id": "RzfPtOMoIrIu"
},
"source": [
"The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set."
"The `datasets` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set."
]
},
{
@@ -681,12 +681,12 @@
"source": [
"print(\n",
" \"Total # of rows in training dataset {} and size {:5.2f} MB\".format(\n",
" dataset[\"train\"].shape[0], dataset[\"train\"].size_in_bytes / (1024 * 1024)\n",
" datasets[\"train\"].shape[0], datasets[\"train\"].size_in_bytes / (1024 * 1024)\n",
" )\n",
")\n",
"print(\n",
" \"Total # of rows in test dataset {} and size {:5.2f} MB\".format(\n",
" dataset[\"test\"].shape[0], dataset[\"test\"].size_in_bytes / (1024 * 1024)\n",
" datasets[\"test\"].shape[0], datasets[\"test\"].size_in_bytes / (1024 * 1024)\n",
" )\n",
")"
]
@@ -708,7 +708,7 @@
},
"outputs": [],
"source": [
"dataset[\"train\"][0]"
"datasets[\"train\"][0]"
]
},
{
@@ -728,7 +728,7 @@
},
"outputs": [],
"source": [
"label_list = dataset[\"train\"].unique(\"label\")\n",
"label_list = datasets[\"train\"].unique(\"label\")\n",
"label_list"
]
},
@@ -779,7 +779,7 @@
},
"outputs": [],
"source": [
"show_random_elements(dataset[\"train\"])"
"show_random_elements(datasets[\"train\"])"
]
},
{
@@ -883,7 +883,7 @@
},
"outputs": [],
"source": [
"example = dataset[\"train\"][4]\n",
"example = datasets[\"train\"][4]\n",
"print(example)"
]
},
@@ -920,7 +920,7 @@
"source": [
"# Dataset loading repeated here to make this cell idempotent\n",
"# Since we are over-writing datasets variable\n",
"dataset = load_dataset(\"imdb\")\n",
"datasets = load_dataset(\"imdb\")\n",
"\n",
"# Mapping labels to ids\n",
"# NOTE: We can extract this automatically but the `Unique` method of the datasets\n",
@@ -948,7 +948,7 @@
"\n",
"\n",
"# apply preprocessing function to input examples\n",
"dataset = dataset.map(preprocess_function, batched=True, load_from_cache_file=True)"
"datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=True)"
]
},
{
@@ -1091,8 +1091,8 @@
"trainer = Trainer(\n",
" model,\n",
" args,\n",
" train_dataset=dataset[\"train\"],\n",
" eval_dataset=dataset[\"test\"],\n",
" train_dataset=datasets[\"train\"],\n",
" eval_dataset=datasets[\"test\"],\n",
" data_collator=default_data_collator,\n",
" tokenizer=tokenizer,\n",
" compute_metrics=compute_metrics,\n",
+2 -9
View File
@@ -7,17 +7,15 @@
/gapic @andrewferlitsch
/gapic/custom/showcase_custom_image_classification_online_explain_example_based_api.ipynb @inardini
/ml_ops @andrewferlitsch
/model_monitoring/* @andrewferlitsch
/model_monitoring/* @mco-gh
/structured_data/rapid_prototyping_* @rafael-carvalho
/managed_notebooks/
/bigquery_ml/ @polong
/sdk/SDK_FBProphet_Forecasting_Online.ipynb @brianchunkang
/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb @brianchunkang
/explainable_ai/SDK_Custom_Container_XAI.ipynb @brianchunkang
/matching_engine/sdk_matching_engine_for_indexing.ipynb @ivanmkc
/matching_engine/matching_engine_for_indexing.ipynb @yinghsienwu
/matching_engine/stream_update_for_matching_engine.ipynb @peterping666
/sdk/pytorch_lightning_custom_container_training.ipynb @brianchunkang
/tensorboard @yfang1
/feature_store @nayaknishant @morgandu
@@ -28,9 +26,4 @@
/notebooks/community/ml_ops/stage2/get_started_with_visionapi_and_automl.ipynb @mansari
/notebooks/community/neo4j/graph_paysim.ipynb @benofben @laeg
/notebooks/community/ml_ops/stage1/get_started_with_visionapi_and_vertex_datasets.ipynb @mansari
/notebooks/community/pipelines/google_cloud_pipeline_components_bqml_pipeline_demand_forecasting.ipynb @inardini
/notebooks/community/ml_ops/stage2/get_started_vertex_hpt_r_kernel.ipynb @fhirschmann
/notebooks/community/ml_ops/stage2/get_started_vertex_training_r_using_r_kernel.ipynb @fhirschmann
/notebooks/community/vertex-ai-samples/notebooks/community/model_registry/vertex_ai_model_registry_bqml_custom_model_versioning.ipynb @inardini
/notebooks/community/vertex-ai-samples/notebooks/community/model_registry/vertex_ai_model_registry_automl_model_versioning.ipynb @inardini
/notebooks/community/vizier/conversions_vertex_vizier_and_open_source_vizier.ipynb @halio-g
/notebooks/community/pipelines/google_cloud_pipeline_components_bqml_pipeline_demand_forecasting.ipynb @inardini
@@ -29,28 +29,18 @@
"id": "JAPoU8Sm5E6e"
},
"source": [
"# Using Vertex AI Feature Store with pandas DataFrame\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/feature_store/sdk-feature-store-pandas.ipynb\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/feature_store/sdk-feature-store-pandas.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/feature_store/sdk-feature-store-pandas.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" \n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/feature_store/sdk-feature-store-pandas.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> \n",
" Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\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/feature_store/sdk-feature-store-pandas.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
@@ -62,29 +52,7 @@
"source": [
"## Overview\n",
"\n",
"This notebook introduces Pandas support for Feature Store using Vertex AI SDK. For pre-requisites and introduction on Vertex AI SDK and Feature Store native support, please go through this [Colab notebook](https://colab.sandbox.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/feature_store/sdk-feature-store.ipynb). "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DxF5JWRVT5PP"
},
"source": [
"### Objective\n",
"\n",
"In this notebook, you learn how to use `Vertex AI Feature Store` with pandas DataFrame.\n",
"\n",
"The steps performed include:\n",
"\n",
"- Ingest Feature values from Pandas DataFrame into Feature Store's Entity types.\n",
"- Read Entity Feature values from Online Feature Store into Pandas DataFrame.\n",
"- Batch serve Feature values from your Feature Store into Pandas DataFrame.\n",
"\n",
"You also learn how Vertex AI Feature Store can be useful in the below scenarios:\n",
"\n",
"- Online serving with updated feature values.\n",
"- Point-in-time correctness to fetch feature values for training."
"This Colab introduces Pandas support of Vertex AI SDK Feature Store. For pre-requisite and introduction for Vertex AI SDK Feature Store native support, please see this [Colab](https://colab.sandbox.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/feature_store/sdk-feature-store.ipynb). "
]
},
{
@@ -95,7 +63,27 @@
"source": [
"### Dataset\n",
"\n",
"This tutorial uses a movie recommendation dataset as an example throughout all the notebooks including this one. The original task is to train a model to predict if a user is going to watch a movie and serve the model online."
"This Colab uses a movie recommendation dataset as an example throughout all the sessions. The task is to train a model to predict if a user is going to watch a movie and serve this model online."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DxF5JWRVT5PP"
},
"source": [
"### Objective\n",
"\n",
"In this notebook, you will learn how to:\n",
"\n",
" * Ingest Feature Values from Pandas DataFrame into featurestore's entity types.\n",
" * Read Entity Feature Values from Online Feature Store into Pandas DataFrame.\n",
" * Batch Serve Feature Values from your featurestore to Pandas DataFrame.\n",
"\n",
"We will also discuss how Vertex AI Feature Store can be useful in the below scenarios:\n",
"\n",
" * online serving with updated feature values\n",
" * point-in-time correctness to fetch feature values for training"
]
},
{
@@ -109,9 +97,11 @@
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud BigQuery\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing) and use the [Pricing\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."
]
@@ -133,7 +123,7 @@
"source": [
"### Install additional packages\n",
"\n",
"To run this notebook, you need to install the following packages for Python."
"For this Colab, you need the Vertex SDK for Python."
]
},
{
@@ -152,14 +142,35 @@
"# Google Cloud Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_GOOGLE_CLOUD_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
" \n",
"! pip install -U {USER_FLAG} --upgrade google-cloud-aiplatform \\\n",
" google-cloud-bigquery \\\n",
" google-cloud-bigquery-storage \\\n",
" avro \\\n",
" pyarrow \\\n",
" pandas -q"
" USER_FLAG = \"--user\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Kd0kgDqVZyRe"
},
"outputs": [],
"source": [
"! pip uninstall {USER_FLAG} -y google-cloud-aiplatform\n",
"! pip uninstall {USER_FLAG} -y google-cloud-bigquery\n",
"! pip uninstall {USER_FLAG} -y google-cloud-bigquery-storage\n",
"! pip uninstall {USER_FLAG} -y google-cloud-aiplatform"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wUswAmpiN2l-"
},
"outputs": [],
"source": [
"! pip install {USER_FLAG} --upgrade google-cloud-aiplatform\n",
"! pip install {USER_FLAG} --upgrade google-cloud-bigquery\n",
"! pip install {USER_FLAG} --upgrade google-cloud-bigquery-storage\n",
"! pip install {USER_FLAG} avro"
]
},
{
@@ -170,7 +181,7 @@
"source": [
"### Restart the kernel\n",
"\n",
"After you install the packages, you need to restart the notebook kernel so that it can find the packages."
"After you install the SDK, you need to restart the notebook kernel so it can find the packages. You can restart kernel from *Kernel -> Restart Kernel*, or running the following:"
]
},
{
@@ -227,17 +238,6 @@
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dcdfccf50581"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -246,56 +246,37 @@
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
"import os\n",
"\n",
"PROJECT_ID = \"\"\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "09021c90b34c"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
" print(\"Project ID: \", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f41eda68c379"
"id": "qJYoRfYng0XZ"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)"
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5c615e53149f"
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"\" # @param {type:\"string\"}\n",
"print(\"Project ID: \", PROJECT_ID)"
]
},
{
@@ -395,6 +376,8 @@
"import pandas as pd\n",
"from google.cloud import aiplatform\n",
"\n",
"REGION = \"\" # @param {type:\"string\"}\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION)"
]
},
@@ -413,11 +396,11 @@
"id": "buQBIv3ZL3A0"
},
"source": [
"### Create Feature Store\n",
"### Create Featurestore\n",
"\n",
"The method to create a Feature Store returns a\n",
"The method to create a Featurestore returns a\n",
"[long-running operation](https://google.aip.dev/151) (LRO). An LRO starts an asynchronous job. LROs are returned for other API\n",
"methods too, such as updating or deleting a featurestore. Running the code cell creates a featurestore and prints the process logs."
"methods too, such as updating or deleting a featurestore. Running the code cell will create a featurestore and print the process log."
]
},
{
@@ -442,7 +425,7 @@
"source": [
"### Create Entity Types\n",
"\n",
"Entity types can be created within the Featurestore class. Below, you create the `Users` entity type and `Movies` entity type. Process logs are printed in the output for each cell."
"Entity types can be created within the Featurestore class. Below, create the Users entity type and Movies entity type. A process log will be printed out."
]
},
{
@@ -480,7 +463,7 @@
},
"source": [
"### Create Features\n",
"Features can be created within each entity type. Add defining features to the `Users` entity type and `Movies` entity type by using the following methods."
"Features can be created within each entity type. Add defining features to the Users entity type and Movies entity type by using the following methods."
]
},
{
@@ -564,7 +547,7 @@
"id": "BlqJ-QdTcs6W"
},
"source": [
"#### Get data from source files"
"#### Entity Type Source Files"
]
},
{
@@ -660,7 +643,7 @@
"id": "bgb0WGwX5OW6"
},
"source": [
"#### Ingest Feature Values into _Users_ Entity Type"
"#### Ingest Feature Values into Users Entity Type"
]
},
{
@@ -685,7 +668,7 @@
"id": "PCAdQ3cF5OW6"
},
"source": [
"#### Ingest Feature Values into _Movies_ Entity Type"
"#### Ingest Feature Values into Movies Entity Type"
]
},
{
@@ -751,9 +734,9 @@
"id": "AK2Glzkq5OW7"
},
"source": [
"## Batch Serve Feature Values from Vertex AI Feature Store\n",
"## Batch Serve Featurestore's Feature Values from Vertex AI Feature Store\n",
"\n",
"Batch Serving is used to fetch a large batch of feature values for high-throughput, and is typically used for training a model or batch prediction. In this section, you learn how to prepare training examples by using the Feature Store's batch serve function."
"Batch Serving is used to fetch a large batch of feature values for high-throughput, and is typically used for training a model or batch prediction. In this section, you will learn how to prepare for training examples by using the Featurestore's batch serve function."
]
},
{
@@ -762,7 +745,7 @@
"id": "hxsotHUe5OW7"
},
"source": [
"#### Read instances from source file"
"#### Read Instances Source File"
]
},
{
@@ -773,8 +756,7 @@
},
"outputs": [],
"source": [
"GCS_READ_INSTANCES_CSV_URI = \"gs://cloud-samples-data-us-central1/vertex-ai/feature-store/datasets/movie_prediction.csv\"\n",
"READ_INSTANCES_CSV_FN = \"data.csv\""
"GCS_READ_INSTANCES_CSV_URI = \"gs://cloud-samples-data-us-central1/vertex-ai/feature-store/datasets/movie_prediction.csv\""
]
},
{
@@ -794,7 +776,7 @@
"id": "T5DW1MFt5OW7"
},
"source": [
"#### Load CSV file into a Pandas DataFrame"
"#### Load Csv File into a Pandas DataFrame"
]
},
{
@@ -805,7 +787,7 @@
},
"outputs": [],
"source": [
"read_instances_df = pd.read_csv(READ_INSTANCES_CSV_FN)\n",
"read_instances_df = pd.read_csv(read_instances_csv_fn)\n",
"print(read_instances_df)"
]
},
@@ -837,7 +819,7 @@
"id": "ao1dC5Pc5OW8"
},
"source": [
"#### Batch Serve Feature Values from Movie Predictions Feature Store"
"#### Batch Serve Feature Values from Movie Predictions Featurestore"
]
},
{
@@ -873,8 +855,7 @@
"id": "XN84znoI5OW8"
},
"source": [
"#### Feature Values from last ingestion\n",
"Recall read from the Entity Type shows Feature Values from the last ingestion."
"#### Recall Read from the Entity Type Shows Feature Values from the Last Ingestion"
]
},
{
@@ -894,7 +875,7 @@
"id": "feTUJjqG5OW9"
},
"source": [
"#### Ingest updated Feature Values"
"#### Ingest Updated Feature Values"
]
},
{
@@ -934,8 +915,7 @@
"id": "s47WCIvL5OW9"
},
"source": [
"#### Latest Feature Values\n",
"Read from the Entity Type shows updated Feature values from the latest ingestion."
"#### Read from the Entity Type Shows Updated Feature Values from the Latest Ingestion"
]
},
{
@@ -968,8 +948,7 @@
"id": "R1YGRNsW5OW9"
},
"source": [
"#### Missing data\n",
"Recall Batch Serve from the last ingestion has some missing data in it."
"#### Recall Batch Serve From the Last Ingestion Has Missing Data"
]
},
{
@@ -989,7 +968,7 @@
"id": "abQRF6mx5OW-"
},
"source": [
"#### Backfill/Correct point-in-time data"
"#### Backfill/Correct Point-in-Time Data"
]
},
{
@@ -1030,7 +1009,7 @@
"id": "WXb4JUhu5OW-"
},
"source": [
"#### Ingest backfilled/corrected point-in-time data from dataframe"
"#### Ingest Backfill/Correct Point-in-Time Data"
]
},
{
@@ -1071,8 +1050,7 @@
"id": "1e62Ku6W5OW_"
},
"source": [
"#### Latest ingestion with imputed missing data\n",
"Batch Serve from the latest ingestion with backfill/correction has reduced missing data."
"#### Batch Serve From the Latest Ingestion with Backfill/Correction Has Reduced Missing Data"
]
},
{

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

@@ -1,55 +1,29 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {
"id": "503077811e70"
},
"outputs": [],
"source": [
"# Copyright 2022 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": "e885ac09bc73"
},
"source": [
"# Train a multi-class classification model for ads-targeting\n",
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/ads_targetting/training-multi-class-classification-model-for-ads-targeting-usecase.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/ads_targetting/training-multi-class-classification-model-for-ads-targeting-usecase.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/ads_targetting/training-multi-class-classification-model-for-ads-targeting-usecase.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td> \n",
"</table>"
"## Table of contents\n",
"\n",
"* [Overview](#section-1)\n",
"* [Dataset](#section-2)\n",
"* [Objective](#section-3)\n",
"* [Costs](#section-4)\n",
"* [Tutorial](#section-5)\n",
"\t- [Fetch the data from BigQuery](#section-5)\n",
" - [Preprocess the data](#section-6)\n",
" - [Train a TensorFlow model](#section-7)\n",
" - [Run the model on test data](#section-8)\n",
" - [Automating the execution of the notebook using executor](#section-9)\n",
" - [Scheduled runs on executor](#section-10)\n",
" - [Parameterizing the variables](#section-11)\n",
"* [Save the model to a Cloud Storage path](#section-12)\n",
"* [Clean up](#section-13)\n"
]
},
{
@@ -59,19 +33,23 @@
},
"source": [
"## Overview\n",
"<a name=\"section-1\"></a>\n",
"\n",
"This tutorial demonstrates how to build a machine learning model for an ads-targeting use case. Ads-targeting is an advertisement technique where chosen or tailor-made ads are shown to the customers based on their past behavior and preferences. Targeted ads are meant to reach specific customers based on demographics, psychographics, behavior, and other second-order activities that are learned usually through data collected from the customers.\n",
"\n",
"*Note: If you are using [Vertex AI Workbench managed notebooks](https://cloud.google.com/vertex-ai/docs/workbench/managed/create-instance) instance use the `TensorFlow 2 (Local)` kernel. Some components of this notebook may not work in other notebook environments.*\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1bea2b6e9b25"
},
"source": [
"*Note: This notebook file was designed to run in a [Vertex AI Workbench managed notebooks](https://cloud.google.com/vertex-ai/docs/workbench/managed/create-instance) instance using the `TensorFlow 2 (Local)` kernel. Some components of this notebook may not work in other notebook environments.*\n",
"\n",
"## Dataset\n",
"<a name=\"section-2\"></a>\n",
"\n",
"This tutorial uses the `looker-private-demo.ecomm` dataset in BigQuery. The dataset consists of information about various advertisement campaigns including the demographics of users who have clicked and made some purchases after seeing the ads. For this tutorial, the top three campaigns from the USA are selected from this dataset and user information for those who have made purchases shall be used to train a model with the campaigns as the classes. The idea is to see if the advertisement and the user data can be used to identify which campaign is best-suited for the user.\n",
"\n",
"The dataset can be accessed by pinning the `looker-private-demo` project in BigQuery. Instead of going to the BigQuery user interface, this process can be performed from the JupyterLab user interface on a Vertex AI Workbench managed notebooks instance. Vertex AI Workbench managed notebooks instances support browsing through the datasets and tables from BigQuery through its BigQuery integration. \n",
"\n",
"<img src=\"images/Bigquery_UI_new.PNG\"></img>\n",
"\n",
"## Objective\n",
"<a name=\"section-3\"></a>\n",
"\n",
"This tutorial demonstrates how to collect data from BigQuery, preprocess it, and train a multi-class classification model on an E-commerce dataset. The steps performed include the following:\n",
"\n",
@@ -81,31 +59,10 @@
"- Evaluate the loss for the trained model\n",
"- Automate the notebook execution using the executor feature\n",
"- Save the model to a Cloud Storage path\n",
"- Clean up the created resources"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "34d623e6dfa3"
},
"source": [
"## Dataset\n",
"- Clean up the created resources\n",
"\n",
"This tutorial uses the `looker-private-demo.ecomm` dataset in BigQuery. The dataset consists of information about various advertisement campaigns including the demographics of users who have clicked and made some purchases after seeing the ads. For this tutorial, the top three campaigns from the USA are selected from this dataset and user information for those who have made purchases shall be used to train a model with the campaigns as the classes. The idea is to see if the advertisement and the user data can be used to identify which campaign is best-suited for the user.\n",
"\n",
"The dataset can be accessed by pinning the `looker-private-demo` project in BigQuery. If you are using Vertex AI Workbench managed notebooks instance, instead of going to the BigQuery user interface, this process can be performed from the JupyterLab user interface. Vertex AI Workbench managed notebooks instances support browsing through the datasets and tables from BigQuery through its BigQuery integration. \n",
"\n",
"<img src=\"images/Bigquery_UI_new.PNG\"></img>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ee02650bb7fd"
},
"source": [
"### Costs \n",
"<a name=\"section-4\"></a>\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -121,121 +78,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "y320EIk-kXT7"
},
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"\n",
"* The Google Cloud SDK\n",
"* Git\n",
"* Python 3\n",
"* virtualenv\n",
"* Jupyter notebook running in a virtual environment with Python 3\n",
"\n",
"The Google Cloud guide to [Setting up a Python development\n",
"environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
"installation guide](https://jupyter.org/install) provide detailed instructions\n",
"for meeting these requirements. The following steps provide a condensed set of\n",
"instructions:\n",
"\n",
"1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
"\n",
"1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
"\n",
"1. [Install\n",
" virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
" and create a virtual environment that uses Python 3. Activate the virtual environment.\n",
"\n",
"1. To install Jupyter, run `pip3 install jupyter` on the\n",
"command-line in a terminal shell.\n",
"\n",
"1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n",
"\n",
"1. Open this notebook in the Jupyter Notebook Dashboard."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1DouUvNOkXT8"
},
"source": [
"### Install additional packages\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ayt1jhFXkXT9"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "95826791kXT_"
},
"outputs": [],
"source": [
"! pip3 install {USER_FLAG} --upgrade pandas-gbq 'google-cloud-bigquery[bqstorage,pandas]' tensorflow sklearn protobuf==3.20.1 -q \\\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aNeMRbpukXUA"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dJ_yvi_9kXUB"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -255,67 +97,34 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5bf9979b96ff"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
"PROJECT_ID = \"\"\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "07-xo93jlC6l"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
" print(\"Project ID: \", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "03d8d65b914d"
"id": "d0058f55f8cf"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3281bedf6d3c"
"id": "19579640c063"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
@@ -342,74 +151,6 @@
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OoPGk5KOkXUG"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. Skip this step.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Teyy6LGqkXUG"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -420,8 +161,20 @@
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you submit a training job using the Cloud SDK, you upload a Python package\n",
"containing your training code to a Cloud Storage bucket. Vertex AI runs\n",
"the code from this package. In this tutorial, Vertex AI also saves the\n",
"trained model that results from your job in the same bucket. Using this model artifact, you can then\n",
"create Vertex AI model and endpoint resources in order to serve\n",
"online predictions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all\n",
"Cloud Storage buckets.\n"
"Cloud Storage buckets.\n",
"\n",
"You may also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Make sure to [choose a region where Vertex AI services are\n",
"available](https://cloud.google.com/vertex-ai/docs/general/locations#available_regions). You may\n",
"not use a Multi-Regional Storage bucket for training with Vertex AI."
]
},
{
@@ -432,8 +185,8 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_NAME = \"gs://[your-bucket-name]\" # @param {type:\"string\"}\n",
"REGION = \"[your-region]\" # @param {type:\"string\"}"
]
},
{
@@ -444,9 +197,8 @@
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
]
},
{
@@ -466,7 +218,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
"! gsutil mb -l $REGION $BUCKET_NAME"
]
},
{
@@ -486,36 +238,7 @@
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bmnMD2MjkXUJ"
},
"source": [
"### Import libraries and define constants"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oqtZRqDEkXUJ"
},
"outputs": [],
"source": [
"import warnings\n",
"\n",
"import pandas as pd\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.preprocessing import StandardScaler\n",
"from tensorflow.keras import Sequential\n",
"from tensorflow.keras.layers import Dense\n",
"from tensorflow.keras.utils import to_categorical\n",
"\n",
"warnings.filterwarnings(\"ignore\")"
"! gsutil ls -al $BUCKET_NAME"
]
},
{
@@ -526,16 +249,8 @@
"source": [
"## Tutorial\n",
"\n",
"### Fetch the data from BigQuery \n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5c07be8840ae"
},
"source": [
"If you are using ***Vertex AI Workbench managed notebooks instance***, below cell which starts with \"#@bigquery\" will be a SQL Query. If you are using Vertex AI Workbench user managed notebooks instance or Colab it will be a markdown cell."
"### Fetch the data from BigQuery \n",
"<a name=\"section-5\"></a>"
]
},
{
@@ -616,7 +331,7 @@
"id": "923fdd823683"
},
"source": [
"If you are using Vertex AI Workbench managed notebooks instance, once the results from BigQuery are displayed in the above cell, click the **Query and load as DataFrame** button and execute the generated code stub to fetch the data into the current notebook as a dataframe.\n",
"Once the results from BigQuery are displayed in the above cell, click the **Query and load as DataFrame** button and execute the generated code stub to fetch the data into the current notebook as a dataframe.\n",
"\n",
"*Note: By default the data is loaded into a `df` variable, though this can be changed before executing the cell if required.*"
]
@@ -633,7 +348,7 @@
"# Comment out otherwise for speed-up.\n",
"from google.cloud.bigquery import Client\n",
"\n",
"client = Client(project=PROJECT_ID)\n",
"client = Client()\n",
"\n",
"query = \"\"\"WITH traindata AS (\n",
"SELECT b.* except(ad_event_id, user_id), c.* except(id), d.* except(keyword_id, ad_id), a.amount, a.device_type, e.name\n",
@@ -664,6 +379,44 @@
},
"source": [
"### Preprocess the data\n",
"<a name=\"section-6\"></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e8503e799eec"
},
"source": [
"Import the required libraries."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5b11973ccf76"
},
"outputs": [],
"source": [
"import warnings\n",
"\n",
"import pandas as pd\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.preprocessing import StandardScaler\n",
"from tensorflow.keras import Sequential\n",
"from tensorflow.keras.layers import Dense\n",
"from tensorflow.keras.utils import to_categorical\n",
"\n",
"warnings.filterwarnings(\"ignore\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e48d156d8bb6"
},
"source": [
"Select the necessary columns from the E-commerce data and divide them based on their type (numerical/categorical)."
]
},
@@ -688,22 +441,13 @@
"num_cols = [\"age\", \"cpc_bid_amount\", \"quality_score\", \"amount\"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9bd71de0d37e"
},
"source": [
"#### Select top three campaigns"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ace612851261"
},
"source": [
"From the current dataset, only the top three campaigns will be chosen to target the users. All the relevant information about the advertisement and the user who purchased an item after seeing the advertisement is available in the dataframe already. "
"From the current dataset, only the top three camapigns will be chosen to target the users. All the relevant information about the advertisement and the user who purchased an item after seeing the advertisement is available in the dataframe already. "
]
},
{
@@ -737,22 +481,13 @@
"df[\"name\"] = df[\"name\"].map({\"Tops & Tees\": 0, \"Active\": 1, \"Accessories\": 2})"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c2d5338b1b95"
},
"source": [
"#### One-hot encode the categorical variables"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8902f763d1ca"
},
"source": [
"After one-hot encoding, the first level-column is dropped to avoid the [dummy-variable trap](https://en.wikipedia.org/wiki/Dummy_variable_(statistics)) scenario. This process is called *dummy-encoding*."
"One-hot encode the categorical variables. After one-hot encoding, the first level-column is dropped to avoid the [dummy-variable trap](https://en.wikipedia.org/wiki/Dummy_variable_(statistics)) scenario. This process is called *dummy-encoding*."
]
},
{
@@ -786,7 +521,7 @@
"id": "3abf027eda2d"
},
"source": [
"#### Split the data into train and test."
"Split the data into train and test."
]
},
{
@@ -811,7 +546,7 @@
"id": "d1a32b9d9640"
},
"source": [
"#### Scale the data."
"Scale the data."
]
},
{
@@ -834,7 +569,16 @@
},
"source": [
"### Train a TensorFlow model\n",
"#### Convert the target column to a categorical encoded colum (one-hot encoded)."
"<a name=\"section-7\"></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3e7656556a48"
},
"source": [
"Convert the target column to a categorical encoded colum (one-hot encoded)."
]
},
{
@@ -855,7 +599,7 @@
"id": "3dd0014a7e1d"
},
"source": [
"#### Define hyperparameters for model training. \n",
"Define hyperparameters for model training. \n",
"\n",
"*Note: Comment or remove the parameters from the following cell if they are provided already as an input parameter through the executor feature.*"
]
@@ -880,7 +624,7 @@
"id": "406b731f576b"
},
"source": [
"#### Define the architecture and compile the model."
"Define the architecture and compile the model."
]
},
{
@@ -920,7 +664,7 @@
"id": "4ab12c34f258"
},
"source": [
"#### Fit the model."
"Fit the model."
]
},
{
@@ -940,7 +684,8 @@
"id": "51a2d0b52df3"
},
"source": [
"### Run the model on test data\n"
"### Run the model on test data\n",
"<a name=\"section-8\"></a>"
]
},
{
@@ -949,7 +694,7 @@
"id": "f08445f2cd02"
},
"source": [
"#### Evaluate the model on test data."
"Evaluate the model on test data."
]
},
{
@@ -964,24 +709,16 @@
"print(f\"Test results - Loss: {test_results}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "81ef0e081340"
},
"source": [
"**Please note that executor feature is available only in Vertex AI Workbench managed notebooks**"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9769168778e8"
},
"source": [
"### Automating the execution of the notebook using executor in Vertex AI Workbench managed notebooks instance\n",
"### Automating the execution of the notebook using executor\n",
"<a name=\"section-9\"></a>\n",
"\n",
"If you are using Vertex AI Workbench managed notebooks instance, the executor can help you run a notebook file from start to end, with your choice of the environment, machine type, input parameters, and other characteristics. After setting up an execution, the notebook is executed as a job in Vertex AI custom training. Your jobs can be monitored from the <b>Notebook Executor</b> pane in the menu on the left.\n",
"The executor can help you run a notebook file from start to end, with your choice of the environment, machine type, input parameters, and other characteristics. After setting up an execution, the notebook is executed as a job in Vertex AI custom training. Your jobs can be monitored from the <b>Notebook Executor</b> pane in the menu on the left.\n",
"\n",
"<img src=\"images/executor.png\"></img>\n",
"\n",
@@ -994,9 +731,10 @@
"id": "cf486c351581"
},
"source": [
"### Scheduled runs on executor in Vertex AI Workbench managed notebooks instance\n",
"### Scheduled runs on executor\n",
"<a name=\"section-10\"></a>\n",
"\n",
"Vertex AI Workbench managed noteboook runs can also be scheduled recurringly with the executor. To do so, select <b>Schedule-based recurring executions</b> as the run type instead of <b>One-time execution</b>. The frequency of the job and the time when it executes is provided when you create the execution.\n",
"Notebook runs can also be scheduled recurringly with the executor. To do so, select <b>Schedule-based recurring executions</b> as the run type instead of <b>One-time execution</b>. The frequency of the job and the time when it executes is provided when you create the execution.\n",
"\n",
"<img src=\"images/executor_scheduled_runs2.png\"></img>"
]
@@ -1008,8 +746,9 @@
},
"source": [
"### Parameterizing the variables\n",
"<a name=\"section-11\"></a>\n",
"\n",
"If you are using Vertex AI Workbench managed notebooks instance, executor lets you run a notebook with different sets of input parameters. If required, constants in the notebook can be treated as arguments to a function, and when you submit the execution, you can provide those constants as input parameters.\n",
"Executor lets you run a notebook with different sets of input parameters. If required, constants in the notebook can be treated as arguments to a function, and when you submit the execution, you can provide those constants as input parameters.\n",
"\n",
"<img src=\"images/executor_input_parameters.png\"></img>\n",
"\n",
@@ -1023,6 +762,7 @@
},
"source": [
"### Save the model to a Cloud Storage path\n",
"<a name=\"section-12\"></a>\n",
"\n",
"TensorFlow's `model.save()` method supports Cloud Storage paths as well as the local file paths while writing the model object to a file. It needs to be ensured that the service account being used to run this notebook has `write` permissions to the specified Cloud Storage path."
]
@@ -1035,7 +775,7 @@
},
"outputs": [],
"source": [
"GCS_PATH = BUCKET_URI + \"/path-to-save/\"\n",
"GCS_PATH = \"gs://\" + BUCKET_NAME + \"/[path-to-save]/\"\n",
"model.save(GCS_PATH)"
]
},
@@ -1046,6 +786,7 @@
},
"source": [
"## Clean up\n",
"<a name=\"section-13\"></a>\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",
@@ -1061,11 +802,7 @@
},
"outputs": [],
"source": [
"# Delete the Cloud Storage bucket\n",
"\n",
"delete_bucket = False\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_URI"
"! gsutil -m rm -r [cloud-storage-folder-path-to-delete]"
]
}
],

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 63 KiB

@@ -1,62 +1,17 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "18ebbd838e32"
},
"outputs": [],
"source": [
"# Copyright 2022 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": "aef73cfa8725"
},
"source": [
"# Predictive Maintenance using Vertex AI\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/predictive_maintainance/predictive_maintenance_usecase.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/predictive_maintainance/predictive_maintenance_usecase.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\\\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/predictive_maintainance/predictive_maintenance_usecase.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>\n",
"<br/><br/><br/>\n",
"\n",
"# Predictive Maintenance \n",
"\n",
"## Table of contents\n",
"* [Overview](#section-1)\n",
"* [Objective](#section-2)\n",
"* [Dataset](#section-3)\n",
"* [Dataset](#section-2)\n",
"* [Objective](#section-3)\n",
"* [Costs](#section-4)\n",
"* [Data analysis](#section-5)\n",
"* [Fit a regression model](#section-6)\n",
@@ -67,32 +22,24 @@
" * [Create an endpoint](#section-11)\n",
" * [Deploy the model to the created endpoint](#section-12)\n",
" * [Test calling the endpoint](#section-13)\n",
"* [Clean up](#section-14)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e10c5167a061"
},
"source": [
"* [Clean up](#section-14)\n",
"\n",
"\n",
"## Overview\n",
"<a name=\"section-1\"></a>\n",
"\n",
"In this notebook, you go through a predictive maintenance usecase on industrial data using machine learning techniques, deploy the machine learning model on Vertex AI, and automate the workflow using the executor feature of Vertex AI Workbench.\n",
"This notebook demonstrates how to perform predictive maintenance on industrial data using machine learning techniques, deploy the machine learning model on Vertex AI, and automate the workflow using the executor feature of Vertex AI Workbench.\n",
"\n",
"*Note: This notebook file is developed to run in a [Vertex AI Workbench managed notebooks](https://console.cloud.google.com/vertex-ai/workbench/list/managed) instance using the XGBoost (Local) kernel. Some components of this notebook may not work in other notebook environments.*"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fead9e83ebd7"
},
"source": [
"### Objective\n",
"*Note: This notebook file was developed to run in a [Vertex AI Workbench managed notebooks](https://console.cloud.google.com/vertex-ai/workbench/list/managed) instance using the XGBoost (Local) kernel. Some components of this notebook may not work in other notebook environments.*\n",
"\n",
"## Dataset\n",
"<a name=\"section-2\"></a>\n",
"\n",
"The dataset used in this notebook is a part of the [NASA Turbofan Engine Degradation Simulation dataset](https://ti.arc.nasa.gov/tech/dash/groups/pcoe/prognostic-data-repository/), which consists of simulated time-series data for four sets of fleet engines under different combinations of operational conditions and fault modes. In this notebook, only one of the engine's simulated data (FD001) has been used to analyze and train a model that can predict the engine's remaining useful life.\n",
"\n",
"## Objectives\n",
"<a name=\"section-3\"></a>\n",
"\n",
"The objectives of this notebook include:\n",
"\n",
"- Loading the required dataset from a Cloud Storage bucket.\n",
@@ -102,28 +49,9 @@
"- Evaluating the model.\n",
"- Running the notebook end-to-end as a training job using Executor.\n",
"- Deploying the model on Vertex AI.\n",
"- Clean up."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a71f4d96bf80"
},
"source": [
"### Dataset\n",
"<a name=\"section-3\"></a>\n",
"- Clean up.\n",
"\n",
"The dataset used in this notebook is a part of the [NASA Turbofan Engine Degradation Simulation dataset](https://ti.arc.nasa.gov/tech/dash/groups/pcoe/prognostic-data-repository/), which consists of simulated time-series data for four sets of fleet engines under different combinations of operational conditions and fault modes. A version of this dataset which is saved to a public Cloud Storage bucket is used in this notebook. In this notebook, one of the engine's simulated data (FD001) is used to analyze and train a model that can predict the engine's remaining useful life."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "36c53c95b4b9"
},
"source": [
"### Costs\n",
"## Costs\n",
"<a name=\"section-4\"></a>\n",
"\n",
"This tutorial uses the following billable components of Google Cloud:\n",
@@ -141,126 +69,24 @@
{
"cell_type": "markdown",
"metadata": {
"id": "629f52f6efe1"
"id": "5b15a97278df"
},
"source": [
"## Before you begin\n",
"\n",
"### Kernel selection\n",
"Select <b>XGBoost</b> kernel while running this notebook on Vertex AI Workbench's managed instances. Otherwise, ensure that the following libraries are installed in the environment where this notebook is being run.\n",
"Select <b>XGBoost</b> kernel while running this notebook on Vertex AI Workbench managed notebooks instances or ensure that the following libraries are installed in the environment where this notebook is being run.\n",
"- XGBoost\n",
"- Pandas\n",
"- Seaborn\n",
"- Sklearn\n",
"\n",
"Along with the above libraries, th`e following google-cloud libraries are also used in this notebook.\n",
"Along with the above libraries, the following google-cloud libraries are also used in this notebook.\n",
"\n",
"- google.cloud.aiplatform\n",
"- google.cloud.storage"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "16bee0754628"
},
"source": [
"## Installation\n",
"- google.cloud.storage\n",
"\n",
"Install the following packages to run this notebook outside Vertex AI Workbench's managed instances."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "69520a67e54c"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\")\n",
"IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# Vertex AI Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
" \n",
"! pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform \\\n",
" google-cloud-storage \\\n",
" xgboost \\\n",
" seaborn \\\n",
" sklearn \\\n",
" fsspec \\\n",
" gcsfs \\\n",
" pandas -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eda79cca981d"
},
"source": [
"### Restart the kernel\n",
"\n",
"Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e200999cabe5"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5b15a97278df"
},
"source": [
"## Before you begin \n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aee4379e8e5"
},
"source": [
"#### Set your project ID\n",
"### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
@@ -273,67 +99,36 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5bf9979b96ff"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
"import os\n",
"\n",
"PROJECT_ID = \"\"\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "09021c90b34c"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
" print(\"Project ID: \", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9658ecf524b1"
"id": "750bf2883c2d"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. It is recommended that you choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5c615e53149f"
"id": "3c6db1ca88b9"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
@@ -342,9 +137,9 @@
"id": "f66f96816fd0"
},
"source": [
"#### UUID\n",
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
@@ -355,84 +150,9 @@
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"from datetime import datetime\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "df899ce9999c"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "201e8e760d22"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
@@ -441,18 +161,11 @@
"id": "ea53caa30628"
},
"source": [
"### Create a Cloud Storage bucket\n",
"## Select or Create a Cloud Storage Bucket for storing the model\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"When you create a model resource on Vertex AI using the Cloud SDK, you need to give a Cloud Storage bucket URI of the model where the model is stored. Using the model saved, you can then create Vertex AI model and endpoint resources in order to serve online predictions.\n",
"\n",
"\n",
"When you create a model in Vertex AI using the Cloud SDK, you give a Cloud Storage path where the trained model is saved. \n",
"In this tutorial, Vertex AI saves the trained model to a Cloud Storage bucket. Using this model artifact, you can then\n",
"create Vertex AI model and endpoint resources in order to serve\n",
"online predictions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all\n",
"Cloud Storage buckets."
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets. You may also change the `REGION` variable, which is used for operations throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are available."
]
},
{
@@ -463,8 +176,9 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_NAME = \"[your-bucket-name]\"\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\"\n",
"REGION = \"us-central1\""
]
},
{
@@ -475,9 +189,13 @@
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"# Set a default bucketname in case bucket name is not given\n",
"if BUCKET_NAME == \"\" or BUCKET_NAME is None:\n",
" from datetime import datetime\n",
"\n",
" TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
]
},
{
@@ -497,7 +215,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
"! gsutil mb -l $REGION $BUCKET_NAME"
]
},
{
@@ -517,7 +235,7 @@
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil ls -al $BUCKET_NAME"
]
},
{
@@ -526,7 +244,7 @@
"id": "4c0f6aac282a"
},
"source": [
"### Import the required libraries"
"## Import the required libraries"
]
},
{
@@ -569,7 +287,7 @@
"outputs": [],
"source": [
"# load the data from the source\n",
"INPUT_PATH = \"gs://cloud-samples-data/ai-platform-unified/datasets/tabular/predictive_maintenance.csv\" # data source\n",
"INPUT_PATH = \"gs://vertex_ai_managed_services_demo/mfg_predictive_maintenance/train_FD001.txt\" # data source\n",
"raw_data = pd.read_csv(INPUT_PATH, sep=\" \", header=None)\n",
"# check the data\n",
"print(raw_data.shape)\n",
@@ -774,7 +492,7 @@
"id": "8197cdef2cff"
},
"source": [
"As the current objective is to predict the remaining useful life (RUL) of each unit (ID), the target variable needs to be identified. Since you're dealing with a timeseries data that represents the lifetime of a unit, remaining useful life of a unit can be calculated by subtracting the current cycle from the maximum cycle of that unit.\n",
"As the current objective is to predict the remaining useful life (RUL) of each unit (ID), the target variable needs to be identified. Since we're dealing with a timeseries data that represents the lifetime of a unit, remaining useful life of a unit can be calculated by subtracting the current cycle from the maximum cycle of that unit.\n",
"\n",
"\t\t\t\t\tRUL = Max. Cycle - Current Cycle \n",
"## RUL calculation and Feature selection"
@@ -1092,7 +810,6 @@
"## Running a notebook end-to-end using executor\n",
"<a name=\"section-9\"></a>\n",
"\n",
"**Note:** This section can only be considered when running this notebook on Managed instances from Vertex AI Workbench.\n",
"### Automating the notebook execution\n",
"All the steps followed until now can be run as a training job without using any additional code using the Vertex AI Workbench executor. The executor can help you run a notebook file from start to end, with your choice of the environment, machine type, input parameters, and other characteristics. After setting up an execution, the notebook is executed as a job in Vertex AI custom training. Your jobs can be monitored from the Executor pane in the left sidebar.\n",
"\n",
@@ -1100,13 +817,13 @@
"\n",
"The executor also lets you choose the environment and machine type while automating the runs similar to Vertex AI training jobs without switching to the training jobs UI. Apart from the custom container that replicates the existing kernel by default, pre-built environments like TensorFlow Enterprise, PyTorch, and others can also be selected to run the notebook. The required compute power can be specified by choosing from the list of machine types available, including GPUs.\n",
"\n",
"### Scheduled runs on executor\n",
"## Scheduled runs on executor\n",
"\n",
"Notebook runs can also be scheduled recurringly with the executor. To do so, select Schedule-based recurring executions as the run type instead of One-time execution. The frequency of the job and the time when it executes is provided when you create the execution.\n",
"\n",
"<img src=\"https://storage.googleapis.com/gweb-cloudblog-publish/images/7_Vertex_AI_Workbench.max-1100x1100.jpg\">\n",
"\n",
"### Parameterizing the variables\n",
"## Parameterizing the variables\n",
"\n",
"The executor lets you run a notebook with different sets of input parameters. If you’ve added parameter tags to any of your notebook cells, you can pass in your parameter values to the executor. More about how to use this feature can be found on this [blog](https://cloud.google.com/blog/products/ai-machine-learning/schedule-and-execute-notebooks-with-vertex-ai-workbench).\n",
"\n",
@@ -1138,37 +855,6 @@
"ARTIFACT_GCS_PATH = f\"gs://{BUCKET_NAME}/{BLOB_PATH}\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1aa75b3d4616"
},
"source": [
"Give a display name to the Vertex AI model resource."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "02ca350dba6c"
},
"outputs": [],
"source": [
"# Set the model-dsiplay-name\n",
"MODEL_DISPLAY_NAME = \"[your-model-display-name]\" # @param {type:\"string\"}\n",
"\n",
"# Otherwise, use the default name\n",
"if (\n",
" MODEL_DISPLAY_NAME == \"[your-model-display-name]\"\n",
" or MODEL_DISPLAY_NAME is None\n",
" or MODEL_DISPLAY_NAME == \"\"\n",
"):\n",
" MODEL_DISPLAY_NAME = \"pred_maint_model_\" + UUID\n",
"\n",
"print(MODEL_DISPLAY_NAME)"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -1205,28 +891,6 @@
"Next, create an endpoint resource for deploying the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e1e0cd571992"
},
"outputs": [],
"source": [
"# Set the endpoint-dsiplay-name\n",
"ENDPOINT_DISPLAY_NAME = \"[your-endpoint-display-name]\" # @param {type:\"string\"}\n",
"\n",
"# Otherwise, use the default name\n",
"if (\n",
" ENDPOINT_DISPLAY_NAME == \"[your-endpoint-display-name]\"\n",
" or ENDPOINT_DISPLAY_NAME is None\n",
" or ENDPOINT_DISPLAY_NAME == \"\"\n",
"):\n",
" ENDPOINT_DISPLAY_NAME = \"pred_maint_endpoint_\" + UUID\n",
"\n",
"print(ENDPOINT_DISPLAY_NAME)"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -1235,7 +899,6 @@
},
"outputs": [],
"source": [
"# Create the Endpoint resource\n",
"endpoint = aiplatform.Endpoint.create(display_name=ENDPOINT_DISPLAY_NAME)\n",
"\n",
"print(endpoint.display_name)\n",
@@ -1252,11 +915,18 @@
"<a name=\"section-12\"></a>\n",
"\n",
"\n",
"Configure the following parameters and deploy the model to the created endpoint.\n",
"\n",
"- `endpoint`: The `Endpoint` object created using Vertex AI SDK.\n",
"- `deployed_model_display_name`: A display-name for the deployment.\n",
"- `machine_type`: Type of the machine required for the deployment environment. See [here](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute) for references."
"Configure the deployment name, machine type, and other parameters for the deployment and deploy the model to the created endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ca41cac871d6"
},
"outputs": [],
"source": [
"MACHINE_TYPE = \"n1-standard-2\""
]
},
{
@@ -1270,8 +940,8 @@
"# deploy the model to the endpoint\n",
"model.deploy(\n",
" endpoint=endpoint,\n",
" deployed_model_display_name=MODEL_DISPLAY_NAME + \"_deployment\",\n",
" machine_type=\"n1-standard-2\",\n",
" deployed_model_display_name=DEPLOYED_MODEL_NAME,\n",
" machine_type=MACHINE_TYPE,\n",
")\n",
"\n",
"model.wait()\n",
@@ -1314,15 +984,7 @@
"## Clean up\n",
"<a name=\"section-14\"></a>\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:\n",
"* Vertex AI Model\n",
"* Vertex AI Endpoint\n",
"* Cloud Storage bucket\n",
"\n",
"Set `delete_bucket` to **True** to delete the Cloud Storage bucket."
"Undeploy the model from the endpoint."
]
},
{
@@ -1333,19 +995,68 @@
},
"outputs": [],
"source": [
"# Undeploy all the models from the endpoint\n",
"endpoint.undeploy_all()\n",
"\n",
"# Delete the endpoint resource\n",
"endpoint.delete()\n",
"\n",
"# Delete the model resource\n",
"model.delete()\n",
"\n",
"# Delete the Cloud Storage bucket\n",
"delete_bucket = False\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_URI"
"DEPLOYED_MODEL_ID = \"\"\n",
"endpoint.undeploy(deployed_model_id=DEPLOYED_MODEL_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "96e427b77791"
},
"source": [
"Delete the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ace028ac23ea"
},
"outputs": [],
"source": [
"endpoint.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4b77998d0512"
},
"source": [
"Delete the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e034150a4c94"
},
"outputs": [],
"source": [
"model.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "23cb2deb122d"
},
"source": [
"Remove the contents of the Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "98aaac27d85d"
},
"outputs": [],
"source": [
"! gsutil -m rm -r $BUCKET_URI"
]
}
],
@@ -0,0 +1,823 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "d1cc1c1fa076"
},
"source": [
"# Pricing Optimization \n",
"## Table of contents\n",
"* [Overview](#section-1)\n",
"* [Dataset](#section-2)\n",
"* [Objective](#section-3)\n",
"* [Costs](#section-4)\n",
"* [Create a BigQuery dataset](#section-5)\n",
"* [Load the dataset from Cloud Storage](#section-6)\n",
"* [Data analysis](#section-7)\n",
"* [Preprocess the data for training](#section-8)\n",
"* [Train the model using BigQuery ML](#section-9)\n",
"* [Generate forecasts from the model](#section-10)\n",
"* [Interpret the results to choose the best price](#section-11)\n",
"* [Clean up](#section-12)\n",
"\n",
"## Overview\n",
"<a name=\"section-1\"></a>\n",
"\n",
"This notebook demonstrates analysis of pricing optimization on [CDM Pricing Data](https://github.com/trifacta/trifacta-google-cloud/tree/main/design-pattern-pricing-optimization) and automating the workflow using Vertex AI Workbench managed notebooks.\n",
"\n",
"*Note: This notebook file was developed to run in a [Vertex AI Workbench managed notebooks](https://console.cloud.google.com/vertex-ai/workbench/list/managed) instance using the Python (Local) kernel. Some components of this notebook may not work in other notebook environments.*\n",
"\n",
"## Dataset\n",
"<a name=\"section-2\"></a>\n",
"\n",
"The dataset used in this notebook is a part of the [CDM Pricing dataset](https://github.com/trifacta/trifacta-google-cloud/blob/main/design-pattern-pricing-optimization/CDM_Pricing_large_table.csv), which consists of product sales information on specified dates.\n",
"\n",
"## Objective\n",
"<a name=\"section-3\"></a>\n",
"\n",
"The objective of this notebook is to build a pricing optimization model using Vertex AI. The following steps have been followed: \n",
"\n",
"- Load the required dataset from a Cloud Storage bucket.\n",
"- Analyze the fields present in the dataset.\n",
"- Process the data to build a model.\n",
"- Build a BigQuery ML forecast model on the processed data.\n",
"- Get forecasted values from the BigQuery ML model.\n",
"- Interpret the forecasts to identify the best prices.\n",
"- Clean up.\n",
"\n",
"## Costs\n",
"<a name=\"section-4\"></a>\n",
"\n",
"This tutorial uses the following billable components of Google Cloud:\n",
"\n",
"- Vertex AI\n",
"- BigQuery\n",
"- Cloud Storage\n",
"\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing), [BigQuery pricing](https://cloud.google.com/bigquery/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.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5ed1f5e85640"
},
"source": [
"## Before you begin\n",
"\n",
"### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c3f30148b66d"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"\"\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID: \", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "750bf2883c2d"
},
"source": [
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3c6db1ca88b9"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2a1c270c7d34"
},
"source": [
"### Import the required libraries and define constants\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "acc6fac1fa55"
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"import seaborn as sns\n",
"from google.cloud import bigquery\n",
"from google.cloud.bigquery import Client"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a06006dff8f9"
},
"outputs": [],
"source": [
"DATASET = \"[your-bigquery-dataset-id]\" # set the BigQuery dataset-id\n",
"TRAINING_DATA_TABLE = \"[your-bigquery-table-id-to-store-the-training-data]\" # set the BigQuery table-id to store the training data"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "016c3d47cc69"
},
"source": [
"## Create a BigQuery dataset\n",
"<a name=\"section-5\"></a>\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "12ccd8d7956e"
},
"source": [
"#@bigquery\n",
"-- create a dataset in BigQuery\n",
"\n",
"CREATE SCHEMA pricing_optimization\n",
"OPTIONS(\n",
" location=\"us\"\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c106b978a79b"
},
"source": [
"## Load the dataset from Cloud Storage\n",
"<a name=\"section-6\"></a>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8aeae9da9796"
},
"outputs": [],
"source": [
"DATA_LOCATION = \"gs://cloud-samples-data/ai-platform-unified/datasets/tabular/cdm_pricing_large_table.csv\"\n",
"df = pd.read_csv(DATA_LOCATION)\n",
"print(df.shape)\n",
"df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7b98d5f09842"
},
"source": [
"You will build a forecast model on this data and thus determine the best price for a product. For this type of model, you will not be using many fields: only the sales and price related ones. For the current execrcise, focus on the following fields:\n",
"\n",
"- `Product_ID`\n",
"- `Customer_Hierarchy`\n",
"- `Fiscal_Date`\n",
"- `List_Price_Converged`\n",
"- `Invoiced_quantity_in_Pieces`\n",
"- `Net_Sales`\n",
"\n",
"## Data Analysis\n",
"<a name=\"section-7\"></a>\n",
"\n",
"First, explore the data and distributions.\n",
"\n",
"Select the required columns from the dataframe."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "af4b41c5eb1f"
},
"outputs": [],
"source": [
"id_col = \"Product_ID\"\n",
"date_col = \"Fiscal_Date\"\n",
"categ_cols = [\"Customer_Hierarchy\"]\n",
"num_cols = [\"List_Price_Converged\", \"Invoiced_quantity_in_Pieces\", \"Net_Sales\"]\n",
"\n",
"df = df[[id_col, date_col] + categ_cols + num_cols].copy()\n",
"df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3d780043ee5b"
},
"source": [
"Check the column types and null values in the dataframe."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f54c445a1288"
},
"outputs": [],
"source": [
"df.info()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cd817b414c4d"
},
"source": [
"This data description reveals that there are no null values in the data. Also, the field `Fiscal_Date` which is a date field is loaded as an object type. \n",
"\n",
"Change the type of the date field to datetime."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b160fac085c8"
},
"outputs": [],
"source": [
"df[\"Fiscal_Date\"] = pd.to_datetime(df[\"Fiscal_Date\"], infer_datetime_format=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fb4778578064"
},
"source": [
"Plot the distributions for the categorical fields."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dd0467cd57c3"
},
"outputs": [],
"source": [
"for i in categ_cols:\n",
" df[i].value_counts(normalize=True).plot(kind=\"bar\")\n",
" plt.title(i)\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "145deed255e0"
},
"source": [
"Plot the distributions for the numerical fields."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f934137c6d82"
},
"outputs": [],
"source": [
"for i in num_cols:\n",
" _, ax = plt.subplots(1, 2, figsize=(10, 4))\n",
" df[i].plot(kind=\"box\", ax=ax[0])\n",
" df[i].plot(kind=\"hist\", ax=ax[1])\n",
" ax[0].set_title(i + \"-Boxplot\")\n",
" ax[1].set_title(i + \"-Histogram\")\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f9b9c2e58380"
},
"source": [
"Check the maximum date and minimum date in Fiscal_Date column."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2a10aa689f9d"
},
"outputs": [],
"source": [
"print(df[\"Fiscal_Date\"].max())\n",
"print(df[\"Fiscal_Date\"].min())"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4834f63e2e59"
},
"source": [
"Check the product distribution across each category."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4664877f5304"
},
"outputs": [],
"source": [
"grp_cols = [\"Customer_Hierarchy\", \"Product_ID\"]\n",
"grp_df = df[grp_cols].groupby(by=grp_cols).count().reset_index()\n",
"grp_df.groupby(\"Customer_Hierarchy\").nunique()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "01ed02b9c8fd"
},
"source": [
"Check the percentage changes in the orders based on the percentage changes in the price."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0b2c428cb135"
},
"outputs": [],
"source": [
"# aggregate the data\n",
"df_aggr = (\n",
" df.groupby([\"Product_ID\", \"List_Price_Converged\"])\n",
" .agg({\"Fiscal_Date\": min, \"Invoiced_quantity_in_Pieces\": sum, \"Net_Sales\": sum})\n",
" .reset_index()\n",
")\n",
"# rename the aggregated columns\n",
"df_aggr.rename(\n",
" columns={\n",
" \"Fiscal_Date\": \"First_price_date\",\n",
" \"Invoiced_quantity_in_Pieces\": \"Total_ordered_pieces\",\n",
" \"Net_Sales\": \"Total_net_sales\",\n",
" },\n",
" inplace=True,\n",
")\n",
"\n",
"# sort values chronologically\n",
"df_aggr.sort_values(by=[\"Product_ID\", \"First_price_date\"], inplace=True)\n",
"df_aggr.reset_index(drop=True, inplace=True)\n",
"\n",
"# add columns for previous values\n",
"df_aggr[\"Previous_List\"] = df_aggr.groupby([\"Product_ID\"])[\n",
" \"List_Price_Converged\"\n",
"].shift()\n",
"df_aggr[\"Previous_Total_ordered_pieces\"] = df_aggr.groupby([\"Product_ID\"])[\n",
" \"Total_ordered_pieces\"\n",
"].shift()\n",
"\n",
"# average price change across sku's\n",
"df_aggr[\"price_change_perc\"] = (\n",
" (df_aggr[\"List_Price_Converged\"] - df_aggr[\"Previous_List\"])\n",
" / df_aggr[\"Previous_List\"].fillna(0)\n",
" * 100\n",
")\n",
"df_aggr[\"order_change_perc\"] = (\n",
" (df_aggr[\"Total_ordered_pieces\"] - df_aggr[\"Previous_Total_ordered_pieces\"])\n",
" / df_aggr[\"Previous_Total_ordered_pieces\"].fillna(0)\n",
" * 100\n",
")\n",
"\n",
"# plot a scatterplot to visualize the changes\n",
"sns.scatterplot(\n",
" x=\"price_change_perc\",\n",
" y=\"order_change_perc\",\n",
" data=df_aggr,\n",
" hue=\"Product_ID\",\n",
" legend=False,\n",
")\n",
"plt.title(\"Percentage of change in price vs order\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8259e916fe25"
},
"source": [
"For most of the products, the percentage change in orders are high where the percentage changes in the prices are low. This suggests that too much change in the prices can affect the number of orders. \n",
"\n",
"**Note**: There seem to be some outliers in the data as percentage changes greater than 800 are found. In the current exercise, do not take any manual measures to deal with outliers as you will create a BigQuery ML timeseries model that already deals with outliers.\n",
"\n",
"## Preprocess the data for training\n",
"<a name=\"section-8\"></a>\n",
"\n",
"Check which `Product_ID`'s have the maximum orders."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f5cbc7709c6a"
},
"outputs": [],
"source": [
"df_orders = df.groupby([\"Product_ID\", \"Customer_Hierarchy\"], as_index=False)[\n",
" \"Invoiced_quantity_in_Pieces\"\n",
"].sum()\n",
"df_orders.loc[\n",
" df_orders.groupby(\"Customer_Hierarchy\")[\"Invoiced_quantity_in_Pieces\"].idxmax()\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fd6d227e513e"
},
"source": [
"From the above result, you can infer the following:\n",
"\n",
"- Under the **Food** category, **SKU 62** has the maximum orders.\n",
"- Under the **Manufacturing** category, **SKU 17** has the maximum orders.\n",
"- Under the **Paper** category, **SKU 107** has the maximum orders.\n",
"- Under the **Publishing** category, **SKU 8** has the maximum orders.\n",
"- Under the **Utilities** category, **SKU 140** has the maximum orders.\n",
"\n",
"Given that there are too many ids and only a few records for most of them, consider only the above `Product_ID`s for which there are a maximum number of orders. \n",
"\n",
"**Note**: The `Invoiced_quantity_in_Pieces` field seems to be a *float* type rather than an *int* type as it should be. This could be because the data itself might be averaged in the first place."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2dbc0d64d157"
},
"source": [
"Check the various prices available for these `Product_ID`s."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "acc1dbd2d838"
},
"outputs": [],
"source": [
"df_type_food = df[(df[\"Product_ID\"] == \"SKU 62\") & (df[\"Customer_Hierarchy\"] == \"Food\")]\n",
"print(\"Food :\")\n",
"print(df_type_food[\"List_Price_Converged\"].value_counts())\n",
"df_type_manuf = df[\n",
" (df[\"Product_ID\"] == \"SKU 17\") & (df[\"Customer_Hierarchy\"] == \"Manufacturing\")\n",
"]\n",
"print(\"Manufacturing :\")\n",
"print(df_type_manuf[\"List_Price_Converged\"].value_counts())\n",
"df_type_paper = df[\n",
" (df[\"Product_ID\"] == \"SKU 107\") & (df[\"Customer_Hierarchy\"] == \"Paper\")\n",
"]\n",
"print(\"Paper :\")\n",
"print(df_type_paper[\"List_Price_Converged\"].value_counts())\n",
"df_type_pub = df[\n",
" (df[\"Product_ID\"] == \"SKU 8\") & (df[\"Customer_Hierarchy\"] == \"Publishing\")\n",
"]\n",
"print(\"Publishing :\")\n",
"print(df_type_pub[\"List_Price_Converged\"].value_counts())\n",
"df_type_util = df[\n",
" (df[\"Product_ID\"] == \"SKU 140\") & (df[\"Customer_Hierarchy\"] == \"Utilities\")\n",
"]\n",
"print(\"Utilities :\")\n",
"print(df_type_util[\"List_Price_Converged\"].value_counts())"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f023af578c0f"
},
"source": [
"In the publishing category, `Product_ID` `SKU 8` and `SKU 17` are less than or equal to two different prices in the entire data and so you will exclude them and consider the rest for building the forecast model. The idea here is to train a forecast model on the timeseries data for products with different prices.\n",
"\n",
"Join the data for all the `Product_ID`s into one dataframe and remove duplicate records."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a44771cc4c20"
},
"outputs": [],
"source": [
"df_final = pd.concat([df_type_food, df_type_paper, df_type_util])\n",
"df_final = (\n",
" df_final[\n",
" [\n",
" \"Product_ID\",\n",
" \"Fiscal_Date\",\n",
" \"Customer_Hierarchy\",\n",
" \"List_Price_Converged\",\n",
" \"Invoiced_quantity_in_Pieces\",\n",
" ]\n",
" ]\n",
" .drop_duplicates()\n",
" .reset_index(drop=True)\n",
")\n",
"df_final.head()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "add5063df368"
},
"source": [
"Save the data to a BigQuery table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fd82ba56571f"
},
"outputs": [],
"source": [
"bq_client = bigquery.Client(project=PROJECT_ID)\n",
"\n",
"job_config = bigquery.LoadJobConfig(\n",
" # Specify a (partial) schema. All columns are always written to the\n",
" # table. The schema is used to assist in data type definitions.\n",
" schema=[\n",
" bigquery.SchemaField(\"Product_ID\", bigquery.enums.SqlTypeNames.STRING),\n",
" bigquery.SchemaField(\"Fiscal_Date\", bigquery.enums.SqlTypeNames.DATE),\n",
" bigquery.SchemaField(\"List_Price_Converged\", bigquery.enums.SqlTypeNames.FLOAT),\n",
" bigquery.SchemaField(\n",
" \"Invoiced_quantity_in_Pieces\", bigquery.enums.SqlTypeNames.FLOAT\n",
" ),\n",
" ],\n",
" # Optionally, set the write disposition. BigQuery appends loaded rows\n",
" # to an existing table by default, but with WRITE_TRUNCATE write\n",
" # disposition it replaces the table with the loaded data.\n",
" write_disposition=\"WRITE_TRUNCATE\",\n",
")\n",
"\n",
"# save the dataframe to a table in the created dataset\n",
"job = bq_client.load_table_from_dataframe(\n",
" df_final,\n",
" \"{}.{}.{}\".format(PROJECT_ID, DATASET, TRAINING_DATA_TABLE),\n",
" job_config=job_config,\n",
") # Make an API request.\n",
"job.result() # Wait for the job to complete."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fca77641b03b"
},
"source": [
"# Train the model using BigQuery ML\n",
"<a name=\"section-9\"></a>\n",
"\n",
"Train an [Arima-Plus](https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-create-time-series) model on the data using BigQuery ML."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cded27507891"
},
"source": [
"#@bigquery\n",
"create or replace model pricing_optimization.bqml_arima\n",
"options\n",
" (model_type = 'ARIMA_PLUS',\n",
" time_series_timestamp_col = 'Fiscal_Date',\n",
" time_series_data_col = 'Invoiced_quantity_in_Pieces',\n",
" time_series_id_col = 'ID'\n",
" ) as\n",
"select\n",
" Fiscal_Date,\n",
" Concat(Product_ID,\"_\" ,Cast(List_Price_Converged as string)) as ID,\n",
" Invoiced_quantity_in_Pieces\n",
"from\n",
" pricing_optimization.TRAINING_DATA\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "332fd11ff32b"
},
"source": [
"## Generate forecasts from the model\n",
"<a name=\"section-10\"></a>\n",
"\n",
"Predict the sales for the next 30 days for each id and save to a dataframe."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ef926cdbf28e"
},
"outputs": [],
"source": [
"client = Client()\n",
"\n",
"query = '''\n",
"DECLARE HORIZON STRING DEFAULT \"30\"; #number of values to forecast\n",
"DECLARE CONFIDENCE_LEVEL STRING DEFAULT \"0.90\"; ## required confidence level\n",
"\n",
"EXECUTE IMMEDIATE format(\"\"\"\n",
" SELECT\n",
" *\n",
" FROM \n",
" ML.FORECAST(MODEL pricing_optimization.bqml_arima, \n",
" STRUCT(%s AS horizon, \n",
" %s AS confidence_level)\n",
" )\n",
" \"\"\",HORIZON,CONFIDENCE_LEVEL)'''\n",
"job = client.query(query)\n",
"dfforecast = job.to_dataframe()\n",
"dfforecast.head()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "608c7de72dae"
},
"source": [
"## Interpret the results to choose the best price\n",
"<a name=\"section-11\"></a>\n",
"\n",
"Calculate average forecast values for the forecast duration."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e1e193680400"
},
"outputs": [],
"source": [
"dfforecast_avg = (\n",
" dfforecast[[\"ID\", \"forecast_value\"]].groupby(\"ID\", as_index=False).mean()\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5ce395d652a3"
},
"source": [
"Extract the ID and Price fields from the ID field."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "452c56fa58ed"
},
"outputs": [],
"source": [
"dfforecast_avg[\"Product_ID\"] = dfforecast_avg[\"ID\"].apply(lambda x: x.split(\"_\")[0])\n",
"dfforecast_avg[\"Price\"] = dfforecast_avg[\"ID\"].apply(lambda x: x.split(\"_\")[1])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3cee67f4028f"
},
"source": [
"Plot the average forecasted sales vs. the price of the product."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fb351c8f383d"
},
"outputs": [],
"source": [
"for i in dfforecast_avg[\"Product_ID\"].unique():\n",
" dfforecast_avg[dfforecast_avg[\"Product_ID\"] == i].set_index(\"Price\").sort_values(\n",
" \"forecast_value\"\n",
" ).plot(kind=\"bar\")\n",
" plt.title(\"Price vs. Average Sales for \" + i)\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "67ff3acc74a5"
},
"source": [
"Based on the plots for price vs. the average forecasted orders, it can be said that to use the maximum orders, each of the considered `Product_ID`s can follow the below prices:\n",
"\n",
"- SKU 107's price range can be from 4.44 - 4.73 units\n",
"- SKU 140's price can be 1.95 units\n",
"- SKU 62's price can be 4.23 units\n",
"\n",
"\n",
"## Clean Up\n",
"<a name=\"section-12\"></a>\n",
"\n",
"To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud 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. The following code deletes the entire dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d78908b8134d"
},
"outputs": [],
"source": [
"# Construct a BigQuery client object.\n",
"client = bigquery.Client()\n",
"\n",
"# TODO(developer): Set model_id to the ID of the model to fetch.\n",
"dataset_id = \"{PROJECT}.{DATASET}\".format(PROJECT=PROJECT_ID, DATASET=DATASET)\n",
"\n",
"# Use the delete_contents parameter to delete a dataset and its contents.\n",
"# Use the not_found_ok parameter to not receive an error if the dataset has already been deleted.\n",
"client.delete_dataset(\n",
" dataset_id, delete_contents=True, not_found_ok=True\n",
") # Make an API request.\n",
"\n",
"print(\"Deleted dataset '{}'.\".format(dataset_id))"
]
}
],
"metadata": {
"colab": {
"name": "pricing-optimization.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -29,49 +29,42 @@
"id": "JAPoU8Sm5E6e"
},
"source": [
"# Create Vertex AI Matching Engine index\n",
"\n",
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/matching_engine/sdk_matching_engine_for_indexing.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\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/community/matching_engine/sdk_matching_engine_for_indexing.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Run in Vertex Workbench\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/matching_engine/sdk_matching_engine_for_indexing.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/matching_engine/sdk_matching_engine_for_indexing.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\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/matching_engine/sdk_matching_engine_for_indexing.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b0a74aaf1481"
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This example demonstrates how to use the GCP ANN Service. It is a high scale, low latency solution, to find similar vectors (or more specifically \"embeddings\") for a large corpus. Moreover, it is a fully managed offering, further reducing operational overhead. It is built upon [Approximate Nearest Neighbor (ANN) technology](https://ai.googleblog.com/2020/07/announcing-scann-efficient-vector.html) developed by Google Research."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "34a4b245e795"
},
"source": [
"This example demonstrates how to use the GCP ANN Service. It is a high scale, low latency solution, to find similar vectors (or more specifically \"embeddings\") for a large corpus. Moreover, it is a fully managed offering, further reducing operational overhead. It is built upon [Approximate Nearest Neighbor (ANN) technology](https://ai.googleblog.com/2020/07/announcing-scann-efficient-vector.html) developed by Google Research.\n",
"\n",
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [GloVe dataset](https://nlp.stanford.edu/projects/glove/).\n",
"\n",
"\"GloVe is an unsupervised learning algorithm for obtaining vector representations for words. Training is performed on aggregated global word-word co-occurrence statistics from a corpus, and the resulting representations showcase interesting linear substructures of the word vector space.\"\n",
"\n",
"### Objective\n",
"\n",
"In this notebook, you learn how to create Approximate Nearest Neighbor (ANN) Index, query against indexes, and validate the performance of the index. \n",
"In this notebook, you will learn how to create Approximate Nearest Neighbor (ANN) Index, query against indexes, and validate the performance of the index. \n",
"\n",
"The steps performed include:\n",
"\n",
@@ -79,28 +72,9 @@
"* Create an IndexEndpoint with VPC Network\n",
"* Deploy ANN Index and Brute Force Index\n",
"* Perform online query\n",
"* Compute recall\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"### Dataset\n",
"* Compute recall\n",
"\n",
"The dataset used for this tutorial is the [GloVe dataset](https://nlp.stanford.edu/projects/glove/).\n",
"\n",
"\"GloVe is an unsupervised learning algorithm for obtaining vector representations for words. Training is performed on aggregated global word-word co-occurrence statistics from a corpus, and the resulting representations showcase interesting linear substructures of the word vector space.\"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5e2eba58ad71"
},
"source": [
"### Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
@@ -118,159 +92,11 @@
{
"cell_type": "markdown",
"metadata": {
"id": "d1e95a984673"
"id": "S5zc4kbEiYCm"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager).\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API, and Service Networking API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,servicenetworking.googleapis.com).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2b9daa35336a"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using a Vertex AI Workbench notebook**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c6bed8c6a6b3"
},
"source": [
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3e2b43c2d2bf"
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"# The Vertex AI Workbench notebook product has specific requirements\n",
"IS_VERTEX_AI_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# If on a Vertex AI Workbench notebook, then don't execute this code\n",
"if not IS_VERTEX_AI_WORKBENCH_NOTEBOOK:\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, log in using gcloud\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "beb72f394541"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID: \", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f4c6d0a9e66c"
},
"source": [
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1dc3fa9ac4f7"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"<your_project_id>\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4962667eec8e"
},
"source": [
"* **Prepare a VPC network**. To reduce any network overhead that might lead to unnecessary increase in overhead latency, it is best to call the ANN endpoints from your VPC via a direct [VPC Peering](https://cloud.google.com/vertex-ai/docs/general/vpc-peering) connection. \n",
" * The following section describes how to setup a VPC Peering connection if you don't have one. \n",
" * This is a one-time initial setup task. You can also reuse existing VPC network and skip this section."
@@ -284,7 +110,9 @@
},
"outputs": [],
"source": [
"VPC_NETWORK = \"[your-vpc-network-name]\" # @param {type:\"string\"}\n",
"PROJECT_ID = \"python-docs-samples-tests\" # @param {type:\"string\"}\n",
"\n",
"NETWORK_NAME = \"ann-vpc-network\" # @param {type:\"string\"}\n",
"\n",
"PEERING_RANGE_NAME = \"ann-haystack-range\""
]
@@ -297,28 +125,24 @@
},
"outputs": [],
"source": [
"import os\n",
"# Create a VPC network\n",
"! gcloud compute networks create {NETWORK_NAME} --bgp-routing-mode=regional --subnet-mode=auto --project={PROJECT_ID}\n",
"\n",
"# Remove the if condition to run the encapsulated code\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Create a VPC network\n",
" ! gcloud compute networks create {VPC_NETWORK} --bgp-routing-mode=regional --subnet-mode=auto --project={PROJECT_ID}\n",
"# Add necessary firewall rules\n",
"! gcloud compute firewall-rules create {NETWORK_NAME}-allow-icmp --network {NETWORK_NAME} --priority 65534 --project {PROJECT_ID} --allow icmp\n",
"\n",
" # Add necessary firewall rules\n",
" ! gcloud compute firewall-rules create {VPC_NETWORK}-allow-icmp --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow icmp\n",
"! gcloud compute firewall-rules create {NETWORK_NAME}-allow-internal --network {NETWORK_NAME} --priority 65534 --project {PROJECT_ID} --allow all --source-ranges 10.128.0.0/9\n",
"\n",
" ! gcloud compute firewall-rules create {VPC_NETWORK}-allow-internal --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow all --source-ranges 10.128.0.0/9\n",
"! gcloud compute firewall-rules create {NETWORK_NAME}-allow-rdp --network {NETWORK_NAME} --priority 65534 --project {PROJECT_ID} --allow tcp:3389\n",
"\n",
" ! gcloud compute firewall-rules create {VPC_NETWORK}-allow-rdp --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow tcp:3389\n",
"! gcloud compute firewall-rules create {NETWORK_NAME}-allow-ssh --network {NETWORK_NAME} --priority 65534 --project {PROJECT_ID} --allow tcp:22\n",
"\n",
" ! gcloud compute firewall-rules create {VPC_NETWORK}-allow-ssh --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow tcp:22\n",
"# Reserve IP range\n",
"! gcloud compute addresses create {PEERING_RANGE_NAME} --global --prefix-length=16 --network={NETWORK_NAME} --purpose=VPC_PEERING --project={PROJECT_ID} --description=\"peering range\"\n",
"\n",
" # Reserve IP range\n",
" ! gcloud compute addresses create {PEERING_RANGE_NAME} --global --prefix-length=16 --network={VPC_NETWORK} --purpose=VPC_PEERING --project={PROJECT_ID} --description=\"peering range\"\n",
"\n",
" # Set up peering with service networking\n",
" # Your account must have the \"Compute Network Admin\" role to run the following.\n",
" ! gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com --network={VPC_NETWORK} --ranges={PEERING_RANGE_NAME} --project={PROJECT_ID}"
"# Set up peering with service networking\n",
"# Your account must have the \"Compute Network Admin\" role to run the following.\n",
"! gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com --network={NETWORK_NAME} --ranges={PEERING_RANGE_NAME} --project={PROJECT_ID}"
]
},
{
@@ -406,6 +230,9 @@
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
@@ -414,15 +241,88 @@
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BF1j6f9HApxa"
},
"source": [
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager).\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI API and Compute Engine API, and Service Networking API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,servicenetworking.googleapis.com).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oM1iC_MfAts1"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"python-docs-samples-tests\"\n",
"\n",
"# Get your Google Cloud project ID from gcloud\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID: \", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qJYoRfYng0XZ"
},
"source": [
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "riG_qUokg0XZ"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"<your_project_id>\" # @param {type:\"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "q7tcBkCDI1_M"
},
"source": [
"### Random ID\n",
"#### Timestamp\n",
"\n",
"To avoid name collisions between users on resources created, create a random ID for each instance session, and append the id onto the name of resources you create in this tutorial."
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial."
]
},
{
@@ -433,10 +333,84 @@
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"from datetime import datetime\n",
"\n",
"RANDOM_ID = \"\".join(random.choices(string.ascii_lowercase + string.digits, k=8))"
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t6Ggbb4DI6by"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using a Vertex AI Workbench notebook**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RpIzUmpOI9G7"
},
"source": [
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"1. In the Cloud Console, go to the [**Create service account key**\n",
" page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
"\n",
"2. Click **Create service account**.\n",
"\n",
"3. In the **Service account name** field, enter a name, and\n",
" click **Create**.\n",
"\n",
"4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
"into the filter box, and select\n",
" **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"5. Click *Create*. A JSON file that contains your key downloads to your\n",
"local environment.\n",
"\n",
"6. Enter the path to your service account key as the\n",
"`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AW9vQHeoI-q_"
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"# The Vertex AI Workbench notebook product has specific requirements\n",
"IS_VERTEX_AI_WORKBENCH_NOTEBOOK = os.path.exists(\n",
" \"/opt/deeplearning/metadata/env_version\"\n",
")\n",
"\n",
"# If on a Vertex AI Workbench notebook, then don't execute this code\n",
"if not IS_VERTEX_AI_WORKBENCH_NOTEBOOK:\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, log in using gcloud\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" ! gcloud auth login"
]
},
{
@@ -479,7 +453,7 @@
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_URI = \"gs://\" + PROJECT_ID + \"aip-\" + RANDOM_ID\n",
" BUCKET_URI = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
@@ -554,15 +528,6 @@
"import h5py"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "76f7b9ffde0b"
},
"source": [
"Use gcloud to retrieve the project number."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -783,10 +748,12 @@
]
},
{
"cell_type": "markdown",
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0f1a9fbecabb"
},
"outputs": [],
"source": [
"Using the resource name, you can retrieve an existing MatchingEngineIndex."
]
@@ -799,7 +766,7 @@
},
"outputs": [],
"source": [
"tree_ah_index = aiplatform.MatchingEngineIndex(index_name=INDEX_RESOURCE_NAME)"
"tree_ah_index = aiplatform.MatchingEngineIndex(INDEX_RESOURCE_NAME)"
]
},
{
@@ -854,7 +821,7 @@
"outputs": [],
"source": [
"brute_force_index = aiplatform.MatchingEngineIndex(\n",
" index_name=INDEX_BRUTE_FORCE_RESOURCE_NAME\n",
" \"projects/1012616486416/locations/us-central1/indexes/6738176690918260736\"\n",
")"
]
},
@@ -965,9 +932,8 @@
},
"outputs": [],
"source": [
"VPC_NETWORK = \"[your-network-name]\"\n",
"VPC_NETWORK_FULL = \"projects/{}/global/networks/{}\".format(PROJECT_NUMBER, VPC_NETWORK)\n",
"VPC_NETWORK_FULL"
"VPC_NETWORK_NAME = \"projects/{}/global/networks/{}\".format(PROJECT_NUMBER, NETWORK_NAME)\n",
"VPC_NETWORK_NAME"
]
},
{
@@ -981,7 +947,7 @@
"my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint.create(\n",
" display_name=\"index_endpoint_for_demo\",\n",
" description=\"index endpoint description\",\n",
" network=VPC_NETWORK_FULL,\n",
" network=VPC_NETWORK_NAME,\n",
")"
]
},
@@ -1023,7 +989,7 @@
},
"outputs": [],
"source": [
"DEPLOYED_INDEX_ID = f\"tree_ah_glove_deployed_{RANDOM_ID}\""
"DEPLOYED_INDEX_ID = f\"tree_ah_glove_deployed_{TIMESTAMP}\""
]
},
{
@@ -1058,7 +1024,7 @@
},
"outputs": [],
"source": [
"DEPLOYED_BRUTE_FORCE_INDEX_ID = f\"glove_brute_force_deployed_{RANDOM_ID}\""
"DEPLOYED_BRUTE_FORCE_INDEX_ID = f\"glove_brute_force_deployed_{TIMESTAMP}\""
]
},
{
@@ -1205,8 +1171,8 @@
"outputs": [],
"source": [
"# Delete indexes\n",
"tree_ah_index.delete()\n",
"brute_force_index.delete()"
"tree_ah_index.delete(force=True)\n",
"brute_force_index.delete(force=True)"
]
}
],
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -14,5 +14,5 @@ The purpose of this set of notebooks and markdown files is to demonstrate Google
4. [Evaluation](stage4)
5. [Deployment](stage5)
6. [Serving](stage6)
7. Monitoring(stage7)
7. Monitoring
8. Continuous Training
-43
View File
@@ -1,43 +0,0 @@
## Before you begin
### Set up your Google Cloud project
**The following steps are required, regardless of your notebook environment.**
1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.
1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).
1. [Enable the Vertex AI, BigQuery, Compute Engine and Cloud Storage APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,bigquery,compute_component,storage_component).
1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).
1. Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.
### Set up your local development environment
**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets all the requirements to run this notebook. You can skip this step.
**Otherwise**, make sure your environment meets this notebook's requirements. You need the following:
- The Cloud Storage SDK
- Python 3
- virtualenv
- Jupyter notebook running in a virtual environment with Python 3
The Cloud Storage guide to [Setting up a Python development environment](https://cloud.google.com/python/setup) and the [Jupyter installation guide](https://jupyter.org/install) provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:
1. [Install and initialize the SDK](https://cloud.google.com/sdk/docs/).
2. [Install Python 3](https://cloud.google.com/python/setup#installing_python).
3. [Install virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv) and create a virtual environment that uses Python 3. Activate the virtual environment.
4. To install Jupyter, run `pip3 install jupyter` on the command-line in a terminal shell.
5. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.
6. Open this notebook in the Jupyter Notebook Dashboard.
-112
View File
@@ -1,112 +0,0 @@
import os
import sys
import argparse
import subprocess
import random
import string
parser = argparse.ArgumentParser()
parser.add_argument('--bucket', dest='bucket_required', action='store_true',
default=False, help='Bucket required')
parser.add_argument('--email', dest='email_required', action='store_true',
default=False, help='Email required')
parser.add_argument('--sa', dest='sa_required', action='store_true',
default=False, help='Service account required')
parser.add_argument('--packages', dest='extra_packages',
default='', type=str, help='additional required packages')
args = parser.parse_args()
extra_pkgs = args.extra_packages
# Installation
# The Vertex AI Workbench Notebook product has specific requirements
IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME")
IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(
"/opt/deeplearning/metadata/env_version"
)
IS_COLAB = "google.colab" in sys.modules
# Vertex AI Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_WORKBENCH_NOTEBOOK:
USER_FLAG = "--user"
# not used
'''
print("Installing packages")
os.system(f"pip3 install --upgrade --quiet {USER_FLAG} google-cloud-aiplatform {args.extra_packages}")
print("Done installation")
'''
# Authenticate
if IS_COLAB:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# project ID
if IS_WORKBENCH_NOTEBOOK:
shell_output = subprocess.check_output("gcloud config list --format 'value(core.project)' 2>/dev/null", shell=True)
PROJECT_ID = shell_output[0:-1].decode('utf-8')
print("PROJECT ID: ", PROJECT_ID)
else:
PROJECT_ID = input("Enter PROJECT_ID: ")
os.system(f"gcloud config set project {PROJECT_ID}")
# email
if args.email_required:
shell_output = subprocess.check_output("gcloud config list --format 'value(core.account)' 2>/dev/null", shell=True)
EMAIL_ADDR = shell_output[0:-1].decode('utf-8')
if EMAIL_ADDR == '':
EMAIL_ADDR = input("Enter Email Address: ")
print("EMAIL_ADDR: ", EMAIL_ADDR)
# region
shell_output = subprocess.check_output("gcloud config list --format 'value(ai.region)'", shell=True)
REGION = shell_output[0:-1].decode('utf-8')
if REGION == '':
REGION = input("Enter REGION: ")
print("REGION: ", REGION)
# multi-region
MULTI_REGION = REGION.split('-')[0]
# UUID
# Generate a uuid of a specifed length(default=8)
def generate_uuid(length: int = 8) -> str:
return "".join(random.choices(string.ascii_lowercase + string.digits, k=length))
UUID = generate_uuid()
print("UUID", UUID)
# Bucket
if args.bucket_required:
BUCKET_NAME = PROJECT_ID + "aip-" + UUID
BUCKET_URI = f"gs://{BUCKET_NAME}"
os.system(f"gsutil mb -l {REGION} {BUCKET_URI}")
print("BUCKET_URI", BUCKET_URI)
# Project Number
if args.sa_required:
if IS_WORKBENCH_NOTEBOOK:
shell_output = subprocess.check_output("gcloud auth list 2>/dev/null", shell=True)
SERVICE_ACCOUNT = shell_output[:-1].decode('utf-8').split('\n')[2].strip()
PROJECT_NUMBER = SERVICE_ACCOUNT.split('-')[0]
else:
shell_output = subprocess.check_output(f"gcloud projects describe {PROJECT_ID}", shell=True)
try:
PROJECT_NUMBER = shell_output[:-1].decode('utf-8').split('\n')[7].split(':')[-1].strip().replace("'", "")
SERVICE_ACCOUNT = f"{PROJECT_NUMBER}-compute@developer.gserviceaccount.com"
except:
PROJECT_NUMBER = input("Enter project number: ")
SERVICE_ACCOUNT = f"{PROJECT_NUMBER}-compute@developer.gserviceaccount.com"
print("SERVICE_ACCOUNT", SERVICE_ACCOUNT)
print("PROJECT_NUMBER", PROJECT_NUMBER)
+36 -38
View File
@@ -28,25 +28,25 @@ The first stage in MLOps is the collection and preparation for the purpose of de
### Get Started
[Get started with Dataflow](community/ml_ops/stage1/get_started_dataflow.ipynb)
In this tutorial, you learn how to use `Dataflow` for training with `Vertex AI`.
[Get Started with BQ datasets](get_started_bq_datasets.ipynb)
```
The steps performed include:
- Offline preprocessing of data:
- Serially - w/o dataflow
- Parallel - with dataflow
- Upstream preprocessing of data:
- tabular data
- image data
- Create a Vertex AI `Dataset` resource from `BigQuery` table -- compatible for `AutoML` training.
- Extract a copy of the dataset from `BigQuery` to a CSV file in Cloud Storage -- compatible for `AutoML` or custom training.
- Select rows from a `BigQuery` dataset into a `pandas` dataframe -- compatible for custom training.
- Select rows from a `BigQuery` dataset into a `tf.data.Dataset` -- compatible for custom training `TensorFlow` models.
- Select rows from extracted CSV files into a `tf.data.Dataset` -- compatible for custom training `TensorFlow` models.
- Create a `BigQuery` dataset from CSV files.
- Extract data from `BigQuery` table into a `DMatrix` -- compatible for custom training `XGBoost` models.
```
[Get started with Vertex AI datasets](community/ml_ops/stage1/get_started_vertex_datasets.ipynb)
In this tutorial, you learn how to use `Vertex AI Dataset` for training with `Vertex AI`.
[Get Started with Vertex datasets](get_started_vertex_datasets.ipynb)
```
The steps performed include:
- Create a Vertex AI `Dataset` resource for:
- image data
- text data
@@ -61,25 +61,24 @@ The steps performed include:
- Detect anomalies in new data using TensorFlow Data Validation.
- Generate a TFRecord feature specification using TensorFlow Transform from the data schema.
- Export a dataset and convert to TFRecords.
```
[Get started with BigQuery datasets](community/ml_ops/stage1/get_started_bq_datasets.ipynb)
In this tutorial, you learn how to use `BigQuery` as a dataset for training with `Vertex AI`.
[Get Started with Dataflow](get_started_dataflow.ipynb)
```
The steps performed include:
- Create a Vertex AI `Dataset` resource from `BigQuery` table -- compatible for `AutoML` training.
- Extract a copy of the dataset from `BigQuery` to a CSV file in Cloud Storage -- compatible for `AutoML` or custom training.
- Select rows from a `BigQuery` dataset into a `pandas` dataframe -- compatible for custom training.
- Select rows from a `BigQuery` dataset into a `tf.data.Dataset` -- compatible for custom training `TensorFlow` models.
- Select rows from extracted CSV files into a `tf.data.Dataset` -- compatible for custom training `TensorFlow` models.
- Create a `BigQuery` dataset from CSV files.
- Extract data from `BigQuery` table into a `DMatrix` -- compatible for custom training `XGBoost` models.
- Offline preprocessing of data:
- Serially - w/o dataflow
- Parallel - with dataflow
- Upstream preprocessing of data:
- tabular data
- image data
```
[Get started with Vertex AI Data Labeling](community/ml_ops/stage1/get_started_with_data_labeling.ipynb)
In this tutorial, you learn how to use the `Vertex AI Data Labeling` service.
[Get Started with Data Labeling](get_started_with_data_labeling.ipynb)
```
The steps performed include:
- Create a Specialist Pool for data labelers.
@@ -87,28 +86,26 @@ The steps performed include:
- Submit the data labeling job.
- List data labeling jobs.
- Cancel a data labeling job.
```
[Get Started with Vision API and Vertex AI Datasets](get_started_with_visionapi_and_vertex_datasets.ipynb)
[Create an unlabelled Vertex AI AutoML text entity extraction dataset from PDFs using Vision API](community/ml_ops/stage1/get_started_with_visionapi_and_vertex_datasets.ipynb)
In this tutorial, you learn to use `Vision API` to extract text from PDF files stored on a Cloud Storage bucket. You then process the results and create an unlabelled `Vertex AI Dataset`, compatible with `AutoML`, for text entity extraction.
```
The steps performed include:
1. Using `Vision API` to perform Optical Character Recognition (OCR) to extract text from PDF files.
2. Processing the results and saving them to text files.
3. Generating a `Vertex AI Dataset` import file.
4. Creating a new unlabelled text entity extraction `Vertex AI Dataset` resource in `Vertex AI`.
- Using Vision API to perform Optical Character Recognition (OCR) to extract text from PDF files.
- Processing the results and saving them to text files.
- Generating a Vertex AI Dataset import file.
- Creating a new unlabelled text entity extraction Vertex AI Dataset resource in Vertex AI.
```
### E2E Stage Example
[Stage 1: Data Management](mlops_data_management.ipynb)
```
The steps performed include:
- Explore and visualize the data.
- Create a Vertex AI `Dataset` resource from `BigQuery` table -- for AutoML training.
- Extract a copy of the dataset to a CSV file in Cloud Storage.
@@ -118,3 +115,4 @@ The steps performed include:
- Generate a TFRecord feature specification using TensorFlow Data Validation from the data schema.
- Preprocess a portion of the BigQuery data using `Dataflow` -- for custom training.
```
@@ -64,6 +64,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 1 : data management: get started with BigQuery datasets."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). In this version of the dataset you consider the fields year, month and day to predict the value of mean daily temperature (mean_temp)."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -120,7 +131,7 @@
" - XGBoost model training:\n",
" - Use BigQuery ML built-in XGBoost training.\n",
" - Alternatively, create a DMatrix generator from CSV files extracted from BigQuery table.\n",
" - PyTorch model training:\n",
" - Pytorch model training:\n",
" - Extract the BigQuery to a pandas dataframe.\n",
" - Preprocess the data in the dataframe.\n",
" - Create a DataLoader generator from the pandas dataframe.\n",
@@ -129,26 +140,8 @@
"- Alternatively:\n",
" - Extract the BigQuery table to CSV files.\n",
" - Preprocess the CSV files.\n",
" - Create a tf.data.Dataset generator from the CSV files."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). In this version of the dataset you consider the fields year, month and day to predict the value of mean daily temperature (mean_temp)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9e483012a752"
},
"source": [
" - Create a tf.data.Dataset generator from the CSV files.\n",
" \n",
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -191,8 +184,13 @@
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"extra_pkgs = \"tensorflow tensorflow-io==0.18 pyarrow xgboost google-cloud-bigquery\"\n",
"! pip3 install --upgrade --quiet {USER_FLAG} google-cloud-aiplatform $extra_pkgs"
"# Install the packages\n",
"! pip3 install --upgrade pyarrow $USER_FLAG -q\n",
"! pip3 install --upgrade google-cloud-bigquery $USER_FLAG -q\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install -U xgboost $USER_FLAG -q\n",
"! pip3 install -U tensorflow $USER_FLAG -q\n",
"! pip3 install -U tensorflow-io==0.18 $USER_FLAG -q"
]
},
{
@@ -214,9 +212,9 @@
},
"outputs": [],
"source": [
"import sys\n",
"import os\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
@@ -227,42 +225,274 @@
{
"cell_type": "markdown",
"metadata": {
"id": "fc8fb52b5cca"
"id": "84cd83853240"
},
"source": [
"### Common setup\n",
"## Before you begin\n",
"\n",
"Now, execute the common setup for the notebook tutorials."
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI, BigQuery, Compute Engine and Cloud Storage APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,bigquery,compute_component,storage_component).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "project_id"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "001a0fcd5d78"
"id": "set_project_id"
},
"outputs": [],
"source": [
"# Common code setup for notebook tutorials\n",
"\n",
"! wget https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/setup.py -O setup.py\n",
"\n",
"%run setup.py --bucket"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d809f07a8935"
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"# Other Common setup instructions for notebook tutorials\n",
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"! wget https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/setup.md -O setup.md\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"%load setup.md"
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "77c385f0db59"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"1. **Click Create service account**.\n",
"\n",
"2. In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"3. In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex AI\" into the filter box, and select **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"4. Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"5. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "535223fa4b84"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:custom"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you create a dataset resource using the Vertex SDK, you can provide a Cloud Storage bucket that contains the data. Vertex AI creates the dataset resource from the data. In this tutorial, Vertex AI also creates a dataset resource from your data in the Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
},
"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": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
@@ -383,7 +613,7 @@
"outputs": [],
"source": [
"dataset = aiplatform.TabularDataset.create(\n",
" display_name=\"NOAA historical weather data\" + \"_\" + UUID,\n",
" display_name=\"NOAA historical weather data\" + \"_\" + TIMESTAMP,\n",
" bq_source=[IMPORT_FILE],\n",
" labels={\"user_metadata\": BUCKET_URI[5:]},\n",
")\n",
@@ -458,7 +688,7 @@
"gcs_source = IMPORT_FILES\n",
"\n",
"dataset = aiplatform.TabularDataset.create(\n",
" display_name=\"NOAA historical weather data\" + \"_\" + UUID,\n",
" display_name=\"NOAA historical weather data\" + \"_\" + TIMESTAMP,\n",
" gcs_source=gcs_source,\n",
" labels={\"user_metadata\": BUCKET_URI[5:]},\n",
")\n",
@@ -500,10 +730,10 @@
" or BQ_MY_DATASET is None\n",
" or BQ_MY_DATASET == \"[your-dataset-name]\"\n",
"):\n",
" BQ_MY_DATASET = \"mlops_dataset_\" + UUID\n",
" BQ_MY_DATASET = \"mlops_dataset_\" + TIMESTAMP\n",
"\n",
"if BQ_MY_TABLE == \"\" or BQ_MY_TABLE is None or BQ_MY_TABLE == \"[your-view-name]\":\n",
" BQ_MY_TABLE = \"mlops_view_\" + UUID"
" BQ_MY_TABLE = \"mlops_view_\" + TIMESTAMP"
]
},
{
@@ -44,7 +44,7 @@
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage1/get_started_dataflow.ipynb\">\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_dataflow.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 1 : data management: get started with Dataflow."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset you use only the fields year, month and day to predict the value of mean daily temperature (mean_temp)."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -126,34 +137,6 @@
"Alternately for AutoML tabular model training, you can reconfigure the otherwise default preprocessing."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset you use only the fields year, month and day to predict the value of mean daily temperature (mean_temp)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9e483012a752"
},
"source": [
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"- Vertex AI\n",
"- Cloud Storage\n",
"- BigQuery\n",
"- Dataflow\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage pricing](https://cloud.google.com/storage/pricing), [BigQuery pricing](https://cloud.google.com/bigquery/pricing), and [Dataflow pricing](https://cloud.google.com/dataflow/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -186,9 +169,13 @@
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"extra_pkgs = \"tensorflow==2.5 tensorflow-data-validation==1.2 tensorflow-transform==1.2 \\\n",
" tensorflow-io==0.18 pyarrow pandas apache-beam[gcp] google-cloud-bigquery\"\n",
"! pip3 install --upgrade --quiet {USER_FLAG} google-cloud-aiplatform $extra_pkgs"
"! pip3 install -U tensorflow==2.5 $USER_FLAG -q\n",
"! pip3 install -U tensorflow-data-validation==1.2 $USER_FLAG -q\n",
"! pip3 install -U tensorflow-transform==1.2 $USER_FLAG -q\n",
"! pip3 install -U tensorflow-io==0.18 $USER_FLAG -q\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install --upgrade google-cloud-bigquery $USER_FLAG -q\n",
"! pip3 install --upgrade apache-beam[gcp] $USER_FLAG -q"
]
},
{
@@ -210,9 +197,9 @@
},
"outputs": [],
"source": [
"import sys\n",
"import os\n",
"\n",
"if \"google.colab\" in sys.modules:\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
@@ -223,42 +210,279 @@
{
"cell_type": "markdown",
"metadata": {
"id": "fc8fb52b5cca"
"id": "84cd83853240"
},
"source": [
"### Common setup\n",
"## Before you begin\n",
"\n",
"Now, execute the common setup for the notebook tutorials."
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
"\n",
"1. [Enable the Vertex AI, BigQuery, Compute Engine and Cloud Storage APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,bigquery,compute_component,storage_component).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "project_id"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "001a0fcd5d78"
"id": "set_project_id"
},
"outputs": [],
"source": [
"# Common code setup for notebook tutorials\n",
"\n",
"! wget https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/setup.py -O setup.py\n",
"\n",
"%run setup.py --bucket"
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d809f07a8935"
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"# Other Common setup instructions for notebook tutorials\n",
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"! wget https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/setup.md -O setup.md\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.\n",
"\n",
"%load setup.md "
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.\n",
"\n",
"Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "region"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "timestamp"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "77c385f0db59"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"\n",
"**Otherwise**, follow these steps:\n",
"\n",
"In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
"\n",
"1. **Click Create service account**.\n",
"\n",
"2. In the **Service account name** field, enter a name, and click **Create**.\n",
"\n",
"3. In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex AI\" into the filter box, and select **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
"\n",
"4. Click Create. A JSON file that contains your key downloads to your local environment.\n",
"\n",
"5. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "535223fa4b84"
},
"outputs": [],
"source": [
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your GCP account. This provides access to your\n",
"# Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this notebook locally, replace the string below with the\n",
" # path to your service account key and run this cell to authenticate your GCP\n",
" # account.\n",
" elif not os.getenv(\"IS_TESTING\"):\n",
" %env GOOGLE_APPLICATION_CREDENTIALS ''"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:custom"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you submit a custom training job using the Vertex SDK, you upload a Python package\n",
"containing your training code to a Cloud Storage bucket. Vertex AI runs\n",
"the code from this package. In this tutorial, Vertex AI also saves the\n",
"trained model that results from your job in the same bucket. You can then\n",
"create an `Endpoint` resource based on this output in order to serve\n",
"online predictions.\n",
"\n",
"Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
},
"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": "create_bucket"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "validate_bucket"
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
]
},
{
@@ -1078,7 +1302,7 @@
},
"outputs": [],
"source": [
"delete_storage = False\n",
"delete_storage = True\n",
"\n",
"if delete_storage or os.getenv(\"IS_TESTING\"):\n",
" if \"BUCKET_URI\" in globals():\n",
@@ -29,16 +29,16 @@
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 1 : data management: get started with Vertex AI datasets\n",
"# E2E ML on GCP: MLOps stage 1 : data management: get started with Vertex datasets\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_vertex_datasets.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_vertex_datasets.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_vertex_datasets.ipynb\">\n",
" <a href=\"https://console.cloud.google.com/ai/platform/notebooks/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_vertex_datasets.ipynb\">\n",
"<img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
@@ -136,26 +136,9 @@
" - Create a tf.data.Dataset generator from the CSV index file.\n",
" - If text strings are in text files:\n",
" - Using the JSON index file, convert the text files and labels to TFRecords.\n",
" - Create a tf.data.Dataset from the TFRecords."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "533dd6fe83c8"
},
"source": [
"### Datasets\n",
" - Create a tf.data.Dataset from the TFRecords.\n",
"\n",
"This tutorial uses a variety of public datasets to demonstrate using a `Vertex AI` managed dataset."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9e483012a752"
},
"source": [
" \n",
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -243,8 +226,6 @@
"id": "cb082379ed5b"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -282,22 +263,36 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
"import os\n",
"\n",
"PROJECT_ID = \"\"\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Get your Google Cloud project ID from gcloud\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID: \", PROJECT_ID)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "37c0a68ff20d"
},
"source": [
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nWlzLu5ELxWd"
"id": "autoset_project_id"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 1 : data management: get started with Vertex AI Data Labeling service."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -91,17 +102,6 @@
"Learn more about [Request a Vertex AI Data Labeling job](https://cloud.google.com/vertex-ai/docs/datasets/data-labeling-job)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -167,7 +167,7 @@
"id": "restart"
},
"source": [
"### Restart the kernel\n",
"### Restart the Kernel\n",
"\n",
"Once you've installed the Vertex AI SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.\n"
]
@@ -212,7 +212,7 @@
"\n",
"3. [Enable the Vertex AI APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component)\n",
"\n",
"4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Vertex AI Workbench Notebooks.\n",
"4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebooks.\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -220,17 +220,6 @@
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -374,8 +363,15 @@
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already\n",
"authenticated. \n",
"\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "32e1cd21a5d5"
},
"source": [
"**If you are using Colab**, run the cell below and follow the instructions\n",
"when prompted to authenticate your account via oAuth.\n",
"\n",
@@ -53,7 +53,7 @@
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage1/get_started_with_visionapi_and_vertex_datasets.ipynb\">\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_with_visionapi_and_vertex_datasets.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
@@ -70,36 +70,11 @@
"source": [
"## Overview\n",
"\n",
"This notebook creates an unlabelled `Vertex AI AutoML` text entity extraction dataset based on a collection of PDF files stored in a Cloud Storage bucket. \n",
"This notebook will create an unlabelled `Vertex AI AutoML` text entity extraction dataset based on a collection of PDF files stored in a Cloud Storage bucket. \n",
"\n",
"The notebook can be modified to create different types of text datasets including sentiment analysis and classification."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3f8c2f702ccd"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn to use `Vision API` to extract text from PDF files stored on a Cloud Storage bucket. You then process the results and create an unlabelled `Vertex AI Dataset`, compatible with `AutoML`, for text entity extraction.\n",
"\n",
"You can then either use Google Cloud console to annotate / label the dataset, or create a labelling job as demonstrated in [this notebook](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_with_data_labeling.ipynb).\n",
"\n",
"This tutorial uses the following Google Cloud services:\n",
"\n",
"- `Vision AI`\n",
"- `Vertex AI AutoML`\n",
"\n",
"The steps performed include:\n",
"\n",
"1. Using `Vision API` to perform Optical Character Recognition (OCR) to extract text from PDF files.\n",
"2. Processing the results and saving them to text files.\n",
"3. Generating a `Vertex AI Dataset` import file.\n",
"4. Creating a new unlabelled text entity extraction `Vertex AI Dataset` resource in `Vertex AI`."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -115,6 +90,31 @@
"The data is published as a [public dataset](https://cloud.google.com/bigquery/public-data) on `BigQuery`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3f8c2f702ccd"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn to use `Vision API` to extract text from PDF files stored on a Cloud Storage bucket. You will then process the results and create an unlabelled `Vertex AI Dataset`, compatible with `AutoML`, for text entity extraction.\n",
"\n",
"You can then either use Google Cloud console to annotate / label the dataset, or create a labelling job as demonstrated in [this notebook](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/get_started_with_data_labeling.ipynb).\n",
"\n",
"This tutorial uses the following Google Cloud services:\n",
"\n",
"- `Vision AI`\n",
"- `Vertex AI AutoML`\n",
"\n",
"The steps performed include:\n",
"\n",
"1. Using `Vision API` to perform Optical Character Recognition (OCR) to extract text from PDF files.\n",
"2. Processing the results and saving them to text files.\n",
"3. Generating a `Vertex AI Dataset` import file.\n",
"4. Creating a new unlabelled text entity extraction `Vertex AI Dataset` resource in `Vertex AI`."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -257,7 +257,7 @@
"\n",
"3. [Enable the following APIs: Vision API, Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=vision.googleapis.com,aiplatform.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -265,17 +265,6 @@
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -39,15 +39,18 @@
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage1/mlops_data_management.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\\\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage1/mlops_data_management.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>\n",
"<br/><br/><br/>\n",
"\n",
"*Note: This notebook is not supported for execution in Colab*"
"<br/><br/><br/>"
]
},
{
@@ -62,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 1 : data management."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:bq,chicago,lbn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Chicago Taxi](https://www.kaggle.com/chicago/chicago-taxi-trips-bq). The version of the dataset you will use in this tutorial is stored in a public BigQuery table. The trained model predicts whether someone would leave a tip for a taxi fare."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -106,34 +120,6 @@
" - Preprocess the data with `Dataflow`"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:bq,chicago,lbn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Chicago Taxi](https://www.kaggle.com/chicago/chicago-taxi-trips-bq). The version of the dataset used in this tutorial is stored in a public BigQuery table. The trained model predicts whether someone leaves a tip for a taxi fare."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9e483012a752"
},
"source": [
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"- Vertex AI\n",
"- Cloud Storage\n",
"- BigQuery\n",
"- Dataflow\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage pricing](https://cloud.google.com/storage/pricing), [BigQuery pricing](https://cloud.google.com/bigquery/pricing), and [Dataflow pricing](https://cloud.google.com/dataflow/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -166,20 +152,20 @@
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"ONCE_ONLY = False\n",
"ONCE_ONLY = True\n",
"if ONCE_ONLY:\n",
" ! pip3 install -U {USER_FLAG} -q tensorflow==2.5 \\\n",
" tensorflow-data-validation==1.2 \\\n",
" tensorflow-transform==1.2 \\\n",
" tensorflow-io==0.18 \n",
" \n",
" ! pip3 install --upgrade {USER_FLAG} -q google-cloud-aiplatform[tensorboard] \\\n",
" google-cloud-pipeline-components \\\n",
" google-cloud-bigquery \\\n",
" google-cloud-logging \\\n",
" apache-beam[gcp] \\\n",
" pyarrow \\\n",
" cloudml-hypertune\n"
" ! pip3 install -U tensorflow==2.5 $USER_FLAG\n",
" ! pip3 install -U tensorflow-data-validation==1.2 $USER_FLAG\n",
" ! pip3 install -U tensorflow-transform==1.2 $USER_FLAG\n",
" ! pip3 install -U tensorflow-io==0.18 $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-aiplatform[tensorboard] $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-pipeline-components $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-bigquery $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-logging $USER_FLAG\n",
" ! pip3 install --upgrade apache-beam[gcp] $USER_FLAG\n",
" ! pip3 install --upgrade pyarrow $USER_FLAG\n",
" ! pip3 install --upgrade cloudml-hypertune $USER_FLAG\n",
" ! pip3 install --upgrade kfp $USER_FLAG"
]
},
{
@@ -351,7 +337,7 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. \n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"\n",
@@ -387,11 +373,12 @@
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
@@ -413,7 +400,7 @@
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"When you submit a custom training job using the Vertex AI SDK, you upload a Python package\n",
"When you submit a custom training job using the Vertex SDK, you upload a Python package\n",
"containing your training code to a Cloud Storage bucket. Vertex AI runs\n",
"the code from this package. In this tutorial, Vertex AI also saves the\n",
"trained model that results from your job in the same bucket. You can then\n",
@@ -662,7 +649,7 @@
},
"outputs": [],
"source": [
"bqclient = bigquery.Client(project=PROJECT_ID)"
"bqclient = bigquery.Client()"
]
},
{
@@ -785,11 +772,6 @@
"LIMIT = 300000\n",
"YEAR = 2020\n",
"\n",
"# First, create the dataset entry\n",
"dataset = bigquery.Dataset(f\"{PROJECT_ID}.{BQ_DATASET}\")\n",
"dataset.location = \"US\"\n",
"dataset = bqclient.create_dataset(dataset, timeout=30)\n",
"\n",
"query = f\"\"\"\n",
"CREATE OR REPLACE TABLE `{BQ_TABLE_COPY}`\n",
"AS (\n",
@@ -1230,7 +1212,7 @@
"import setuptools\n",
"\n",
"REQUIRED_PACKAGES = [\n",
" \"google-cloud-aiplatform\",\n",
" \"google-cloud-aiplatform==1.4.2\",\n",
" \"tensorflow-transform==1.2.0\",\n",
" \"tensorflow-data-validation==1.2.0\",\n",
"]\n",
+186 -219
View File
@@ -35,167 +35,18 @@ The second stage in MLOps is experimenting in developing one or more baseline mo
### Get Started
[Get started with Vertex AI Training for R](community/ml_ops/stage2/get_started_vertex_training_r.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` for training a R custom model.
The steps performed include:
- Locally train an R model in a notebook using %%R magic commands
- Create a deployment image with trained R model and serving functions.
- Test the deployment image locally.
- Create a `Vertex AI Model` resource for the deployment image with embedded R model.
- Deploy the deployment image with embedded R model to a `Vertex AI Endpoint` resource.
- Test the deployment image with embedded R model.
- Create a R-to-Python training package.
- Create a training image for training the model.
- Train a R model using `Vertex AI Trainingh` service with the R-to-Python training package.
[Get started with Logging](community/ml_ops/stage2/get_started_with_logging.ipynb)
In this tutorial, you learn how to use Python and Cloud logging awhen training with `Vertex AI`.
[Get Started with Logging](get_started_with_logging.ipynb)
```
The steps performed include:
- Use Python logging to log training configuration/results locally.
- Use Google Cloud Logging to log training configuration/results in cloud storage.
```
[Get started with Vertex AI Hyperparameter Tuning for XGBoost] (community/ml_ops/stage2/get_started_vertex_hpt_xgboost.ipynb)
In this tutorial, you learn how to use `Vertex AI Hyperparameter Tuning` for training a XGBoost custom model.
The steps performed include:
- Training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
[Get started with Vertex AI Training for XGBoost](community/ml_ops/stage2/get_started_vertex_training_xgboost.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` for training a XGBoost custom model.
The steps performed include:
- Training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
[Get started with TabNet builtin algorithm for training tabular models](community/ml_ops/stage2/get_started_with_tabnet.ipynb)
In this notebook, you learn how to run `Vertex AI TabNet` built algorithm for training custom tabular models.
The steps performed include:
- Get the training data.
- Configure training parameters for the `Vertex AI TabNet` container.
- Train the model using `Vertex AI Training` using CSV data.
- Upload the model as a `Vertex AI Model` resource.
- Deploy the `Vertex AI Model` resource to a `Vertex AI Endpoint` resource.
- Make a prediction with the deployed model.
- Hyperparameter tuning the `Vertex AI TabNet` model.
- Train the model using `Vertex AI Training` using BigQuery table.
[Get started with prebuilt TFHub models](community/ml_ops/stage2/get_started_with_tfhub_models.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` with prebuilt models from TensorFlow Hub.
The steps performed include:
- Download a TensorFlow Hub prebuilt model.
- Add the task component as a classifier for the CIFAR-10 dataset.
- Fine tune locally the model with transfer learning training.
- Construct a custom training script:
- Get training data from TensorFlow Datasets
- Get model architecture from TensorFlow Hub
- Train then model
- Save model artifacts and upload as Vertex AI Model resource.
[Get started with BigQuery ML Training](community/ml_ops/stage2/get_started_bqml_training.ipynb)
In this tutorial, you learn how to use `BigQueryML` (BQML) for training with `Vertex AI`.
The steps performed include:
- Create a local BigQuery table in your project
- Train a BQML model
- Evaluate the BQML model
- Export the BQML model as a cloud model
- Upload the exported model as a `Vertex AI Model` resource
- Hyperparameter tune a BQML model with `Vertex AI Vizier`
- Automatically register a BQML model to `Vertex AI Model Registry`
[Get started with Vertex AI Vizier](community/ml_ops/stage2/get_started_vertex_vizier.ipynb)
In this tutorial, you learn how to use `Vertex AI Vizier` for when training with `Vertex AI`.
The steps performed include:
- Hyperparameter tuning with Random algorithm.
- Hyperparameter tuning with Vizier (Bayesian) algorithm.
- Suggesting trials and updating results for Vizier study
[Get started with distributed training using DASK](community/ml_ops/stage2/get_started_with_distributed_training_xgboost.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` for distributed training of XGBoost model using the OSS package DASK. Additionally, you learn to construct and deploy a custom serving container using a Flask web server.
The steps performed include:
- Construct an XGBoost training script using DASK for distributed training.
- Construct a custom training container.
- Configure a distributed custom training job.
- Execute the custom training job.
- Construct a custom serving container using Flask.
- Upload the trained XGBoost model as a `Vertex AI Model` resource.
- Create a `Vertex AI Endpoint` resource.
- Deploy the `Vertex AI Model` resource to `Vertex AI Endpoint` resource.
- Make a prediction.
[Get started with Vertex AI TensorBoard](community/ml_ops/stage2/get_started_vertex_tensorboard.ipynb)
In this tutorial, you learn how to use `Vertex AI TensorBoard` when training with `Vertex AI`.
The steps performed include:
- Create a TensorBoard callback when training a model.
- Using TensorBoard with locally trained model.
- Using Vertex AI TensorBoard with Vertex AI Training.
[Get started with Vertex AI Training for R using R Kernel](community/ml_ops/stage2/get_started_vertex_training_r_using_r_kernel.ipynb)
In this tutorial, you learn how to use `Vertex AI`, using an R kernel, for training and deploying an R custom model.
The steps performed include:
- Create a custom R training script
- Create a custom R serving script
- Create a custom R deployment (serving) container.
- Train the model using `Vertex AI` custom training.
- Create an `Endpoint` resouce.
- Deploy the `Model` resource (trained R model) to the `Endpoint` resource.
- Make an online prediction.
[Get started Vision API test preprocessing and AutoML text model generation](community/ml_ops/stage2/get_started_with_visionapi_and_automl.ipynb)
In this tutorial, you create an `AutoML` text entity extraction model pre-existing extracted data by generating a custom import file. You deploy this mode for online prediction from a Python script using the `BigQuery`, `Vision AI`, Cloud Storage and `Vertex AI SDK` for Python.
The steps performed include:
- Preprocess training files using `Vision AI` APIs to extract the text from PDF files.
- Create a custom import file that includes annotation data based on the sample `BigQuery` dataset.
- Create a `Vertex AI Dataset` resource.
- Train the model.
- View the model evaluation.
- Deploy the `Vertex AI Model` resource to a serving `Endpoint` resource.
- Make a prediction.
- Undeploy the `Model`.
[Get started with Vertex AI Experiments](community/ml_ops/stage2/get_started_vertex_experiments.ipynb)
In this tutorial, you learn how to use `Vertex AI Experiments` when training with `Vertex AI`.
[Get Started with Vertex Experiments and Vertex ML Metadata](get_started_vertex_experiments.ipynb)
```
The steps performed include:
- Local (notebook) Training
@@ -214,49 +65,94 @@ The steps performed include:
- Create a `Vertex AI Training` custom job
- Execute the custom job
- Visualize the experiment results
```
[AutoML Image Classfication Training with Customer Managed Encryption Keys (CMEK)](community/ml_ops/stage2/get_started_with_cmek_training.ipynb)
In this tutorial, you learn how to use a customer managed encryption key (CMEK) for `Vertex AI AutoML` training.
[Get Started with Vertex TensorBoard](get_started_vertex_tensorboard.ipynb)
```
The steps performed include:
- Creating a customer managed encryption key.
- Creating an image dataset with CMEK encryption.
- Train an AutoML model with CMEK encryption.
- Create a TensorBoard callback when training a model.
- Using Tensorboard with locally trained model.
- Using Vertex AI TensorBoard with Vertex AI Training.
```
[Get started with Vertex AI Feature Store](community/ml_ops/stage2/get_started_vertex_feature_store.ipynb)
In this tutorial, you learn how to use `Vertex AI Feature Store` when training and predicting with `Vertex AI`.
[Get Started with Custom Training Packages (Tensorflow)](get_started_vertex_training.ipynb)
```
The steps performed include:
- Creating a Vertex AI `Featurestore` resource.
- Creating `EntityType` resources for the `Featurestore` resource.
- Creating `Feature` resources for each `EntityType` resource.
- Import feature values (entity data items) into `Featurestore` resource.
- From a Cloud Storage location.
- From a pandas DataFrame.
- Perform online serving from a `Featurestore` resource.
- Perform batch serving from a `Featurestore` resource.
- Training using a single Python script.
- Training using a Python package.
- Training using a custom training image.
- Laying out a training package.
```
[Get started with AutoML Training](community/ml_ops/stage2/get_started_automl_training.ipynb)
In this tutorial, you learn how to use `AutoML` for training with `Vertex AI`.
[Get Started with Custom Training Packages (Scikit-Learn)](get_started_vertex_training_sklearn.ipynb)
```
The steps performed include:
- Train an image model
- Export the image model as an edge model
- Train a tabular model
- Export the tabular model as a cloud model
- Train a text model
- Train a video model
- Training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
```
[Get started with Vertex AI Training for LightGBM](community/ml_ops/stage2/get_started_vertex_training_lightgbm.ipynb)
[Get Started with Custom Training Packages (XGBoost)](get_started_vertex_training_xgboost.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` for training a LightGBM custom model.
```
The steps performed include:
- Training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
```
[Get Started with Custom Training Packages (Pytorch)](get_started_vertex_training_pytorch.ipynb)
```
The steps performed include:
- Single node training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
```
[Get Started with Custom Training Packages (R)](get_started_vertex_training_r.ipynb)
```
The steps performed include:
- Locally train an R model in a notebook using %%R magic commands
- Create a deployment image with trained R model and serving functions.
- Test the deployment image locally.
- Create a `Vertex AI Model` resource for the deployment image with embedded R model.
- Deploy the deployment image with embedded R model to a `Vertex AI Endpoint` resource.
- Test the deployment image with embedded R model.
- Create a R-to-Python training package.
- Create a training image for training the model.
- Train a R model using `Vertex AI Trainingh` service with the R-to-Python training package.
```
[Get Started with Custom Training Packages (R) and Deployment in R environment](get_started_vertex_training_r_using_r_kernel.ipynb)
```
The steps performed include:
- Create a custom R training script
- Create a custom R serving script
- Create a custom R deployment (serving) container.
- Train the model using `Vertex AI` custom training.
- Create an `Endpoint` resource.
- Deploy the `Model` resource (trained R model) to the `Endpoint` resource.
- Make an online prediction.
```
[Get Started with Custom Training Packages (LightGBM)](get_started_vertex_training_lightgbm.ipynb)
```
The steps performed include:
- Training using a Python package.
@@ -265,45 +161,11 @@ The steps performed include:
- Construct a Dockerfile deployment image.
- Test the deployment image locally.
- Create a `Vertex AI Model` resource.
```
[Get started with Vertex AI Training for Scikit-Learn](community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` for training a Scikit-Learn custom model.
The steps performed include:
- Training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
[Get started with Vertex AI Training](community/ml_ops/stage2/get_started_vertex_training.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` for custom models when training with `Vertex AI`.
The steps performed include:
- Training using a single Python script.
- Training using a Python package.
- Training using a custom training image.
- Laying out a training package.
[Get started with Vertex AI Training for Pytorch](community/ml_ops/stage2/get_started_vertex_training_pytorch.ipynb)
In this tutorial, you learn how to use `Vertex AI Training` for training a Pytorch custom model.
The steps performed include:
- Single node training using a Python package.
- Report accuracy when hyperparameter tuning.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Create a `Vertex AI Model` resource.
[Get started with Vertex AI Distributed Training](community/ml_ops/stage2/get_started_vertex_distributed_training.ipynb)
In this tutorial, you learn how to use `Vertex AI Distributed Training` for when training with `Vertex AI`.
[Get Started with Distributed Training](get_started_vertex_distributed_training.ipynb)
```
The steps performed include:
- `MirroredStrategy`: Train on a single VM with multiple GPUs.
@@ -311,6 +173,110 @@ The steps performed include:
- `MultiWorkerMirroredStrategy`: Train on multiple VMs with fine grain control of replicas.
- `ReductionServer`: Train on multiple VMS and sync updates across VMS with `Vertex AI Reduction Server`.
- `TPUTraining`: Train with multiple Cloud TPUs.
```
[Get Started with Vizier Hyperparameter Tuning](get_started_vertex_vizier.ipynb)
```
The steps performed include:
- Hyperparameter tuning with Random algorithm.
- Hyperparameter tuning with Vizier (Bayesian) algorithm.
```
[Get Started with AutoML Training](get_started_automl_training.ipynb)
```
The steps performed include:
- Train an image model.
- Export the image model as an edge model.
- Train a tabular model.
- Export the tabular model as a cloud model.
- Train a text model.
```
[Get Started with BQML Training](get_started_bqml_training.ipynb)
```
The steps performed include:
- Create a local BigQuery table in your project
- Train a BQML model
- Evaluate the BQML model
- Export the BQML model as a cloud model
- Upload the exported model as a `Vertex AI Model` resource
- Hyperparameter tune a BQML model with `Vertex AI Vizier`
- Automatically register a BQML model to `Vertex AI Model Registry`
```
[Get Started with Vertex Feature Store](get_started_vertex_feature_store.ipynb)
```
The steps performed include:
- Creating a Vertex AI `Featurestore` resource.
- Creating `EntityType` resources for the `Featurestore` resource.
- Creating `Feature` resources for each `EntityType` resource.
- Import feature values (entity data items) into `Featurestore` resource from Cloud Storage.
- Import feature values (entity data items) into `Featurestore` resource from pandas DataFrame.
- Perform online serving from a `Featurestore` resource.
- Perform batch serving from a `Featurestore` resource.
```
[Get Started with Google CMEK Training](get_started_with_cmek_training.ipynb)
```
The steps performed include:
- Creating a customer managed encryption key.
- Creating an image dataset with CMEK encryption.
- Train an AutoML model with CMEK encryption.
```
[Get Started with TensorFlow Hub models](get_started_with_tfhub_models.ipynb)
```
The steps performed include:
- Download a TensorFlow Hub prebuilt model.
- Add the task component as a classifier for the CIFAR-10 dataset.
- Fine tune locally the model with transfer learning training.
- Construct a custom training script:
- Get training data from TensorFlow Datasets
- Get model architecture from TensorFlow Hub
- Train then model
- Save model artifacts and upload as Vertex AI Model resource.
```
[Get Started with Vertex AI TabNet builtin algorithm](get_started_with_tabnet.ipynb)
```
The steps performed include:
- Get the training data.
- Configure training parameters for the Vertex AI TabNet container.
- Train the model using Vertex AI Training using CSV data.
- Upload the model as a Vertex AI Model resource.
- Deploy the Vertex AI Model resource to a Vertex AI Endpoint resource.
- Make a prediction with the deployed model.
- Hyperparameter tuning the Vertex AI TabNet model.
- Train the model using Vertex AI Training using BigQuery table.
```
[Get Started with Vision API and AutoML](get_started_with_visionapi_and_automl.ipynb)
```
The steps performed include:
- Preprocess training files using `Vision AI` APIs to extract the text from PDF files.
- Create a custom import file that includes annotation data based on the sample `BigQuery` dataset.
- Create a `Vertex AI Dataset` resource.
- Train the model.
- View the model evaluation.
- Deploy the `Vertex AI Model` resource to a serving `Endpoint` resource.
- Make a prediction.
- Undeploy the `Model`.
```
### E2E Stage Example
@@ -318,6 +284,7 @@ The steps performed include:
```
The steps performed include:
- Review the `Dataset` resource created during stage 1.
- Train an AutoML tabular binary classifier model in the background.
- Build the experimental model architecture.
@@ -65,6 +65,52 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with AutoML Training."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Datasets\n",
"\n",
"#### Image\n",
"\n",
"The image dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower in a given image from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"#### Tabular\n",
"\n",
"The tabular dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset you use only the fields year, month and day to predict the value of mean daily temperature (mean_temp)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:happydb,tcn"
},
"source": [
"#### Text\n",
"\n",
"The text dataset used for this tutorial is the [Happy Moments dataset](https://www.kaggle.com/ritresearch/happydb) from [Kaggle Datasets](https://www.kaggle.com/ritresearch/happydb). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "98eb93ec6faa"
},
"source": [
"#### Video\n",
"\n",
"The video dataset used for this tutorial is the golf swing recognition portion of the [Human Motion dataset](https://todo) from [MIT](http://cbcl.mit.edu/publications/ps/Kuehne_etal_iccv11.pdf). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model will predict the start frame where a golf swing begins."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -78,7 +124,6 @@
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `AutoML Training`\n",
"- `Vertex AI Datasets`\n",
"\n",
"The steps performed include:\n",
"\n",
@@ -105,31 +150,6 @@
"* **You want to establish a baseline metric before experimenting with a custom model**"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Datasets\n",
"\n",
"#### Image\n",
"\n",
"The image dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower in a given image from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip.\n",
"\n",
"#### Tabular\n",
"\n",
"The tabular dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset you use only the fields year, month and day to predict the value of mean daily temperature (mean_temp).\n",
"\n",
"#### Text\n",
"\n",
"The text dataset used for this tutorial is the [Happy Moments dataset](https://www.kaggle.com/ritresearch/happydb) from [Kaggle Datasets](https://www.kaggle.com/ritresearch/happydb). The version of the dataset you use in this tutorial is stored in a public Cloud Storage bucket.\n",
"\n",
"#### Video\n",
"\n",
"The video dataset used for this tutorial is the golf swing recognition portion of the [Human Motion dataset](https://todo) from [MIT](http://cbcl.mit.edu/publications/ps/Kuehne_etal_iccv11.pdf). The version of the dataset you use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the start frame where a golf swing begins."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -218,8 +238,6 @@
"id": "project_id"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -235,15 +253,8 @@
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aee4379e8e5"
},
"source": [
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n",
"\n",
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
@@ -499,7 +510,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"metadata": {
"id": "import_aip:mbsdk"
},
@@ -569,142 +580,6 @@
"Learn more about [AutoML Model Types](https://cloud.google.com/vertex-ai/docs/start/automl-model-types)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_preparation:image,u_dataset"
},
"source": [
"### Data preparation\n",
"\n",
"The Vertex `Dataset` resource for images has some requirements for your data:\n",
"\n",
"- Images must be stored in a Cloud Storage bucket.\n",
"- Each image file must be in an image format (PNG, JPEG, BMP, ...).\n",
"- There must be an index file stored in your Cloud Storage bucket that contains the path and label for each image.\n",
"- The index file must be either CSV or JSONL.\n",
"\n",
"Learn more about [Preparing image data](https://cloud.google.com/vertex-ai/docs/datasets/prepare-image)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_import_format:icn,u_dataset,csv"
},
"source": [
"#### CSV\n",
"\n",
"For image classification, the CSV index file has the requirements:\n",
"\n",
"- No heading.\n",
"- First column is the Cloud Storage path to the image.\n",
"- Second column is the label.\n",
"- Any remaining columns are additional labels for multi-label image classification.\n",
"\n",
"For image object detection, the CSV index file has the requirements:\n",
"\n",
"- No heading.\n",
"- First column is the Cloud Storage path to the image.\n",
"- Second column is the label.\n",
"- Third/Fourth columns are the upper left corner of bounding box. Coordinates are normalized, between 0 and 1.\n",
"- Fifth/Sixth/Seventh columns are not used and should be 0.\n",
"- Eighth/Ninth columns are the lower right corner of the bounding box.\n",
"\n",
"##### ML_USE\n",
"\n",
"Each row may additionally specify which split to assign the data item to when the dataset is split for training; otherwise, the dataset will be randomly split: 80/10/10.\n",
"\n",
"The `ml_use` assignment is specified by prepending a column for specifying the assignment -- as the first column. The value may be one of: training, test, or validation."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_import_format:isg,u_dataset,jsonl"
},
"source": [
"#### JSONL\n",
"\n",
"For image classification, the JSONL index file has the requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `image_gcs_uri` is the Cloud Storage path to the image.\n",
"- The key/value pair `display_name` is the label for the image.\n",
"\n",
" { 'image_gcs_uri': image, \n",
" 'classification_annotations': \n",
" { 'display_name': label\n",
" }\n",
" }\n",
" \n",
"For multi-label, the labels are specified as a list of `display_name` key/value pairs:\n",
"\n",
" { 'image_gcs_uri': image, \n",
" 'classification_annotations': [\n",
" { 'display_name': label1\n",
" },\n",
" { 'display_name': labelN\n",
" },\n",
" ]\n",
" }\n",
" \n",
"For object detection, the JSONL index file has the requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `image_gcs_uri` is the Cloud Storage path to the image.\n",
"- The key/value pair `bounding_box_annotations` is a list of:\n",
" - `display_name`: The label of the object\n",
" - `x_min`, `y_min`, `x_max`, `y_max`: The coordinates for the bounding box\n",
"\n",
"{\n",
" \"image_gcs_uri\": image,\n",
" \"bounding_box_annotations\": [\n",
" {\n",
" \"display name\": label,\n",
" \"x_min\": \"X_MIN\",\n",
" \"y_min\": \"Y_MIN\",\n",
" \"x_max\": \"X_MAX\",\n",
" \"y_max\": \"Y_MAX\"\n",
" }\n",
" },\n",
" {\n",
" \"displayName\": \"OBJECT2_LABEL\",\n",
" \"x_min\": \"X_MIN\",\n",
" \"y_min\": \"Y_MIN\",\n",
" \"x_max\": \"X_MAX\",\n",
" \"y_max\": \"Y_MAX\"\n",
" }\n",
" ]\n",
"}\n",
"\n",
"\n",
"For image segmentation, the JSONL index file has the requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `image_gcs_uri` is the Cloud Storage path to the image.\n",
"- The key/value pair `category_mask_uri` is the Cloud Storage path to the mask image in PNG format.\n",
"- The key/value pair `'annotation_spec_colors'` is a list mapping mask colors to a label.\n",
" - The key/value pair pair `display_name` is the label for the pixel color mask.\n",
" - The key/value pair pair `color` are the RGB normalized pixel values (between 0 and 1) of the mask for the corresponding label.\n",
"\n",
" { 'image_gcs_uri': image, \n",
" 'segmentation_annotations': { 'category_mask_uri': mask_image, 'annotation_spec_colors' : [ \n",
" { 'display_name': label, 'color': {\"red\": value, \"blue\", value, \"green\": value} }, ...\n",
" ] \n",
" }\n",
" \n",
"##### ML_USE\n",
"\n",
"Each JSONL object may additionally specify which split to assign the data item to when the dataset is split for training; otherwise, the dataset will be randomly split: 80/10/10.\n",
"\n",
"\"data_item_resource_labels\": {\n",
" \"aiplatform.googleapis.com/ml_use\": \"training|test|validation\"\n",
" }\n",
"\n",
"*Note*: The dictionary key fields may alternatively be in camelCase. For example, 'image_gcs_uri' can also be 'imageGcsUri'."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -1205,42 +1080,6 @@
"Learn more about [AutoML Model Types](https://cloud.google.com/vertex-ai/docs/start/automl-model-types)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_preparation:tabular,u_dataset"
},
"source": [
"### Data preparation\n",
"\n",
"The Vertex AI `Dataset` resource for tabular has a couple of requirements for your tabular data.\n",
"\n",
"- Must be in a CSV file or a BigQuery table.\n",
"\n",
"Learn more about [Preparing tabular data](https://cloud.google.com/vertex-ai/docs/datasets/prepare-tabular)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_import_format:lbn,u_dataset,csv"
},
"source": [
"#### CSV\n",
"\n",
"For tabular models, the CSV file has a few requirements:\n",
"\n",
"- The first row must be the heading -- note how this is different from Image, Text and Video where the requirement is no heading.\n",
"- All but one column are features.\n",
"- One column is the label, which you will specify when you subsequently create the training pipeline.\n",
"\n",
"##### ML_USE\n",
"\n",
"Each row may additionally specify which split to assign the data item to when the dataset is split for training; otherwise, the dataset will be randomly split: 80/10/10.\n",
"\n",
"The `ml_use` assignment is specified by prepending a column for specifying the assignment -- as the first column. The value may be one of: training, test, or validation."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -1600,155 +1439,6 @@
"Learn more about [AutoML Model Types](https://cloud.google.com/vertex-ai/docs/start/automl-model-types)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_preparation:text,u_dataset"
},
"source": [
"### Data preparation\n",
"\n",
"The Vertex AI `Dataset` resource for text has a couple of requirements for your text data.\n",
"\n",
"- Text examples must be stored in a CSV or JSONL file.\n",
"\n",
"Learn more about [Preparing text data](https://cloud.google.com/vertex-ai/docs/datasets/prepare-text)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_import_format:tcn,u_dataset,csv"
},
"source": [
"#### CSV\n",
"\n",
"For text classification, the CSV file has a few requirements:\n",
"\n",
"- No heading.\n",
"- First column is the text example or Cloud Storage path to text file (.txt suffix).\n",
"- Second column the label.\n",
"- Any remaining columns are additional labels for multi-label text classification.\n",
"\n",
"For text sentiment analysis, the CSV file has a few requirements:\n",
"\n",
"- No heading.\n",
"- First column is the text example or Cloud Storage path to text file (.txt suffix).\n",
"- Second column is the sentiment value.\n",
"- Third column is the maximum possible sentiment value.\n",
"\n",
"##### ML_USE\n",
"\n",
"Each row may additionally specify which split to assign the data item to when the dataset is split for training; otherwise, the dataset will be randomly split: 80/10/10.\n",
"\n",
"The `ml_use` assignment is specified by prepending a column for specifying the assignment -- as the first column. The value may be one of: training, test, or validation."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "766c838de8a0"
},
"source": [
"#### JSONL \n",
"\n",
"For text classification, the JSONL file has a few requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `text_gcs_uri` is the Cloud Storage path to the text file.\n",
"- The key/value pair `text_content` is the alternate way of specifying the text as inlined.\n",
"- The key/value pair `display_name` is the label for the text.\n",
"\n",
"{\n",
" \"classification_annotation\": {\n",
" \"display_name\": label\n",
" },\n",
" \"text_content\": text\n",
"}\n",
"{\n",
" \"classification_annotation\": {\n",
" \"display_name\": label\n",
" },\n",
" \"text_gcs_uri\": \"gcs_uri_to_file\"\n",
"}\n",
"\n",
" \n",
"For multi-label, the labels are specified as a list of `display_name` key/value pairs:\n",
"\n",
" 'classification_annotations': [\n",
" { 'display_name': label1\n",
" },\n",
" { 'display_name': labelN\n",
" },\n",
" ]\n",
"\n",
"For text sentiment analysis, the JSONL file has a few requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `text_gcs_uri` is the Cloud Storage path to the text file.\n",
"- The key/value pair `text_content` is the alternate way of specifying the text as inlined.\n",
"- The key/value pair `sentiment` is the sentiment value as an integer value greater than 0.\n",
"- The key/value pair `sentiment_max`is the maximum possible value for the sentiment.\n",
"\n",
"{\n",
" \"sentiment_annotation\": {\n",
" \"sentiment\": number,\n",
" \"sentiment_max\": number\n",
" },\n",
" \"text_content\": text,\n",
"}\n",
"{\n",
" \"sentiment_annotation\": {\n",
" \"sentiment\": number,\n",
" \"sentiment_max\": number\n",
" },\n",
" \"text_gcs_uri\": \"gcs_uri_to_file\"\n",
"}\n",
"\n",
"\n",
"For text entity extraction, the JSONL file has a few requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `text_gcs_uri` is the Cloud Storage path to the text file.\n",
"- The key/value pair `text_content` is the alternate way of specifying the text as inlined.\n",
"- The key/value pair `start_offset` is the character offset of the start of the text.\n",
"- The key/value pair `end_offset` is the character offset of the end of the text.\n",
"- The key/value pair `display_name` is the label for the text.\n",
"\n",
"{\n",
" \"text_segment_annotations\": [\n",
" {\n",
" \"start_offset\":number,\n",
" \"end_offset\":number,\n",
" \"display_name\": label\n",
" },\n",
" ...\n",
" ],\n",
" \"textContent\": \"inline_text\"\n",
"}\n",
"{\n",
" \"textSegmentAnnotations\": [\n",
" {\n",
" \"start_offset\": number,\n",
" \"end_offset\": number,\n",
" \"displayName\": label\n",
" },\n",
" ...\n",
" ],\n",
" \"text_gcs_uri\": \"gcs_uri_to_file\"\n",
"}\n",
"\n",
"##### ML_USE\n",
"\n",
"Each JSONL object may additionally specify which split to assign the data item to when the dataset is split for training; otherwise, the dataset will be randomly split: 80/10/10.\n",
"\n",
"\"data_item_resource_labels\": {\n",
" \"aiplatform.googleapis.com/ml_use\": \"training|test|validation\"\n",
" }\n",
"\n",
"*Note*: The dictionary key fields may alternatively be in camelCase. For example, 'text_gcs_uri' can also be 'textGcsUri'."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -2071,144 +1761,6 @@
"Learn more about [AutoML Model Types](https://cloud.google.com/vertex-ai/docs/start/automl-model-types)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "data_preparation:text,u_dataset"
},
"source": [
"### Data preparation\n",
"\n",
"The Vertex AI `Dataset` resource for text has a couple of requirements for your text data.\n",
"\n",
"- Text examples must be stored in a CSV or JSONL file.\n",
"\n",
"Learn more about [Preparing video data](https://cloud.google.com/vertex-ai/docs/datasets/prepare-video)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "427212b48840"
},
"source": [
"#### CSV\n",
"\n",
"For video classification, the CSV file has a few requirements:\n",
"\n",
"- No heading.\n",
"- First column is the Cloud Storage path to video file.\n",
"- Second column the label.\n",
"- Third column is the start time (seconds) in the video to classify.\n",
"- Fourth column is the end time (seconds) in the video to classify.\n",
"\n",
"For multi-label classification, each label is a separate row entry.\n",
"\n",
"For video object tracking, the CSV file has a few requirements:\n",
"\n",
"- No heading.\n",
"- First column is the Cloud Storage path to video file.\n",
"- Second column the label.\n",
"- Third column is unused (blank).\n",
"- Fourth column is the start time (seconds) in the video to start tracking the object.\n",
"- The fifth through eighth columns are the vertices of the object to track.\n",
" - x_min\n",
" - y_min\n",
" - x_max\n",
" - y_max\n",
" \n",
"For action recognition, the CSV file has a few requirements:\n",
"\n",
"- No heading.\n",
"- Each row can be one of the following four formats:\n",
"\n",
"VIDEO_URI, TIME_SEGMENT_START, TIME_SEGMENT_END, LABEL, ANNOTATION_FRAME_TIMESTAMP\n",
"\n",
"VIDEO_URI, , , LABEL, ANNOTATION_FRAME_TIMESTAMP\n",
"\n",
"VIDEO_URI, TIME_SEGMENT_START, TIME_SEGMENT_END, LABEL, ANNOTATION_SEGMENT_START, ANNOTATION_SEGMENT_END\n",
"\n",
"VIDEO_URI, , , LABEL, ANNOTATION_SEGMENT_START, ANNOTATION_SEGMENT_END\n",
"\n",
"\n",
"##### ML_USE\n",
"\n",
"Each row may additionally specify which split to assign the data item to when the dataset is split for training; otherwise, the dataset will be randomly split: 80/10/10.\n",
"\n",
"The `ml_use` assignment is specified by prepending a column for specifying the assignment -- as the first column. The value may be one of: training, or test."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "461301339727"
},
"source": [
"#### JSONL\n",
"\n",
"For video classification, the CSV file has a few requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `video_gcs_uri` is the Cloud Storage path to the text file.\n",
"- The key/value pair `display_name` is the label for the text.\n",
"- The key/value pair `start_time` is the start time (seconds) for classifying.\n",
"- The key/value pair `end_time` is the end time (seconds) for classifying.\n",
"\n",
"\n",
" {\n",
" \"video_gcs_uri\": video,\n",
" \"time_segment_annotations\": [{\n",
" \"display_name\": label,\n",
" \"start_time\": \"start_time_of_segment\",\n",
" \"end_time\": \"end_time_of_segment\"\n",
" }]\n",
" }\n",
"\n",
"For video object tracking, the CSV file has a few requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `video_gcs_uri` is the Cloud Storage path to the text file.\n",
"\n",
" {\n",
" \"video_gcs_uri\": video,\n",
" \"temporal_bounding_box_annotations\": [{\n",
" \"display_name\": label,\n",
" \"x_min\": \"leftmost_coordinate_of_the_bounding box\",\n",
" \"x_max\": \"rightmost_coordinate_of_the_bounding box\",\n",
" \"y_min\": \"topmost_coordinate_of_the_bounding box\",\n",
" \"y_max\": \"bottommost_coordinate_of_the_bounding box\",\n",
" \"time_offset\": \"timeframe_object-detected\"\n",
" }]\n",
" }\n",
"\n",
"For video action recognition, the CSV file has a few requirements:\n",
"\n",
"- Each data item is a separate JSON object, on a separate line.\n",
"- The key/value pair `video_gcs_uri` is the Cloud Storage path to the text file.\n",
"\n",
" {\n",
" \"video_gcs_uri': video,\n",
" \"time_segments\": [{\n",
" \"start_time\": \"start_time_of_fully_annotated_segment\",\n",
" \"end_time\": \"end_time_of_segment\"}],\n",
" \"time_segment_annotations\": [{\n",
" \"display_name\": label,\n",
" \"start_time\": \"start_time_of_segment\",\n",
" \"end_time\": \"end_time_of_segment\"\n",
" }]\n",
" }\n",
"\n",
"##### ML_USE\n",
"\n",
"Each JSONL object may additionally specify which split to assign the data item to when the dataset is split for training; otherwise, the dataset will be randomly split: 80/20.\n",
"\n",
"\"data_item_resource_labels\": {\n",
" \"aiplatform.googleapis.com/ml_use\": \"training|test\"\n",
" }\n",
"\n",
"*Note*: The dictionary key fields may alternatively be in camelCase. For example, 'video_gcs_uri' can also be 'videoGcsUri'."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -44,7 +44,7 @@
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage2/get_started_bqml_training.ipynb\">\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_bqml_training.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
@@ -65,33 +65,6 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with BigQuery ML Training."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "objective:mlops,stage2,get_started_bqml_training"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use `BigQueryML` for training with `Vertex AI`.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `BigQueryML Training`\n",
"- `Vertex AI Model resource`\n",
"- `Vertex AI Vizier`\n",
"\n",
"The steps performed include:\n",
"\n",
"- Create a local BigQuery table in your project\n",
"- Train a BigQuery ML model\n",
"- Evaluate the BigQuery ML model\n",
"- Export the BigQuery ML model as a cloud model\n",
"- Upload the exported model as a `Vertex AI Model` resource\n",
"- Hyperparameter tune a BigQuery ML model with `Vertex AI Vizier`\n",
"- Automatically register a BigQuery ML model to `Vertex AI Model Registry`"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -106,9 +79,29 @@
{
"cell_type": "markdown",
"metadata": {
"id": "81c777b8ad32"
"id": "objective:mlops,stage2,get_started_bqml_training"
},
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use `BigQueryML` (BQML) for training with `Vertex AI`.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `BigQueryML Training`\n",
"- `Vertex AI Model resource`\n",
"- `Vertex AI Vizier`\n",
"\n",
"The steps performed include:\n",
"\n",
"- Create a local BigQuery table in your project\n",
"- Train a BQML model\n",
"- Evaluate the BQML model\n",
"- Export the BQML model as a cloud model\n",
"- Upload the exported model as a `Vertex AI Model` resource\n",
"- Hyperparameter tune a BQML model with `Vertex AI Vizier`\n",
"- Automatically register a BQML model to `Vertex AI Model Registry`\n",
"\n",
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -191,8 +184,6 @@
"id": "project_id"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -208,15 +199,8 @@
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "56d591439df1"
},
"source": [
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n",
"\n",
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
@@ -749,9 +733,9 @@
"id": "bqml_create_model"
},
"source": [
"### Train BigQuery ML model\n",
"### Train BQML model\n",
"\n",
"Next, you create and train a BigQuery ML tabular classification model from the public dataset penguins and store the model in your project using the `CREATE MODEL` statement. The model configuration is specified in the `OPTIONS` statement as follows:\n",
"Next, you create and train a BQML tabular classification model from the public dataset penguins and store the model in your project using the `CREATE MODEL` statement. The model configuration is specified in the `OPTIONS` statement as follows:\n",
"\n",
"- `model_type`: The type and archictecture of tabular model to train, e.g., DNN classification.\n",
"- `labels`: The column which are the labels.\n",
@@ -800,9 +784,9 @@
"id": "bqml_eval_model"
},
"source": [
"### Evaluate the trained BigQuery ML model\n",
"### Evaluate the trained BQML model\n",
"\n",
"Next, retrieve the model evaluation for the trained BigQuery ML model.\n",
"Next, retrieve the model evaluation for the trained BQML model.\n",
"\n",
"Learn more about [The ML.EVALUATE function](https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-evaluate)."
]
@@ -833,9 +817,9 @@
"id": "bqml_export_model"
},
"source": [
"### Export the model from BigQuery ML\n",
"### Export the model from BQML\n",
"\n",
"The model you trained in BigQuery ML is a TensorFlow model. Next, you export the TensorFlow model artifacts in TF.SavedModel format."
"The model you trained in BQML is a TensorFlow model. Next, you export the TensorFlow model artifacts in TF.SavedModel format."
]
},
{
@@ -1028,9 +1012,9 @@
"id": "bqml_create_model:vizier"
},
"source": [
"### Hyperparameter Tune and train a BigQuery ML model\n",
"### Hyperparameter Tune and train a BQML model\n",
"\n",
"Next, you train a BigQuery ML tabular classification model with hyperparameter tuning using the `Vertex AI Vizier` service. The hyperparameter settings are specified in the `OPTIONS` statement as follows:\n",
"Next, you train a BQML tabular classification model with hyperparameter tuning using the `Vertex AI Vizier` service. The hyperparameter settings are specified in the `OPTIONS` statement as follows:\n",
"\n",
"- `HPARAM_TUNING_ALGORITHM`: The algorithm for selecting the next trial parameters.\n",
"- `num_trials`: The number of trials.\n",
@@ -1083,9 +1067,9 @@
"id": "bqml_eval_model"
},
"source": [
"### Evaluate the BigQuery ML trained model\n",
"### Evaluate the BQML trained model\n",
"\n",
"Next, retrieve the model evaluation results for the trained BigQuery ML model.\n",
"Next, retrieve the model evaluation results for the trained BQML model.\n",
"\n",
"Learn more about [The ML.EVALUATE function](https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-evaluate)."
]
@@ -1142,9 +1126,9 @@
"id": "bqml_create_model:xai"
},
"source": [
"### Train a BigQuery ML model with Explainability\n",
"### Train a BQML model with Explainability\n",
"\n",
"Next, you train the same BigQuery ML model, but this time you enable Vertex AI Explainability on the model predictions by adding the option:\n",
"Next, you train the same BQML model, but this time you enable Vertex AI Explainability on the model predictions by adding the option:\n",
"\n",
"- `ENABLE_GLOBAL_EXPLAIN`"
]
@@ -29,7 +29,7 @@
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex AI Distributed Training\n",
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex Distributed Training\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex Distributed Training. Please note: There are incompatibilities between Colab and Docker and the Docker section may not work until resolved by the platform."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,boston,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Boston Housing Prices dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). The version of the dataset you will use in this tutorial is built into TensorFlow. The trained model predicts the median price of a house in units of 1K USD."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -95,6 +106,15 @@
"id": "recommendation:mlops,stage2,vertex,distributed_training"
},
"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 pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/),\n",
" to generate a cost estimate based on your projected usage.\n",
"### Recommendations\n",
"\n",
"When doing E2E MLOps on Google Cloud, the following are best practices for when to use Vertex AI Distributed Training:\n",
@@ -118,41 +138,13 @@
"While training across a large number of VMs and the model parameters updates to sync is very large."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,boston,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Boston Housing Prices dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). The version of the dataset you use in this tutorial is built into TensorFlow. The trained model predicts the median price of a house in units of 1K USD."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d10166df7141"
},
"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 pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/),\n",
" to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XkYpRvOQyVYb"
},
"source": [
"## Installation\n",
"### Install additional packages\n",
"\n",
"Install the packages required for executing this notebook."
]
@@ -178,7 +170,7 @@
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform -q"
"! pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform"
]
},
{
@@ -256,6 +248,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
@@ -87,7 +87,7 @@
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
"- `Vertex AI Experiments`\n",
"- `Vertex ML Metadata`\n",
"- `Vertex AI ML Metadata`\n",
"- `Vertex AI Training`\n",
"\n",
"The steps performed include:\n",
@@ -130,26 +130,8 @@
"\n",
"#### Experiments\n",
"\n",
"Use Vertex AI Experiments in conjunction with logging when performing experiments to compare results for different experiment configurations."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "313c25f2f514"
},
"source": [
"### Dataset\n",
"Use Vertex AI Experiments in conjunction with logging when performing experiments to compare results for different experiment configurations.\n",
"\n",
"This tutorial does not use a dataset. References to example datasets is for demonstration purposes."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bd73a4bd07ef"
},
"source": [
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -229,8 +211,6 @@
"id": "project_id"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -246,15 +226,9 @@
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1460fd744366"
},
"source": [
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n",
"\n",
"\n",
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
@@ -29,7 +29,7 @@
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex AI Feature Store\n",
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Feature Store\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
@@ -68,6 +68,19 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Feature Store."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:movies,lbn,avro"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the `Movie Recommendations` dataset. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket, in Avro format.\n",
"\n",
"This dataset is used to predict whether a person will watch a movie or not."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -94,19 +107,6 @@
"- Perform batch serving from a `Featurestore` resource."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:movies,lbn,avro"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the `Movie Recommendations` dataset. The version of the dataset you use in this tutorial is stored in a public Cloud Storage bucket, in Avro format.\n",
"\n",
"This dataset is used to predict whether a person watches a movie or not."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -194,8 +194,6 @@
"id": "project_id"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -29,7 +29,7 @@
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex AI TensorBoard\n",
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex AI Tensorboard\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
@@ -44,7 +44,7 @@
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage2/get_started_vertex_tensorboard.ipynb\">\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/notebook_template.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
@@ -62,7 +62,7 @@
"## Overview\n",
"\n",
"\n",
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI TensorBoard."
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Tensorboard."
]
},
{
@@ -83,44 +83,10 @@
"The steps performed include:\n",
"\n",
"- Create a TensorBoard callback when training a model.\n",
"- Using TensorBoard with locally trained model.\n",
"- Using Tensorboard with locally trained model.\n",
"- Using Vertex AI TensorBoard with Vertex AI Training."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "recommendation:mlops,stage2,vertex,tensorboard"
},
"source": [
"### Recommendations\n",
"\n",
"When doing E2E MLOps on Google Cloud, the following are the best practices for visualizing your training with TensorBoard.\n",
"\n",
"#### Local TensorBoard\n",
"\n",
"Use the OSS version of TensorBoard, either command-line or daemon version, when doing ad-hoc training locally.\n",
"\n",
"#### Cloud TensorBoard\n",
"\n",
"Use the tensorboard.dev, when doing training on the cloud -- unless you have a privacy issue.\n",
"\n",
"#### Experiments\n",
"\n",
"Use Vertex AI TensorBoard when you have a privacy issue or doing experiments to compare results for different experiment configurations."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "03bfd1274241"
},
"source": [
"### Dataset\n",
"\n",
"In this tutorial you use the MNIST dataset. The version of the dataset is built into the TF.Keras framework. The dataset predicts which digit an image is, between 0 .. 9."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -149,8 +115,8 @@
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. \n",
"**If you are using Colab or Google Cloud Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
@@ -183,6 +149,29 @@
"1. Open this notebook in the Jupyter Notebook Dashboard.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "recommendation:mlops,stage2,vertex,tensorboard"
},
"source": [
"### Recommendations\n",
"\n",
"When doing E2E MLOps on Google Cloud, the following are the best practices for visualizing your training with TensorBoard.\n",
"\n",
"#### Local TensorBoard\n",
"\n",
"Use the OSS version of TensorBoard, either command-line or daemon version, when doing ad-hoc training locally.\n",
"\n",
"#### Cloud TensorBoard\n",
"\n",
"Use the Tensorboard.dev, when doing training on the cloud -- unless you have a privacy issue.\n",
"\n",
"#### Experiments\n",
"\n",
"Use Vertex AI TensorBoard when you have a privacy issue or doing experiments to compare results for different experiment configurations."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -266,7 +255,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -785,9 +774,9 @@
"source": [
"## Training with TensorBoard\n",
"\n",
"TensorBoard provides the means to visualize your training in-real time and to visualize the results (metrics).\n",
"Tensorboard provides the means to visualize your training in-real time and to visualize the results (metrics).\n",
"\n",
"You can use TensorBoard in conjunction with local training, cloud training and with `Vertex AI Training`, which is referred to as `Vertex AI TensorBoard`"
"You can use Tensorboard in conjunction with local training, cloud training and with `Vertex AI Training`, which is referred to as `Vertex AI TensorBoard`"
]
},
{
@@ -62,7 +62,18 @@
"## Overview\n",
"\n",
"\n",
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Training."
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex Training."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,boston,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Boston Housing Prices dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). The version of the dataset you will use in this tutorial is built into TensorFlow. The trained model predicts the median price of a house in units of 1K USD."
]
},
{
@@ -114,38 +125,6 @@
"CustomJob"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,boston,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Boston Housing Prices dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). The version of the dataset this tutorial is built into TensorFlow. The trained model predicts the median price of a house in units of 1K USD."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c480fc50ec3c"
},
"source": [
"### Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\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": {
@@ -230,7 +209,7 @@
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -29,7 +29,7 @@
"id": "4f82ca678df6"
},
"source": [
"This notebook is a revised version of notebook from [Rajesh Thallam](https://github.com/RajeshThallam/vertex-ai-labs/blob/main/07-vertex-train-deploy-lightgbm/vertex-train-deploy-lightgbm-model.ipynb)"
"Notebook is a revised version of notebook from [Rajesh Thallam](https://github.com/RajeshThallam/vertex-ai-labs/blob/main/07-vertex-train-deploy-lightgbm/vertex-train-deploy-lightgbm-model.ipynb)"
]
},
{
@@ -43,12 +43,12 @@
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_vertex_training_lightgbm.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/ml_ops/stage2/get_started_vertex_training_lightgbm.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_vertex_training_lightgbm.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/master/notebooks/ocommunity/ml_ops/stage2/get_started_vertex_training_lightgbm.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
@@ -56,7 +56,7 @@
" <td>\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/community/ml_ops/stage2/get_started_vertex_training_lightgbm.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" Run in Vertex Workbench\n",
" </a>\n",
" </td>\n",
"</table>"
@@ -74,6 +74,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Training for LightGBM."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:iris,lcn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Iris dataset](https://www.tensorflow.org/datasets/catalog/iris) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -96,26 +107,8 @@
"- Construct a FastAPI prediction server.\n",
"- Construct a Dockerfile deployment image.\n",
"- Test the deployment image locally.\n",
"- Create a `Vertex AI Model` resource."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:iris,lcn"
},
"source": [
"### Dataset\n",
"- Create a `Vertex AI Model` resource.\n",
"\n",
"The dataset used for this tutorial is the [Iris dataset](https://www.tensorflow.org/datasets/catalog/iris) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "de76bb18c85b"
},
"source": [
"### Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
@@ -138,7 +131,7 @@
"source": [
"### Set up your local development environment\n",
"\n",
"If you are using Colab or Vertex AI Workbench Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step.\n",
"If you are using Colab or Google Cloud Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step.\n",
"\n",
"Otherwise, make sure your environment meets this notebook's requirements. You need the following:\n",
"\n",
@@ -197,10 +190,19 @@
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install -U google-cloud-storage $USER_FLAG -q\n",
"! pip3 install -U lightgbm $USER_FLAG -q\n",
"\n",
"! pip3 install -U lightgbm $USER_FLAG -q"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_tensorflow"
},
"outputs": [],
"source": [
"if os.getenv(\"IS_TESTING\"):\n",
" ! pip3 install --upgrade tensorflow $USER_FLAG -q"
" ! pip3 install --upgrade tensorflow $USER_FLAG"
]
},
{
@@ -254,7 +256,7 @@
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -29,7 +29,7 @@
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex AI Training for PyTorch\n",
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex Training for Pytorch\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
@@ -44,7 +44,7 @@
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage2/get_started_vertex_training_pytorch.ipynb\">\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/notebook_template.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
@@ -62,7 +62,18 @@
"## Overview\n",
"\n",
"\n",
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Training for PyTorch."
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex Training for Pytorch."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:pytorch,cifar10,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [CIFAR10 dataset](https://pytorch.org/vision/stable/datasets.html#cifar) from [Pytorch Datasets](https://pytorch.org/vision/stable/datasets.html). The version of the dataset you will use is built into TensorFlow. The trained model predicts which type of class an image is from ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, or truck."
]
},
{
@@ -73,7 +84,7 @@
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use `Vertex AI Training` for training a PyTorch custom model.\n",
"In this tutorial, you learn how to use `Vertex AI Training` for training a Pytorch custom model.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
@@ -89,24 +100,13 @@
"- Create a `Vertex AI Model` resource."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:pytorch,cifar10,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [CIFAR10 dataset](https://pytorch.org/vision/stable/datasets.html#cifar) from [PyTorch Datasets](https://pytorch.org/vision/stable/datasets.html). The version of the dataset is built into TensorFlow. The trained model predicts which type of class an image is from ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, or truck."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "85ee859437ed"
},
"source": [
"### Costs \n",
"## Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -128,7 +128,7 @@
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"**If you are using Colab or Google Cloud Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step."
]
},
@@ -672,17 +672,17 @@
"id": "pytorch_intro"
},
"source": [
"## Introduction to PyTorch training\n",
"## Introduction to Pytorch training\n",
"\n",
"The PyTorch package supports both single node and distributed model training.\n",
"The Pytorch package supports both single node and distributed model training.\n",
"\n",
"Once you have trained a PyTorch model, you will want to save it at a Cloud Storage location, so it can subsequently be uploaded to a `Vertex AI Model` resource.\n",
"The PyTorch package does not have support to save the model to a Cloud Storage location. Instead, you will do the following steps to save to a Cloud Storage location.\n",
"Once you have trained a Pytorch model, you will want to save it at a Cloud Storage location, so it can subsequently be uploaded to a `Vertex AI Model` resource.\n",
"The Pytorch package does not have support to save the model to a Cloud Storage location. Instead, you will do the following steps to save to a Cloud Storage location.\n",
"\n",
"1. Save the in-memory model to the local filesystem (e.g., model.pth).\n",
"2. Use gsutil to copy the local copy to the specified Cloud Storage location.\n",
"\n",
"*Note*: You can do hyperparameter tuning with a PyTorch model."
"*Note*: You can do hyperparameter tuning with a Pytorch model."
]
},
{
@@ -1069,9 +1069,9 @@
"id": "docker_write,prediction,pytorch"
},
"source": [
"### Make PyTorch container for prediction\n",
"### Make Pytorch container for prediction\n",
"\n",
"Currently, Vertex AI does not have a predefined container for making predictions with a deployed PyTorch model. No problem, you can assemble your own custom container. Typically, one would base the container on the `Torch Server`. For demonstration purpose, you build a placeholder container (not complete) that includes the latest `Torch Server` image, and push it to the `Container Registry`."
"Currently, Vertex AI does not have a predefined container for making predictions with a deployed Pytorch model. No problem, you can assemble your own custom container. Typically, one would base the container on the `Torch Server`. For demonstration purpose, you build a placeholder container (not complete) that includes the latest `Torch Server` image, and push it to the `Container Registry`."
]
},
{
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Training for R. Please note that this notebook should be ran only in R notebook image (e.g., R4.1)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:r,iris,lcn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the Iris dataset built into the R package. This dataset does not require any feature engineering. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -93,17 +104,6 @@
"- Train a R model using `Vertex AI Trainingh` service with the R-to-Python training package."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:r,iris,lcn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the Iris dataset built into the R package. This dataset does not require any feature engineering. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -216,7 +216,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -243,6 +243,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
@@ -29,7 +29,7 @@
"id": "e3ba05e16cf2"
},
"source": [
"This notebook is an updated version of a notebook contributed by [Fabian Hirschmann](https://github.com/fhirschmann)."
"This is an updated version of a notebook contributed by [Fabian Hirschmann](https://github.com/fhirschmann)."
]
},
{
@@ -38,17 +38,15 @@
"id": "JAPoU8Sm5E6e"
},
"source": [
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex AI Training for R using R Kernel\n",
"\n",
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_vertex_training_r_using_r_kernel.ipynb\">\n",
" <a href=\"https://colab.sandbox.google.com/github/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_vertex_training_r_using_r_kernel.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_vertex_training_r_using_r_kernel.ipynb\">\n",
" <a href=\"https://github.com/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_vertex_training_r_using_r_kernel.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
@@ -65,20 +63,18 @@
{
"cell_type": "markdown",
"metadata": {
"id": "be1799d4f500"
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"This example demonstrates how to train and deploy R models with `Vertex AI` using an R kernel -- such as in `Vertex AI Workbench Notebooks`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"This example demonstrates how to train and deploy R models with `Vertex AI` using an R kernel -- such as in `Vertex AI Workbench Notebooks`.\n",
"\n",
"### Dataset\n",
"\n",
"The dataset used for this tutorial is [California Housing Dataset](https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html). The data contains information from the 1990 California census. The data set is publicly available from Google Cloud Storage at `gs://cloud-samples-data/ai-platform-unified/datasets/tabular/california-housing-tabular-regression.csv`. The dataset is used to train a Random Forest regressor to predict a median housing price, given a longitude and lattitude along with data from the corresponding census block group. A block group is the smallest geographical unit for which the U.S. Census Bureau publishes sample data (a block group typically has a population of 600 to 3,000 people).\n",
"\n",
"\n",
"### Objective\n",
"\n",
"In this tutorial, you learn how to use `Vertex AI`, using an R kernel, for training and deploying an R custom model.\n",
@@ -98,26 +94,9 @@
"- Train the model using `Vertex AI` custom training.\n",
"- Create an `Endpoint` resouce.\n",
"- Deploy the `Model` resource (trained R model) to the `Endpoint` resource.\n",
"- Make an online prediction.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e1266da324d2"
},
"source": [
"### Dataset\n",
"- Make an online prediction.\n",
"\n",
"\n",
"The dataset used for this tutorial is [California Housing Dataset](https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html). The data contains information from the 1990 California census. The data set is publicly available from Cloud Storage at `gs://cloud-samples-data/ai-platform-unified/datasets/tabular/california-housing-tabular-regression.csv`. The dataset is used to train a Random Forest regressor to predict a median housing price, given a longitude and lattitude along with data from the corresponding census block group. A block group is the smallest geographical unit for which the U.S. Census Bureau publishes sample data (a block group typically has a population of 600 to 3,000 people).\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "de76bb18c85b"
},
"source": [
"### Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
@@ -237,10 +216,10 @@
},
"outputs": [],
"source": [
"required_packages < -c(\"reticulate\", \"glue\", \"httr\")\n",
"required_packages <- c(\"reticulate\", \"glue\", \"httr\")\n",
"install.packages(setdiff(required_packages, rownames(installed.packages())))\n",
"\n",
"sh(\"pip3 install --upgrade google-cloud-aiplatform -q\")"
"sh(\"pip install --upgrade google-cloud-aiplatform\")"
]
},
{
@@ -268,7 +247,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com) and the [Artifact Registry API](https://console.cloud.google.com/flows/enableapi?apiid=artifactregistry.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Have the project ID autodetected or enter it below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook."
@@ -293,7 +272,7 @@
},
"outputs": [],
"source": [
"PROJECT_ID < -\"[your-project-id]\" # @param {type:\"string\"}"
"PROJECT_ID <- \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
@@ -461,8 +440,8 @@
},
"outputs": [],
"source": [
"BUCKET_NAME < -\"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI < -paste0(\"gs://\", BUCKET_NAME)"
"BUCKET_NAME <- \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI <- paste0(\"gs://\", BUCKET_NAME)"
]
},
{
@@ -632,11 +611,9 @@
},
"outputs": [],
"source": [
"PRIVATE_REPO < -\"my-docker-repo\"\n",
"PRIVATE_REPO <- \"my-docker-repo\"\n",
"\n",
"sh(\n",
" 'gcloud artifacts repositories create {PRIVATE_REPO} --repository-format=docker --location={REGION} --description=\"Docker repository\"'\n",
")\n",
"sh(\"gcloud artifacts repositories create {PRIVATE_REPO} --repository-format=docker --location={REGION} --description=\\\"Docker repository\\\"\")\n",
"\n",
"sh(\"gcloud artifacts repositories list\")"
]
@@ -682,13 +659,11 @@
},
"outputs": [],
"source": [
"IMAGE_NAME < -\"vertex-r\" # @param {type:\"string\"}\n",
"IMAGE_TAG < -\"latest\" # @param {type:\"string\"}\n",
"IMAGE_URI < -glue(\n",
" \"{REGION}-docker.pkg.dev/{PROJECT_ID}/{PRIVATE_REPO}/{IMAGE_NAME}:{IMAGE_TAG}\"\n",
")\n",
"IMAGE_NAME <- \"vertex-r\" # @param {type:\"string\"}\n",
"IMAGE_TAG <- \"latest\" # @param {type:\"string\"}\n",
"IMAGE_URI <- glue(\"{REGION}-docker.pkg.dev/{PROJECT_ID}/{PRIVATE_REPO}/{IMAGE_NAME}:{IMAGE_TAG}\")\n",
"\n",
"dir.create(\"src\", showWarnings=FALSE)"
"dir.create(\"src\", showWarnings = FALSE)"
]
},
{
@@ -1076,22 +1051,20 @@
},
"outputs": [],
"source": [
"url < -glue(\n",
" \"https://{REGION}-aiplatform.googleapis.com/v1/{endpoint$resource_name}:predict\"\n",
")\n",
"access_token < -sh(\"gcloud auth print-access-token\", intern=TRUE)\n",
"url <- glue(\"https://{REGION}-aiplatform.googleapis.com/v1/{endpoint$resource_name}:predict\")\n",
"access_token <- sh(\"gcloud auth print-access-token\", intern = TRUE)\n",
"\n",
"sh(\n",
" \"curl\",\n",
" c(\n",
" \"--tr-encoding\",\n",
" \"-s\",\n",
" \"-X POST\",\n",
" glue(\"-H 'Authorization: Bearer {access_token}'\"),\n",
" \"-H 'Content-Type: application/jsoin'\",\n",
" url,\n",
" glue(\"-d {json_instances}\"),\n",
" ),\n",
" c(\"--tr-encoding\",\n",
" \"-s\",\n",
" \"-X POST\",\n",
" glue(\"-H 'Authorization: Bearer {access_token}'\"),\n",
" \"-H 'Content-Type: application/jsoin'\",\n",
" url,\n",
" glue(\"-d {json_instances}\")\n",
" ),\n",
" \n",
")"
]
},
@@ -29,7 +29,7 @@
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex AI Training for Scikit-Learn\n",
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Vertex Training for Scikit-Learn\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
@@ -44,7 +44,7 @@
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb\">\n",
" <a href=\"https://console.cloud.google.com/ai/platform/notebooks/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/stage2/get_started_vertex_training_sklearn.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
"Open in Vertex AI Workbench\n",
" </a>\n",
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Training for scikit-Learn."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,newsaggr,tcn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [News Aggregation](https://archive.ics.uci.edu/ml/datasets/News+Aggregator) from [ICS Machine Learning Datasets](https://archive.ics.uci.edu/ml/datasets.php). The trained model predicts the news category of the news article."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -88,17 +99,6 @@
"- Create a `Vertex AI Model` resource."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,newsaggr,tcn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [News Aggregation](https://archive.ics.uci.edu/ml/datasets/News+Aggregator) from [ICS Machine Learning Datasets](https://archive.ics.uci.edu/ml/datasets.php). The trained model predicts the news category of the news article."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -127,7 +127,7 @@
"source": [
"### Set up your local development environment\n",
"\n",
"**If you are using Colab or Vertex AI Workbench Notebooks**, your environment already meets\n",
"**If you are using Colab or Google Cloud Notebooks**, your environment already meets\n",
"all the requirements to run this notebook. You can skip this step.\n",
"\n",
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
@@ -167,7 +167,7 @@
"id": "install_mlops"
},
"source": [
"## Installation\n",
"### Install additional packages\n",
"\n",
"Install the following packages for executing this notebook."
]
@@ -243,7 +243,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -66,6 +66,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Training for XGBoost."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:iris,lcn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Iris dataset](https://www.tensorflow.org/datasets/catalog/iris) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -86,26 +97,8 @@
"- Training using a Python package.\n",
"- Report accuracy when hyperparameter tuning.\n",
"- Save the model artifacts to Cloud Storage using GCSFuse.\n",
"- Create a `Vertex AI Model` resource."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:iris,lcn"
},
"source": [
"### Dataset\n",
"- Create a `Vertex AI Model` resource.\n",
"\n",
"The dataset used for this tutorial is the [Iris dataset](https://www.tensorflow.org/datasets/catalog/iris) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4fc0ad661ebb"
},
"source": [
"### Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
@@ -156,36 +149,6 @@
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oQhwq1iozAxh"
},
"source": [
"### Restart the kernel\n",
"\n",
"After you install the additional packages, you need to restart the notebook kernel so it can find the packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zo3YFZXLzCRJ"
},
"outputs": [],
"source": [
"# Automatically restart kernel after installs\n",
"import os\n",
"\n",
"if not os.getenv(\"IS_TESTING\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -204,7 +167,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -297,32 +260,25 @@
{
"cell_type": "markdown",
"metadata": {
"id": "06571eb4063b"
"id": "timestamp"
},
"source": [
"#### UUID\n",
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4e166d927e36"
"id": "JYtXOocrox9Q"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"from datetime import datetime\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
@@ -369,11 +325,12 @@
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
@@ -408,8 +365,7 @@
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}\n",
"BUCKET_URI = f\"gs://{BUCKET_NAME}\""
"BUCKET_URI = \"gs://[your-bucket-name]\" # @param {type:\"string\"}"
]
},
{
@@ -420,9 +376,8 @@
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_URI = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
]
},
{
@@ -757,7 +712,6 @@
"import hypertune\n",
"import argparse\n",
"import logging\n",
"import numpy as np\n",
"\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import accuracy_score\n",
@@ -799,23 +753,16 @@
"def train_model(dtrain):\n",
" logging.info(\"Start training ...\")\n",
" # Train XGBoost model\n",
" params = {\n",
" 'objective': 'multi:softprob',\n",
" 'num_class': 3\n",
" }\n",
" model = xgb.train(params, dtrain, num_boost_round=args.boost_rounds)\n",
" model = xgb.train({}, dtrain, num_boost_round=args.boost_rounds)\n",
" logging.info(\"Training completed\")\n",
" return model\n",
"\n",
"def evaluate_model(model, test_data, test_labels):\n",
" dtest = xgb.DMatrix(test_data)\n",
" pred = model.predict(dtest)\n",
" predictions = [np.around(value) for value in pred]\n",
" predictions = [round(value) for value in pred]\n",
" # evaluate predictions\n",
" try:\n",
" accuracy = accuracy_score(test_labels, predictions)\n",
" except:\n",
" accuracy = 0.0\n",
" accuracy = accuracy_score(test_labels, predictions)\n",
" logging.info(f\"Evaluation completed with model accuracy: {accuracy}\")\n",
"\n",
" # report metric for hyperparameter tuning\n",
@@ -909,7 +856,7 @@
},
"outputs": [],
"source": [
"DISPLAY_NAME = \"iris_\" + UUID\n",
"DISPLAY_NAME = \"iris_\" + TIMESTAMP\n",
"\n",
"job = aip.CustomPythonPackageTrainingJob(\n",
" display_name=DISPLAY_NAME,\n",
@@ -948,7 +895,7 @@
},
"outputs": [],
"source": [
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, UUID)\n",
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, TIMESTAMP)\n",
"DATASET_DIR = \"gs://cloud-samples-data/ai-platform/iris\"\n",
"\n",
"ROUNDS = 20\n",
@@ -999,7 +946,7 @@
"source": [
"if TRAIN_GPU:\n",
" model = job.run(\n",
" model_display_name=\"iris_\" + UUID,\n",
" model_display_name=\"iris_\" + TIMESTAMP,\n",
" args=CMDARGS,\n",
" replica_count=1,\n",
" machine_type=TRAIN_COMPUTE,\n",
@@ -1010,7 +957,7 @@
" )\n",
"else:\n",
" model = job.run(\n",
" model_display_name=\"iris_\" + UUID,\n",
" model_display_name=\"iris_\" + TIMESTAMP,\n",
" args=CMDARGS,\n",
" replica_count=1,\n",
" machine_type=TRAIN_COMPUTE,\n",
@@ -1111,7 +1058,7 @@
},
"outputs": [],
"source": [
"delete_bucket = True\n",
"delete_bucket = False\n",
"\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil rm -r $BUCKET_URI"
@@ -62,7 +62,18 @@
"## Overview\n",
"\n",
"\n",
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex AI Vizier."
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with Vertex Vizier."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,boston,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Boston Housing Prices dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). The version of the dataset you will use in this tutorial is built into TensorFlow. The trained model predicts the median price of a house in units of 1K USD."
]
},
{
@@ -84,8 +95,7 @@
"The steps performed include:\n",
"\n",
"- Hyperparameter tuning with Random algorithm.\n",
"- Hyperparameter tuning with Vizier (Bayesian) algorithm.\n",
"- Suggesting trials and updating results for Vizier study"
"- Hyperparameter tuning with Vizier (Bayesian) algorithm."
]
},
{
@@ -124,38 +134,6 @@
"- multiple of objectives"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:custom,boston,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Boston Housing Prices dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html). The version of the dataset in this tutorial is built into TensorFlow. The trained model predicts the median price of a house in units of 1K USD."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c480fc50ec3c"
},
"source": [
"### Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\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": {
@@ -188,8 +166,7 @@
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade $USER_FLAG -q google-cloud-aiplatform \\\n",
" google-vizier==0.0.4"
"! pip3 install --upgrade google-cloud-aiplatform[tensorboard] $USER_FLAG"
]
},
{
@@ -239,7 +216,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -331,32 +308,25 @@
{
"cell_type": "markdown",
"metadata": {
"id": "06571eb4063b"
"id": "timestamp"
},
"source": [
"#### UUID\n",
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a uuid for each instance session, and append it onto the name of resources you create in this tutorial."
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4e166d927e36"
"id": "timestamp"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"from datetime import datetime\n",
"\n",
"\n",
"# Generate a uuid of a specifed length(default=8)\n",
"def generate_uuid(length: int = 8) -> str:\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=length))\n",
"\n",
"\n",
"UUID = generate_uuid()"
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
@@ -367,7 +337,7 @@
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. \n",
"**If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step.\n",
"\n",
"**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
"\n",
@@ -455,7 +425,7 @@
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_URI = \"gs://\" + PROJECT_ID + \"aip-\" + UUID"
" BUCKET_URI = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
]
},
{
@@ -518,8 +488,7 @@
},
"outputs": [],
"source": [
"import google.cloud.aiplatform as aip\n",
"from google.cloud.aiplatform.vizier import Study, pyvizier"
"import google.cloud.aiplatform as aip"
]
},
{
@@ -544,6 +513,35 @@
"aip.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aip_constants"
},
"source": [
"#### Vertex AI constants\n",
"\n",
"Setup up the following constants for Vertex AI:\n",
"\n",
"- `API_ENDPOINT`: The Vertex AI API service endpoint for `Dataset`, `Model`, `Job`, `Pipeline` and `Endpoint` services.\n",
"- `PARENT`: The Vertex AI location root path for `Dataset`, `Model`, `Job`, `Pipeline` and `Endpoint` resources."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aip_constants"
},
"outputs": [],
"source": [
"# API service endpoint\n",
"API_ENDPOINT = \"{}-aiplatform.googleapis.com\".format(REGION)\n",
"\n",
"# Vertex location root path for your dataset, model and endpoint resources\n",
"PARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -607,7 +605,7 @@
"if os.getenv(\"IS_TESTING_TF\"):\n",
" TF = os.getenv(\"IS_TESTING_TF\")\n",
"else:\n",
" TF = \"2.5\".replace(\".\", \"-\")\n",
" TF = \"2.1\".replace(\".\", \"-\")\n",
"\n",
"if TF[0] == \"2\":\n",
" if TRAIN_GPU:\n",
@@ -1012,7 +1010,7 @@
},
"outputs": [],
"source": [
"JOB_NAME = \"custom_job_\" + UUID\n",
"JOB_NAME = \"custom_job_\" + TIMESTAMP\n",
"MODEL_DIR = \"{}/{}\".format(BUCKET_URI, JOB_NAME)\n",
"\n",
"if not TRAIN_NGPU or TRAIN_NGPU < 2:\n",
@@ -1075,7 +1073,9 @@
},
"outputs": [],
"source": [
"job = aip.CustomJob(display_name=\"boston_\" + UUID, worker_pool_specs=worker_pool_spec)"
"job = aip.CustomJob(\n",
" display_name=\"boston_\" + TIMESTAMP, worker_pool_specs=worker_pool_spec\n",
")"
]
},
{
@@ -1107,7 +1107,7 @@
"from google.cloud.aiplatform import hyperparameter_tuning as hpt\n",
"\n",
"hpt_job = aip.HyperparameterTuningJob(\n",
" display_name=\"boston_\" + UUID,\n",
" display_name=\"boston_\" + TIMESTAMP,\n",
" custom_job=job,\n",
" metric_spec={\n",
" \"val_loss\": \"minimize\",\n",
@@ -1275,8 +1275,7 @@
"Use the class `CustomJob` to create a custom job, such as for hyperparameter tuning, with the following parameters:\n",
"\n",
"- `display_name`: A human readable name for the custom job.\n",
"- `worker_pool_specs`: The specification for the corresponding VM instances.\n",
"- `base_output_dir`: The Cloud Storage location for storing the model artifacts."
"- `worker_pool_specs`: The specification for the corresponding VM instances."
]
},
{
@@ -1288,9 +1287,7 @@
"outputs": [],
"source": [
"job = aip.CustomJob(\n",
" display_name=\"boston_\" + UUID,\n",
" worker_pool_specs=worker_pool_spec,\n",
" base_output_dir=MODEL_DIR,\n",
" display_name=\"boston_\" + TIMESTAMP, worker_pool_specs=worker_pool_spec\n",
")"
]
},
@@ -1323,7 +1320,7 @@
"from google.cloud.aiplatform import hyperparameter_tuning as hpt\n",
"\n",
"hpt_job = aip.HyperparameterTuningJob(\n",
" display_name=\"boston_\" + UUID,\n",
" display_name=\"boston_\" + TIMESTAMP,\n",
" custom_job=job,\n",
" metric_spec={\n",
" \"val_loss\": \"minimize\",\n",
@@ -1423,32 +1420,6 @@
"print(best)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "get_best_model"
},
"source": [
"### Get the Best Model\n",
"\n",
"If you used the method of having the service tell the tuning script where to save the model artifacts (`DIRECT = False`), then the model artifacts for the best model are saved at:\n",
"\n",
" MODEL_DIR/<best_trial_id>/model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "get_best_model"
},
"outputs": [],
"source": [
"BEST_MODEL_DIR = MODEL_DIR + \"/\" + best[0] + \"/model\"\n",
"\n",
"! gsutil ls {BEST_MODEL_DIR}"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -1492,25 +1463,22 @@
"id": "vizier_client"
},
"source": [
"### Specify the algorithm used to suggest trial parameters\n",
"### Create Vizier client\n",
"\n",
"First, you create a `StudyConfig`, and specify the algorithm to suggest the next trial.\n",
"\n",
" GRID_SEARCH: grid search\n",
" RANDOM_SEARCH: random search\n",
" ALGORIGTHM_UNSPECIFIED: Vizier bayesian algorithm"
"Create a client side connection to the Vertex AI Vizier service."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d7dd26490358"
"id": "vizier_client"
},
"outputs": [],
"source": [
"problem = pyvizier.StudyConfig()\n",
"problem.algorithm = pyvizier.Algorithm.RANDOM_SEARCH"
"vizier_client = aip.gapic.VizierServiceClient(\n",
" client_options=dict(api_endpoint=API_ENDPOINT)\n",
")"
]
},
{
@@ -1525,15 +1493,7 @@
"\n",
"In the following example, the goal is to maximize y = x^2 with x in the range of \\[-10. 10\\]. This example has only one parameter and uses an easily calculated function to help demonstrate how to use Vizier.\n",
"\n",
"First, you specify the metrics to minimize or maximize in the study as a list to the property `metric_information`. Then you specify the parameters to the study using the `add_XXX_params()` method for the corresponding data type:\n",
"\n",
" - add_bool_param\n",
" - add_categorical_param\n",
" - add_discrete_param\n",
" - add_float_param\n",
" - add_int_param\n",
"\n",
"You create the study using the `create_or_load()` method."
"First, you will create the study using the `create_study()` method."
]
},
{
@@ -1544,19 +1504,28 @@
},
"outputs": [],
"source": [
"STUDY_DISPLAY_NAME = \"xpow2\" + UUID\n",
"STUDY_DISPLAY_NAME = \"xpow2\" + TIMESTAMP\n",
"\n",
"problem.metric_information.append(\n",
" pyvizier.MetricInformation(name=\"y\", goal=pyvizier.ObjectiveMetricGoal.MAXIMIZE)\n",
")\n",
"param_x = {\n",
" \"parameter_id\": \"x\",\n",
" \"double_value_spec\": {\"min_value\": -10.0, \"max_value\": 10.0},\n",
"}\n",
"\n",
"params = problem.search_space.select_root()\n",
"params.add_float_param(\"x\", -10.0, 10.0, scale_type=pyvizier.ScaleType.LINEAR)\n",
"metric_y = {\"metric_id\": \"y\", \"goal\": \"MAXIMIZE\"}\n",
"\n",
"study = Study.create_or_load(display_name=STUDY_DISPLAY_NAME, problem=problem)\n",
"study = {\n",
" \"display_name\": STUDY_DISPLAY_NAME,\n",
" \"study_spec\": {\n",
" \"algorithm\": \"RANDOM_SEARCH\",\n",
" \"parameters\": [param_x],\n",
" \"metrics\": [metric_y],\n",
" },\n",
"}\n",
"\n",
"study = vizier_client.create_study(parent=PARENT, study=study)\n",
"STUDY_NAME = study.name\n",
"print(\"STUDY_NAME: {}\".format(STUDY_NAME))"
"\n",
"print(STUDY_NAME)"
]
},
{
@@ -1567,7 +1536,9 @@
"source": [
"### Get Vizier study\n",
"\n",
"You can get a study using the method `list()`."
"You can get a study using the method `get_study()`, with the following key/value pairs:\n",
"\n",
"- `name`: The name of the study."
]
},
{
@@ -1578,8 +1549,9 @@
},
"outputs": [],
"source": [
"studies = Study.list()\n",
"print(studies[0].gca_resource)"
"study = vizier_client.get_study({\"name\": STUDY_NAME})\n",
"\n",
"print(study)"
]
},
{
@@ -1590,9 +1562,11 @@
"source": [
"### Get suggested trial\n",
"\n",
"Next, query the Vizier service for a suggested trial(s) using the method `suggest()`, with the following key/value pairs:\n",
"Next, query the Vizier service for a suggested trial(s) using the method `suggest_trials`, with the following key/value pairs:\n",
"\n",
"- `count`: The number of trials to suggest.\n",
"- `parent`: The name of the study.\n",
"- `suggestion_count`: The number of trials to suggest.\n",
"- `client_id`: blah\n",
"\n",
"This call is a long running operation. The method `result()` from the response object will wait until the call has completed."
]
@@ -1601,13 +1575,18 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "11ff2c4562cb"
"id": "vizier_suggest_trial"
},
"outputs": [],
"source": [
"SUGGEST_COUNT = 1\n",
"CLIENT_ID = \"1001\"\n",
"\n",
"trials = study.suggest(count=SUGGEST_COUNT)\n",
"response = vizier_client.suggest_trials(\n",
" {\"parent\": STUDY_NAME, \"suggestion_count\": SUGGEST_COUNT, \"client_id\": CLIENT_ID}\n",
")\n",
"\n",
"trials = response.result().trials\n",
"\n",
"print(trials)\n",
"\n",
@@ -1650,10 +1629,12 @@
"source": [
"RESULT = 0.01\n",
"\n",
"measurement = pyvizier.Measurement()\n",
"measurement.metrics[\"y\"] = RESULT\n",
"\n",
"trials[0].add_measurement(measurement)"
"vizier_client.add_trial_measurement(\n",
" {\n",
" \"trial_name\": TRIAL_ID,\n",
" \"measurement\": {\"metrics\": [{\"metric_id\": \"y\", \"value\": RESULT}]},\n",
" }\n",
")"
]
},
{
@@ -1664,7 +1645,7 @@
"source": [
"### Delete the Vizier study\n",
"\n",
"The method 'delete()' will delete the study."
"The method 'delete_study()' will delete the study."
]
},
{
@@ -1675,7 +1656,7 @@
},
"outputs": [],
"source": [
"study.delete()"
"vizier_client.delete_study({\"name\": STUDY_NAME})"
]
},
{
@@ -64,6 +64,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with AutoML training with a customer managed encyrption key CMEK."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use in this tutorial is stored in a public #(GCS) bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -86,17 +97,6 @@
"- Train an AutoML model with CMEK encryption."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset in this tutorial is stored in a public #(GCS) bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -207,7 +207,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -73,7 +73,7 @@
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use Python and Cloud logging when training with `Vertex AI`.\n",
"In this tutorial, you learn how to use Python and Cloud logging awhen training with `Vertex AI`.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
@@ -105,26 +105,8 @@
"\n",
"#### Experiments\n",
"\n",
"Use Vertex AI Experiments in conjunction with logging when performing experiments to compare results for different experiment configurations."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5341f31587c8"
},
"source": [
"### Dataset\n",
"Use Vertex AI Experiments in conjunction with logging when performing experiments to compare results for different experiment configurations.\n",
"\n",
"This tutorial does not use a dataset. References to example datasets is for demonstration purposes."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "41512a89f379"
},
"source": [
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -203,8 +185,6 @@
"id": "project_id"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -220,15 +200,9 @@
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5aee4379e8e5"
},
"source": [
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n",
"\n",
"\n",
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
@@ -39,7 +39,7 @@
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_with_tabnet.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samplestree/main/notebooks/community/ml_ops/stage2/get_started_with_tabnet.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
@@ -67,18 +67,15 @@
"\n",
"TabNet uses a machine learning technique called sequential attention to select which model features to reason from at each step in the model. This mechanism makes it possible to explain how the model arrives at its predictions and helps it learn more accurate models. TabNet not only outperforms other neural networks and decision trees but also provides interpretable feature attributions. \n",
"\n",
"Research paper: [TabNet: Attentive Interpretable Tabular Learning](https://arxiv.org/pdf/1908.07442.pdf)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c5040751873a"
},
"source": [
"Research paper: [TabNet: Attentive Interpretable Tabular Learning](https://arxiv.org/pdf/1908.07442.pdf)\n",
"\n",
"### Dataset\n",
"\n",
"This tutorial uses the `petfinder` in the public Cloud Storage bucket `gs://cloud-samples-data/ai-platform-unified/datasets/tabular/`, which was generated from the [PetFinder.my Adoption Prediction](https://www.kaggle.com/c/petfinder-adoption-prediction). This dataset predicts how quickly an animal will be adopted.\n",
"\n",
"### Objective\n",
"\n",
"In this notebook, you learn how to run `Vertex AI TabNet` built algorithm for training custom tabular models.\n",
"In this notebook, you will learn how to run `Vertex AI TabNet` built algorithm for training custom tabular models.\n",
"\n",
"This tutorial uses the following Google Cloud ML services and resources:\n",
"\n",
@@ -96,28 +93,11 @@
"- Deploy the `Vertex AI Model` resource to a `Vertex AI Endpoint` resource.\n",
"- Make a prediction with the deployed model.\n",
"- Hyperparameter tuning the `Vertex AI TabNet` model.\n",
"- Train the model using `Vertex AI Training` using BigQuery table."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ac8c8586ab03"
},
"source": [
"### Dataset\n",
"- Train the model using `Vertex AI Training` using BigQuery table.\n",
"\n",
"This tutorial uses the `petfinder` in the public Cloud Storage bucket `gs://cloud-samples-data/ai-platform-unified/datasets/tabular/`, which was generated from the [PetFinder.my Adoption Prediction](https://www.kaggle.com/c/petfinder-adoption-prediction). This dataset predicts how quickly an animal is adopted.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4fc0ad661ebb"
},
"source": [
"### Costs \n",
"\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* Vertex AI\n",
@@ -163,8 +143,8 @@
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install {USER_FLAG} --upgrade tensorflow -q\n",
"! pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform tensorboard-plugin-profile -q\n",
"! pip3 install {USER_FLAG} --upgrade tensorflow\n",
"! pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform tensorboard-plugin-profile\n",
"! gcloud components update --quiet"
]
},
@@ -220,7 +200,7 @@
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation: get started with prebuilt TensorFlow Hub (TFHub) models."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [CIFAR10 dataset](https://www.tensorflow.org/datasets/catalog/cifar10) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use is built into TensorFlow. The trained model predicts which type of class an image is from ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -92,17 +103,6 @@
" - Save model artifacts and upload as Vertex AI Model resource."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [CIFAR10 dataset](https://www.tensorflow.org/datasets/catalog/cifar10) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset is built into TensorFlow. The trained model predicts which type of class an image is from ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -157,8 +157,27 @@
" USER_FLAG = \"\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q\n",
"! pip3 install tensorflow-datasets $USER_FLAG -q\n",
"! pip3 install -U google-cloud-storage $USER_FLAG -q"
"! pip3 install tensorflow-datasets $USER_FLAG -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_storage"
},
"source": [
"Install the latest GA version of *google-cloud-storage* library as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_storage"
},
"outputs": [],
"source": [
"! pip3 install -U google-cloud-storage $USER_FLAG"
]
},
{
@@ -212,7 +231,7 @@
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -29,7 +29,7 @@
"id": "3f8c2f702ccd"
},
"source": [
"This notebook is an updated version of a notebook contributed by [Mohammad Al-Ansari](https://github.com/Mansari). Special thanks to [Andrew Ferlitsch](https://github.com/andrewferlitsch) for his reviews and edits.\n",
"This is an updated version of a notebook contributed by [Mohammad Al-Ansari](https://github.com/Mansari). Special thanks to [Andrew Ferlitsch](https://github.com/andrewferlitsch) for his reviews and edits.\n",
"\n",
"This is an extension of the [Vertex AI SDK for Python: AutoML training text entity extraction model for online prediction notebook](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/automl/sdk_automl_text_entity_extraction_online.ipynb) originally co-authored by [Andrew Ferlitsch](https://github.com/andrewferlitsch) and [\n",
"Karl Weinmeister](https://github.com/kweinmeister). This version add the use of `Vision API` and `BigQuery` to preprocess a `Vertex AI AutoML` dataset for text entity extraction model training."
@@ -76,6 +76,21 @@
"This tutorial demonstrates how to use `BigQuery`, `Vision AI`, and `Vertex AI SDK` for Python to train a text entity extraction model based on existing training data."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:biomedical,ten"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Patent PDF Samples with Extracted Structured Data](https://console.cloud.google.com/marketplace/product/global-patents/labeled-patents) from Google Public Data Sets. \n",
"\n",
"This dataset includes data extracted from over 300 patent documents issued in the US and EU. The dataset includes links to Google Cloud Storage blobs for the first page of each patent, in addition to a number of extracted entities. \n",
"\n",
"The data is published as a [public dataset](https://cloud.google.com/bigquery/public-data) on `BigQuery`."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -84,7 +99,7 @@
"source": [
"### Objective\n",
"\n",
"In this tutorial, you create an `AutoML` text entity extraction model pre-existing extracted data by generating a custom import file. You deploy this mode for online prediction from a Python script using the `BigQuery`, `Vision AI`, Cloud Storage and `Vertex AI SDK` for Python. You can alternatively create and deploy models using the `gcloud` command-line tool or online using the Cloud Console.\n",
"In this tutorial, you create an `AutoML` text entity extraction model pre-existing extracted data by generating a custom import file. You will deploy this mode for online prediction from a Python script using the `BigQuery`, `Vision AI`, Cloud Storage and `Vertex AI SDK` for Python. You can alternatively create and deploy models using the `gcloud` command-line tool or online using the Cloud Console.\n",
"\n",
"Using existing training data that have been previously annotated can be very useful in training a model, as it allows you to use a larger data set with minimal resources.\n",
"\n",
@@ -106,21 +121,6 @@
"- Undeploy the `Model`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:biomedical,ten"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Patent PDF Samples with Extracted Structured Data](https://console.cloud.google.com/marketplace/product/global-patents/labeled-patents) from Google Public Data Sets. \n",
"\n",
"This dataset includes data extracted from over 300 patent documents issued in the US and EU. The dataset includes links to Cloud Storage blobs for the first page of each patent, in addition to a number of extracted entities. \n",
"\n",
"The data is published as a [public dataset](https://cloud.google.com/bigquery/public-data) on `BigQuery`."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -151,7 +151,7 @@
"source": [
"### Set up your local development environment\n",
"\n",
"If you are using Colab or Vertex AI Workbench Notebooks, your environment already meets all the requirements to run this notebook. \n",
"If you are using Colab or Google Cloud Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step.\n",
"\n",
"Otherwise, make sure your environment meets this notebook's requirements. You need the following:\n",
"\n",
@@ -265,7 +265,7 @@
"\n",
"3. [Enable the following APIs: BigQuery APIs, Vision API, Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=bigquery.googleapis.com,vision.googleapis.com,aiplatform.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -273,17 +273,6 @@
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WReHDGG5g0XY"
},
"source": [
"#### Set your project ID\n",
"\n",
"**If you don't know your project ID**, you may be able to get your project ID using `gcloud`."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -39,15 +39,18 @@
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/mlops_experimentation.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage2/mlops_experimentation.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
" </td>\n",
"</table>\n",
"<br/><br/><br/>\n",
"\n",
"*Note: This notebook is not supported for execution in Colab*"
"<br/><br/><br/>"
]
},
{
@@ -62,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 2 : experimentation."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:bq,chicago,lbn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Chicago Taxi](https://www.kaggle.com/chicago/chicago-taxi-trips-bq). The version of the dataset you will use in this tutorial is stored in a public BigQuery table. The trained model predicts whether someone would leave a tip for a taxi fare."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -146,39 +160,6 @@
" - If greater then baseline, then upload model as the new baseline and save evaluation results with the model."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:bq,chicago,lbn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Chicago Taxi](https://www.kaggle.com/chicago/chicago-taxi-trips-bq). The version of the dataset in this tutorial is stored in a public BigQuery table. The trained model predicts whether someone leaves a tip for a taxi fare."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "costs"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"* BigQuery\n",
"* Vision API\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI\n",
"pricing](https://cloud.google.com/vertex-ai/pricing), [Vision API pricing](https://cloud.google.com/vision/pricing), [BigQuery pricing](https://cloud.google.com/bigquery/pricing), [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": {
@@ -213,18 +194,20 @@
"\n",
"ONCE_ONLY = False\n",
"if ONCE_ONLY:\n",
" ! pip3 install -U {USER_FLAG} -q tensorflow==2.5 \\\n",
" tensorflow-data-validation==1.2 \\\n",
" tensorflow-transform==1.2 \\\n",
" tensorflow-io==0.18 \n",
" \n",
" ! pip3 install --upgrade {USER_FLAG} -q google-cloud-aiplatform[tensorboard] \\\n",
" google-cloud-pipeline-components \\\n",
" google-cloud-bigquery \\\n",
" google-cloud-logging \\\n",
" apache-beam[gcp] \\\n",
" pyarrow \\\n",
" cloudml-hypertune"
" ! pip3 install -U tensorflow==2.5 $USER_FLAG\n",
" ! pip3 install -U tensorflow-data-validation==1.2 $USER_FLAG\n",
" ! pip3 install -U tensorflow-transform==1.2 $USER_FLAG\n",
" ! pip3 install -U tensorflow-io==0.18 $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-aiplatform[tensorboard] $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-pipeline-components $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-bigquery $USER_FLAG\n",
" ! pip3 install --upgrade google-cloud-logging $USER_FLAG\n",
" ! pip3 install --upgrade apache-beam[gcp] $USER_FLAG\n",
" ! pip3 install --upgrade pyarrow $USER_FLAG\n",
" ! pip3 install --upgrade cloudml-hypertune $USER_FLAG\n",
" ! pip3 install --upgrade kfp $USER_FLAG\n",
" ! pip3 install --upgrade torchvision $USER_FLAG\n",
" ! pip3 install --upgrade rpy2 $USER_FLAG"
]
},
{
@@ -274,7 +257,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). \n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -439,11 +422,12 @@
"import sys\n",
"\n",
"# If on Vertex AI Workbench, then don't execute this code\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"IS_COLAB = False\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\") and not os.getenv(\n",
" \"DL_ANACONDA_HOME\"\n",
"):\n",
" if \"google.colab\" in sys.modules:\n",
" IS_COLAB = True\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
+119 -128
View File
@@ -33,44 +33,9 @@ The third stage in MLOps is formalization to develop an automated pipeline proce
### Get Started
[Get Started with Kubeflow pipelines](get_started_with_kubeflow_pipelines.ipynb)
[Get started with Vertex AI Model Registry](community/ml_ops/stage3/get_started_with_model_registry.ipynb)
In this tutorial, you learn how to use `Vertex AI Model Registry` to create and register multiple versions of a model.
The steps performed include:
- Create and register a first version of a model to `Vertex AI Model Registry`.
- Create and register a second version of a model to `Vertex AI Model Registry`.
- Updating the model version which is the default (blessed).
- Deleting a model version.
- Retraining the next model version.
[Get started with Dataflow pipeline components](community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.ipynb)
In this tutorial, you learn how to use prebuilt `Google Cloud Pipeline Components` for `Dataflow`.
The steps performed include:
- Build an Apache Beam data pipeline.
- Encapsulate the Apache Beam data pipeline with a Dataflow component in a Vertex AI pipeline.
- Execute a Vertex AI pipeline.
[Get started with Apache Airflow and Vertex AI Pipelines](community/ml_ops/stage3/get_started_with_airflow_and_vertex_pipelines.ipynb)
In this tutorial, you learn how to use Apache Airflow with `Vertex AI Pipelines`.
The steps performed include:
- Create Cloud Composer environment.
- Upload Airflow DAG to Composer environment that performs data processing -- i.e., creates a BigQuery table from a CSV file.
- Create a `Vertex AI Pipeline` that triggers the Airflow DAG.
- Execute the `Vertex AI Pipeline`.
[Get started with Kubeflow Pipelines](community/ml_ops/stage3/get_started_with_kubeflow_pipelines.ipynb)
In this tutorial, you learn how to use `Kubeflow Pipelines`(KFP).
```
The steps performed include:
- Building KFP lightweight Python function components.
@@ -79,11 +44,54 @@ The steps performed include:
- Loading component and pipeline definitions from a source code repository.
- Building sequential, parallel, multiple output components.
- Building control flow into pipelines.
```
[Get started with Vertex AI custom training pipeline components](community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb)
[Get Started with BQ and TFDV components](get_started_with_bq_tfdv_pipeline_components.ipynb)
In this tutorial, you learn how to use prebuilt `Google Cloud Pipeline Components` for `Vertex AI Training`.
```
The steps performed include:
- Build and execute a pipeline component for creating a Vertex AI Tabular Dataset from a BigQuery table.
- Build and execute a pipeline component for generating TFDV statistics and schema from a Vertex AI Tabular Dataset.
- Execute a Vertex AI pipeline.
```
[Get Started with Dataflow components](get_started_with_dataflow_pipeline_components.ipynb)
```
The steps performed include:
- Build an Apache Beam data pipeline.
- Encapsulate the Apache Beam data pipeline with a Dataflow component in a Vertex AI pipeline.
- Execute a Vertex AI pipeline.
```
[Get Started with Dataproc components](get_started_with_dataproc_pipeline_components.ipynb)
```
The steps performed include:
- DataprocPySparkBatchOp for PySpark batch workloads.
- DataprocSparkBatchOp for Spark batch workloads.
- DataprocSparkSqlBatchOp for running Spark SQL batch workloads.
- DataprocSparkRBatchOp for running SparkR batch workloads.
```
[Get Started with Vertex AI AutoML components](get_started_with_automl_pipeline_components.ipynb)
```
The steps performed include:
- Construct a pipeline for:
- Training a Vertex AI AutoML trained model.
- Test the serving binary with a batch prediction job.
- Deploying a Vertex AI AutoML trained model.
- Execute a Vertex AI pipeline.
```
[Get Started with Vertex AI Custom Training components](get_started_with_custom_training_pipeline_components.ipynb)
```
The steps performed include:
- Construct a pipeline for:
@@ -91,30 +99,11 @@ The steps performed include:
- Test the serving binary with a batch prediction job.
- Deploying a Vertex AI custom trained model.
- Execute a Vertex AI pipeline.
- Construct a pipeline for:
- Construct a custom training component.
- Convert custom training component to CustomTrainingJobOp.
- Training a Vertex AI custom trained model using the converted component.
- Deploying a Vertex AI custom trained model.
- Execute a Vertex AI pipeline.
```
[Get started with Dataproc Serverless pipeline components](community/ml_ops/stage3/get_started_with_dataproc_serverless_pipeline_components.ipynb)
In this tutorial, you learn how to use prebuilt `Google Cloud Pipeline Components` for `Dataproc Serverless` service.
The steps performed include:
- `DataprocPySparkBatchOp` for running PySpark batch workloads.
- `DataprocSparkBatchOp` for running Spark batch workloads.
- `DataprocSparkSqlBatchOp` for running Spark SQL batch workloads.
- `DataprocSparkRBatchOp` for running SparkR batch workloads.
[Get started with Vertex AI Hyperparameter Tuning pipeline components](community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb)
In this tutorial, you learn how to use prebuilt `Google Cloud Pipeline Components` for `Vertex AI Hyperparameter Tuning`.
[Get Started with Vertex AI Hyperparameter Tuning components](get_started_with_hpt_pipeline_components.ipynb)
```
The steps performed include:
- Construct a pipeline for:
@@ -124,36 +113,11 @@ The steps performed include:
- Get the location of the model artifacts for the best tuned model.
- Upload the model artifacts to a `Vertex AI Model` resource.
- Execute a Vertex AI pipeline.
```
[Get started with machine management for Vertex AI Pipelines](community/ml_ops/stage3/get_started_with_machine_management.ipynb)
In this tutorial, you convert a self-contained custom training component into a `Vertex AI CustomJob`, whereby:
- The training job and artifacts are trackable.
- Set machine resources, such as machine-type, cpu/gpu, memory, disk, etc.
The steps performed in this tutorial include:
- Create a custom component with a self-contained training job.
- Execute pipeline using component-level settings for machine resources
- Convert the self-contained training component into a `Vertex AI CustomJob`.
- Execute pipeline using customjob-level settings for machine resources
[Get started with TFX pipelines](community/ml_ops/stage3/get_started_with_tfx_pipeline.ipynb)
In this tutorial, you learn how to use TensorFlow Extended (TFX) with `Vertex AI Pipelines`.
The steps performed include:
- Create a TFX e2e pipeline.
- Execute the pipeline locally.
- Execute the pipeline on Google Cloud using `Vertex AI Training`
- Execute the pipeline using `Vertex AI Pipelines`.
[Get started with BigQuery ML pipeline components](community/ml_ops/stage3/get_started_with_bqml_pipeline_components.ipynb)
In this tutorial, you learn how to use prebuilt `Google Cloud Pipeline Components` for `BigQuery ML`.
[Get Started with BQML components](get_started_with_bqml_pipeline_components.ipynb)
```
The steps performed include:
- Construct a pipeline for:
@@ -164,13 +128,75 @@ The steps performed include:
- Deploy the Vertex AI model.
- Execute a Vertex AI pipeline.
- Make a prediction with the deployed Vertex AI model.
```
[Get started with AutoML tabular pipeline workflows](community/ml_ops/stage3/get_started_with_automl_tabular_pipeline_workflow.ipynb)
[Get Started with rapid prototyping with BQML and AutoML components](get_started_with_rapid_prototyping_bqml_automl.ipynb)
In this tutorial, you learn how to use `AutoML Tabular Pipeline Template` for training, exporting and tuning an AutoML tabular model.
```
The steps performed include:
- Creating a BigQuery and Vertex AI training dataset.
- Training a BigQuery ML and AutoML model.
- Extracting evaluation metrics from the BigQueryML and AutoML models.
- Selecting the best trained model.
- Deploying the best trained model.
- Testing the deployed model infrastructure.
```
[Get Started with TFX Pipelines with Vertex AI](get_started_with_tfx_pipeline.ipynb)
```
The steps performed include:
- Create a TFX e2e pipeline.
- Execute the pipeline locally.
- Execute the pipeline on Google Cloud using `Vertex AI Training`
- Execute the pipeline using `Vertex AI Pipelines`.
```
[Get Started with machine management](get_started_with_machine_management.ipynb)
```
The steps performed in this tutorial include:
- Create a custom component with a self-contained training job.
- Execute pipeline using component-level settings for machine resources
- Convert the self-contained training componnt into a Vertex AI CustomJob.
- Execute pipeline using customjob-level settings for machine resources
```
[Get Started with Apache Airflow and Vertex AI Pipelines](get_started_with_airflow_and_vertex_pipelines.ipynb)
```
The steps performed in this tutorial include:
- Create Cloud Composer environment.
- Upload Airflow DAG to Composer environment that performs data processing -- i.e., creates a BigQuery table from a CSV file.
- Create a Vertex Pipeline that triggers the Airflow DAG.
- Execute the `Vertex AI Pipeline`.
```
[Get Started with Vertex AI Model Registry](get_started_with_model_registry.ipynb)
```
The steps performed in this tutorial include:
- Create and register a first version of a model to `Vertex AI Model Registry`
- Create and register a second version of a model to `Vertex AI Model Registry`
- List all versions of a `Model` resource.
- Change the default version of a `Model` resource`
- Deploy the default version of a `Model` resource.
- Delete a model version from a `Model` resource.
- Delete a `Model` resource along with all model versions.
```
[Get Started with AutoML Tabular Pipeline Workflow](get_started_with_automl_tabular_pipeline_workflow.ipynb)
```
The steps performed in this tutorial include:
- Define training specification.
- Dataset specification
- Hyperparameter overide specification
@@ -182,42 +208,7 @@ The steps performed include:
- Create `Endpoint` resource.
- Deploy exported OSS TF model.
- Make a prediction.
[Get started with rapid prototyping with AutoML and BigQuery ML](community/ml_ops/stage3/get_started_with_rapid_prototyping_bqml_automl.ipynb)
In this tutorial, you learn how to use `Vertex AI Predictions` for rapid prototyping a model.
The steps performed include:
- Creating a BigQuery and Vertex AI training dataset.
- Training a BigQuery ML and AutoML model.
- Extracting evaluation metrics from the BigQueryML and AutoML models.
- Selecting the best trained model.
- Deploying the best trained model.
- Testing the deployed model infrastructure.
[Get started with AutoML pipeline components](community/ml_ops/stage3/get_started_with_automl_pipeline_components.ipynb)
In this tutorial, you learn how to use prebuilt `Google Cloud Pipeline Components` for `Vertex AI AutoML`.
The steps performed include:
- Construct a pipeline for:
- Training a Vertex AI AutoML trained model.
- Test the serving binary with a batch prediction job.
- Deploying a Vertex AI AutoML trained model.
- Execute a Vertex AI pipeline.
[Get started with BigQuery and TFDV pipeline components](community/ml_ops/stage3/get_started_with_bq_tfdv_pipeline_components.ipynb)
In this tutorial, you learn how to use build lightweight Python components for BigQuery and TensorFlow Data Validation.
The steps performed include:
- Build and execute a pipeline component for creating a Vertex AI Tabular Dataset from a BigQuery table.
- Build and execute a pipeline component for generating TFDV statistics and schema from a Vertex AI Tabular Dataset.
- Execute a Vertex AI pipeline.
```
### E2E Stage Example
@@ -225,6 +216,7 @@ The steps performed include:
```
The steps performed include:
- Obtain resources from the experimentation stage.
- Baseline model.
- Dataset schema/statistics for baseline model.
@@ -237,4 +229,3 @@ The steps performed include:
- Create the Vertex AI Model base model.
- Formalize a training pipeline.
```
@@ -64,6 +64,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with Apache Airflow and Vertex AI Pipelines."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is [Condensed Game Data](gs://example-datasets/game_data_condensed.csv), which comes from the [Apache Beam examples](https://github.com/apache/beam/tree/master/sdks/python/apache_beam/examples/complete/game). The version used in this tutorial is stored in a Cloud Storage bucket."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -86,35 +97,16 @@
"- Create Cloud Composer environment.\n",
"- Upload Airflow DAG to Composer environment that performs data processing -- i.e., creates a BigQuery table from a CSV file.\n",
"- Create a `Vertex AI Pipeline` that triggers the Airflow DAG.\n",
"- Execute the `Vertex AI Pipeline`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"- Execute the `Vertex AI Pipeline`.\n",
"\n",
"The dataset used for this tutorial is [Condensed Game Data](gs://example-datasets/game_data_condensed.csv), which comes from the [Apache Beam examples](https://github.com/apache/beam/tree/master/sdks/python/apache_beam/examples/complete/game). The version used in this tutorial is stored in a Cloud Storage bucket."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b8a374d1a7dc"
},
"source": [
"### Costs\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"- Vertex AI\n",
"- Cloud Storage\n",
"- BigQuery\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage pricing](https://cloud.google.com/storage/pricing) and [BigQuery pricing](https://cloud.google.com/bigquery/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
]
},
{
@@ -190,8 +182,6 @@
"id": "ce9e86b26403"
},
"source": [
"#### Check package versions\n",
"\n",
"Check that you have correctly installed the packages. The KFP SDK version should be >=1.6:"
]
},
@@ -213,8 +203,6 @@
"id": "BF1j6f9HApxa"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -225,7 +213,7 @@
"\n",
"1. [Enable the Vertex AI](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com) and [Composer API](https://console.cloud.google.com/flows/enableapi?apiid=composer.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -568,6 +556,7 @@
},
"outputs": [],
"source": [
"import kfp\n",
"from google.cloud import aiplatform\n",
"from kfp import dsl\n",
"from kfp.v2 import compiler\n",
@@ -758,7 +747,7 @@
"source": [
"# This code is modified version of https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/composer/rest/get_client_id.py\n",
"\n",
"shell_output = ! python3 get_composer_config.py $PROJECT_ID $REGION $COMPOSER_ENV_NAME\n",
"shell_output=! python3 get_composer_config.py $PROJECT_ID $REGION $COMPOSER_ENV_NAME\n",
"COMPOSER_WEB_URI = shell_output[0]\n",
"COMPOSER_DAG_GCS = shell_output[1]\n",
"COMPOSER_CLIENT_ID = shell_output[2]\n",
@@ -988,7 +977,7 @@
" dag_name: str,\n",
" composer_client_id: str,\n",
" composer_webserver_id: str,\n",
" response: Output[Artifact],\n",
" response: Output[Artifact]\n",
"):\n",
" # [START composer_trigger]\n",
"\n",
@@ -999,7 +988,12 @@
" from google.auth.transport.requests import Request\n",
" from google.oauth2 import id_token\n",
"\n",
"\n",
" IAM_SCOPE = 'https://www.googleapis.com/auth/iam'\n",
" OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'\n",
" \n",
" data = '{\"replace_microseconds\":\"false\"}'\n",
" context = None\n",
"\n",
" \"\"\"Makes a POST request to the Composer DAG Trigger API\n",
"\n",
@@ -1014,13 +1008,13 @@
" \"\"\"\n",
"\n",
" # Form webserver URL to make REST API calls\n",
" webserver_url = f\"{composer_webserver_id}/api/experimental/dags/{dag_name}/dag_runs\"\n",
" webserver_url = f'{composer_webserver_id}/api/experimental/dags/{dag_name}/dag_runs'\n",
" # print(webserver_url)\n",
"\n",
" # This code is copied from\n",
" # https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iap/make_iap_request.py\n",
" # START COPIED IAP CODE\n",
" def make_iap_request(url, client_id, method=\"GET\", **kwargs):\n",
" def make_iap_request(url, client_id, method='GET', **kwargs):\n",
" \"\"\"Makes a request to an application protected by Identity-Aware Proxy.\n",
" Args:\n",
" url: The Identity-Aware Proxy-protected URL to fetch.\n",
@@ -1034,8 +1028,8 @@
" The page body, or raises an exception if the page couldn't be retrieved.\n",
" \"\"\"\n",
" # Set the default timeout, if missing\n",
" if \"timeout\" not in kwargs:\n",
" kwargs[\"timeout\"] = 90\n",
" if 'timeout' not in kwargs:\n",
" kwargs['timeout'] = 90\n",
"\n",
" # Obtain an OpenID Connect (OIDC) token from metadata server or using service\n",
" # account.\n",
@@ -1045,41 +1039,32 @@
" # Authorization header containing \"Bearer \" followed by a\n",
" # Google-issued OpenID Connect token for the service account.\n",
" resp = requests.request(\n",
" method,\n",
" url,\n",
" headers={\"Authorization\": \"Bearer {}\".format(google_open_id_connect_token)},\n",
" **kwargs,\n",
" )\n",
" method, url,\n",
" headers={'Authorization': 'Bearer {}'.format(\n",
" google_open_id_connect_token)}, **kwargs)\n",
" if resp.status_code == 403:\n",
" raise Exception(\n",
" \"Service account does not have permission to \"\n",
" \"access the IAP-protected application.\"\n",
" )\n",
" raise Exception('Service account does not have permission to '\n",
" 'access the IAP-protected application.')\n",
" elif resp.status_code != 200:\n",
" raise Exception(\n",
" \"Bad response from application: {!r} / {!r} / {!r}\".format(\n",
" resp.status_code, resp.headers, resp.text\n",
" )\n",
" )\n",
" 'Bad response from application: {!r} / {!r} / {!r}'.format(\n",
" resp.status_code, resp.headers, resp.text))\n",
" else:\n",
" print(f\"response = {resp.text}\")\n",
" # not executed when testing locally\n",
" if response:\n",
" file_path = os.path.join(response.path)\n",
" os.makedirs(file_path)\n",
" with open(os.path.join(file_path, \"airflow_response.json\"), \"w\") as f:\n",
" with open(os.path.join(file_path, \"airflow_response.json\"), 'w') as f:\n",
" json.dump(resp.text, f)\n",
"\n",
" # END COPIED IAP CODE\n",
"\n",
" \n",
" # Make a POST request to IAP which then Triggers the DAG\n",
" make_iap_request(\n",
" webserver_url,\n",
" composer_client_id,\n",
" method=\"POST\",\n",
" json={\"conf\": data, \"replace_microseconds\": \"false\"},\n",
" )\n",
"\n",
" webserver_url, composer_client_id, method='POST', json={\"conf\": data, \"replace_microseconds\": 'false'})\n",
" \n",
" # [END composer_trigger]"
]
},
@@ -1109,7 +1094,7 @@
" dag_name=COMPOSER_DAG_NAME,\n",
" composer_client_id=COMPOSER_CLIENT_ID,\n",
" composer_webserver_id=COMPOSER_WEB_URI,\n",
" response=None,\n",
" response=None\n",
" )\n",
"except Exception as e:\n",
" print(e)"
@@ -1136,13 +1121,12 @@
},
"outputs": [],
"source": [
"PATH = %env PATH\n",
"PATH=%env PATH\n",
"%env PATH={PATH}:/home/jupyter/.local/bin\n",
"\n",
"PIPELINE_ROOT = f\"{BUCKET_URI}/pipeline_root/\"\n",
"print(PIPELINE_ROOT)\n",
"\n",
"\n",
"@dsl.pipeline(\n",
" name=\"pipeline-trigger-airflow-dag\",\n",
" description=\"Trigger Airflow DAG from Vertex AI Pipelines\",\n",
@@ -1156,7 +1140,7 @@
" data_processing_task = trigger_airflow_dag(\n",
" dag_name=data_processing_task_dag_name,\n",
" composer_client_id=COMPOSER_CLIENT_ID,\n",
" composer_webserver_id=COMPOSER_WEB_URI,\n",
" composer_webserver_id=COMPOSER_WEB_URI\n",
" )"
]
},
@@ -1187,8 +1171,9 @@
" display_name=\"airflow_pipeline\",\n",
" template_path=\"pipeline-trigger-airflow-dag.json\",\n",
" pipeline_root=PIPELINE_ROOT,\n",
" parameter_values={},\n",
" enable_caching=False,\n",
" parameter_values={\n",
" },\n",
" enable_caching=False\n",
")\n",
"\n",
"pipeline.run()\n",
@@ -1228,7 +1213,7 @@
},
"outputs": [],
"source": [
"COMPOSER_WEB_URI + \"/admin/airflow/tree?dag_id=dag_gcs_to_bq_orch\""
"COMPOSER_WEB_URI + '/admin/airflow/tree?dag_id=dag_gcs_to_bq_orch'"
]
},
{
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with AutoML pipeline components."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower in the given image from the five classes of flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -89,26 +100,8 @@
" - Training a Vertex AI AutoML trained model.\n",
" - Test the serving binary with a batch prediction job.\n",
" - Deploying a Vertex AI AutoML trained model.\n",
"- Execute a Vertex AI pipeline.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"- Execute a Vertex AI pipeline.\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower in the given image from the five classes of flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eef426a35e17"
},
"source": [
"### Costs\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
@@ -193,8 +186,6 @@
"id": "BF1j6f9HApxa"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -205,7 +196,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -33,18 +33,18 @@
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage3/get_started_with_automl_tabular_pipeline_workflow.ipynb\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/ml_ops/stage3/get_started_with_automl_tabular_pipeline_workflow.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
" </a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage3/get_started_with_automl_tabular_pipeline_workflow.ipynb\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notcommunity/ml_ops/stage3ebooks/community/ml_ops/stage3/get_started_with_automl_tabular_pipeline_workflow.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
" View on GitHub\n",
" </a>\n",
" </td>\n",
" <td>\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/community/ml_ops/stage3/get_started_with_automl_tabular_pipeline_workflow.ipynb\">\n",
" <a href=\"https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/automl/get_started_with_automl_tabular_pipeline_workflow.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI logo\">\n",
" Open in Vertex AI Workbench\n",
" </a>\n",
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with AutoML Tabular pipeline template."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:iris,lcn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Iris dataset](https://www.tensorflow.org/datasets/catalog/iris) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -94,26 +105,8 @@
"- Export AutoML model as an OSS TF model.\n",
"- Create `Endpoint` resource.\n",
"- Deploy exported OSS TF model.\n",
"- Make a prediction."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:iris,lcn"
},
"source": [
"### Dataset\n",
"- Make a prediction.\n",
"\n",
"The dataset used for this tutorial is the [Iris dataset](https://www.tensorflow.org/datasets/catalog/iris) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4fc0ad661ebb"
},
"source": [
"### Costs \n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
@@ -219,7 +212,7 @@
"\n",
"3. [Enable the following APIs: Vertex AI APIs, Dataflow APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,dataflow.googleapis.com,compute_component,storage-component.googleapis.com)\n",
"\n",
"4. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"4. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -227,6 +220,32 @@
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zebLBGXOky2A"
},
"source": [
"## Notes about service account and permission\n",
"\n",
"**By default no configuration is required**, if you run into any permission related issue, please make sure the service accounts above have the required roles:\n",
"\n",
"|Service account email|Description|Roles|\n",
"|---|---|---|\n",
"|PROJECT_NUMBER-compute@developer.gserviceaccount.com|Compute Engine default service account|Dataflow Admin, Dataflow Worker, Storage Admin, BigQuery Admin, Vertex AI User|\n",
"|service-PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com|AI Platform Service Agent|Vertex AI Service Agent|\n",
"\n",
"\n",
"1. Goto https://console.cloud.google.com/iam-admin/iam.\n",
"2. Check the \"Include Google-provided role grants\" checkbox.\n",
"3. Find the above emails.\n",
"4. Grant the corresponding roles.\n",
"\n",
"### Using data source from a different project\n",
"- For the BQ data source, grant both service accounts the \"BigQuery Data Viewer\" role.\n",
"- For the CSV data source, grant both service accounts the \"Storage Object Viewer\" role.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -500,32 +519,6 @@
"! rm gcs_lifecycle.tmp"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zebLBGXOky2A"
},
"source": [
"### Notes about service account and permission\n",
"\n",
"**By default no configuration is required**, if you run into any permission related issue, please make sure the service accounts above have the required roles:\n",
"\n",
"|Service account email|Description|Roles|\n",
"|---|---|---|\n",
"|PROJECT_NUMBER-compute@developer.gserviceaccount.com|Compute Engine default service account|Dataflow Admin, Dataflow Worker, Storage Admin, BigQuery Admin, Vertex AI User|\n",
"|service-PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com|AI Platform Service Agent|Vertex AI Service Agent|\n",
"\n",
"\n",
"1. Goto https://console.cloud.google.com/iam-admin/iam.\n",
"2. Check the \"Include Google-provided role grants\" checkbox.\n",
"3. Find the above emails.\n",
"4. Grant the corresponding roles.\n",
"\n",
"### Using data source from a different project\n",
"- For the BQ data source, grant both service accounts the \"BigQuery Data Viewer\" role.\n",
"- For the CSV data source, grant both service accounts the \"Storage Object Viewer\" role.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with BigQuery and TFDV pipeline components."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset you use only the fields year, month and day to predict the value of mean daily temperature (mean_temp)."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -73,7 +84,7 @@
"source": [
"### Objective\n",
"\n",
"In this tutorial, you learn how to use build lightweight Python components for BigQuery and TensorFlow Data Validation.\n",
"In this tutorial, you learn how to use build lightweight Python components for BigQuery and Tensorflow Data Validation.\n",
"\n",
"This tutorial uses the following Google Cloud ML services:\n",
"\n",
@@ -88,31 +99,26 @@
"- Execute a Vertex AI pipeline."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:gsod,lrg"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the GSOD dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset you use only the fields year, month and day to predict the value of mean daily temperature (mean_temp)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c997d8d92ce"
},
"source": [
"### Costs\n",
"### Costs \n",
"\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"- Vertex AI\n",
"- Cloud Storage\n",
"- BigQuery\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage pricing](https://cloud.google.com/storage/pricing) and [BigQuery pricing](https://cloud.google.com/bigquery/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
"\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."
]
},
{
@@ -187,8 +193,6 @@
"id": "BF1j6f9HApxa"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -199,7 +203,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,dataflow.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -226,6 +230,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with BigQuery ML pipeline components."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:penguins,lcn,bq"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the Penguins dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset predicts the species."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -94,31 +105,26 @@
"- Make a prediction with the deployed Vertex AI model."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:penguins,lcn,bq"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the Penguins dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). The version of the dataset predicts the species."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c997d8d92ce"
},
"source": [
"### Costs\n",
"### Costs \n",
"\n",
"\n",
"This tutorial uses billable components of Google Cloud:\n",
"\n",
"- Vertex AI\n",
"- Cloud Storage\n",
"- BigQuery\n",
"* Vertex AI\n",
"* Cloud Storage\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage pricing](https://cloud.google.com/storage/pricing) and [BigQuery pricing](https://cloud.google.com/bigquery/pricing) and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
"\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."
]
},
{
@@ -195,8 +201,6 @@
"id": "BF1j6f9HApxa"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -207,7 +211,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,dataflow.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -234,6 +238,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
@@ -29,7 +29,7 @@
"id": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 3 : formalization: get started with Vertex AI custom training pipeline components\n",
"# E2E ML on GCP: MLOps stage 3 : formalization: get started with custom training pipeline components\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
@@ -65,6 +65,17 @@
"This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with custom training pipeline components."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -98,17 +109,6 @@
"- Execute a Vertex AI pipeline."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:flowers,icn"
},
"source": [
"### Dataset\n",
"\n",
"The dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -204,8 +204,6 @@
"id": "BF1j6f9HApxa"
},
"source": [
"## Before you begin\n",
"\n",
"### Set up your Google Cloud project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
@@ -216,7 +214,7 @@
"\n",
"1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,dataflow.googleapis.com).\n",
"\n",
"1. If you are running this notebook locally, you need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
"\n",
"1. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
@@ -243,6 +241,8 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},

Some files were not shown because too many files have changed in this diff Show More