Compare commits

..
Author SHA1 Message Date
ivanmkc d7591ed256 Improved git diff logic 2022-06-22 20:53:03 -04:00
209 changed files with 13622 additions and 900745 deletions
@@ -1,2 +1 @@
ratemate
google-cloud-aiplatform
+2 -16
View File
@@ -62,18 +62,6 @@ parser.add_argument(
help="The GCP region. This is used to inject a variable value into the notebook before running.",
required=True,
)
parser.add_argument(
"--variable_service_account",
type=str,
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 +108,9 @@ 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,
)
@@ -68,20 +68,11 @@ class NotebookExecutionResult:
build_id: 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:
@@ -93,8 +84,6 @@ def _process_notebook(
replacement_map={
"PROJECT_ID": variable_project_id,
"REGION": variable_region,
"SERVICE_ACCOUNT": variable_service_account,
"VPC_NETWORK": variable_vpc_network,
},
)
@@ -129,10 +118,8 @@ def process_and_execute_notebook(
artifacts_bucket: str,
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:
@@ -140,13 +127,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])
@@ -172,8 +152,6 @@ def process_and_execute_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
@@ -277,8 +255,7 @@ 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 = [notebook for notebook in notebooks if notebook.endswith(".ipynb")]
notebooks = [notebook for notebook in notebooks if len(notebook) > 0]
@@ -297,13 +274,11 @@ 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.
@@ -360,8 +335,6 @@ def process_and_execute_notebooks(
artifacts_bucket,
variable_project_id,
variable_region,
variable_service_account,
variable_vpc_network,
private_pool_id,
deadline,
),
@@ -376,8 +349,6 @@ def process_and_execute_notebooks(
artifacts_bucket=artifacts_bucket,
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,
@@ -403,18 +374,10 @@ def process_and_execute_notebooks(
format_timedelta(result.duration),
result.log_url,
result.output_uri,
result.output_uri_web,
]
for result in results_sorted
],
headers=[
"build_tag",
"status",
"duration",
"log_url",
"output_uri",
"output_uri_web",
],
headers=["build_tag", "status", "duration", "log_url", "output_url"],
)
)
@@ -442,8 +405,6 @@ def process_and_execute_notebooks(
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,
)
execute_notebook_helper.execute_notebook(
+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)):
@@ -4,35 +4,25 @@ 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
# Create a virtual environment
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- python3 -m venv workspace/env
- 'python3 .cloud-build/CheckPythonVersion.py'
# Install Python dependencies
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- . workspace/env/bin/activate &&
python3 -m pip -q install -U pip &&
python3 -m pip -q install -U -r .cloud-build/requirements.txt
- 'python3 -m pip install -U pip && python3 -m pip install -U --user -r .cloud-build/requirements.txt'
# 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}"
- 'python3 -m pip install -U pip && python3 -m pip freeze && 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,42 +4,32 @@ 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]
# Create a virtual environment
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- python3 -m venv workspace/env
args: [fetch, --unshallow]
# Install Python dependencies
- name: ${_PYTHON_IMAGE}
entrypoint: /bin/sh
args:
- -c
- . workspace/env/bin/activate &&
python3 -m pip -q install -U pip &&
python3 -m pip -q install -U -r .cloud-build/requirements.txt
- 'python3 -m pip install -U pip && python3 -m pip install -U --user -r .cloud-build/requirements.txt'
# 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} --variable_vpc_network "${_GPC_VPC_NETWORK_NAME}" `if [ ! -z "${_PRIVATE_POOL_NAME}" ]; then echo "--private_pool_id ${_PRIVATE_POOL_NAME}"; fi`
- 'python3 -m pip install -U pip && python3 -m pip freeze && 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} `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}
+1 -1
View File
@@ -1,5 +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/pipelines/metrics_viz_run_compare_kfp.ipynb
notebooks/official/matching_engine/sdk_matching_engine_for_indexing.ipynb
-1
View File
@@ -1 +0,0 @@
notebooks/official/pipelines/metrics_viz_run_compare_kfp.ipynb
+2 -25
View File
@@ -35,8 +35,8 @@ Variables in conditionals can also be replaced:
def get_updated_value(content: str, variable_name: str, variable_value: str) -> str:
return re.sub(
rf"({variable_name}.*? = .*?[\",\'])\[.+?\]([\",\'].*?)",
rf"\g<1>{variable_value}\g<2>",
rf"({variable_name}.*?=.*?[\",\'])\[.+?\]([\",\'].*?)",
rf"\1{variable_value}\2",
content,
flags=re.M,
)
@@ -79,26 +79,3 @@ def test_region():
variable_value="us-central1",
)
assert new_content == 'REGION = "us-central1" # @param {type:"string"}'
def test_region_equal_equals_ignore():
# Tests that == is ignored
new_content = get_updated_value(
content='REGION == "[your-region]" # @param {type:"string"}',
variable_name="REGION",
variable_value="us-central1",
)
assert new_content == 'REGION == "[your-region]" # @param {type:"string"}'
def test_service_account():
# Tests that == is ignored
new_content = get_updated_value(
content='SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"}',
variable_name="SERVICE_ACCOUNT",
variable_value="12345-compute@developer.gserviceaccount.com",
)
assert (
new_content
== 'SERVICE_ACCOUNT = "12345-compute@developer.gserviceaccount.com" # @param {type:"string"}'
)
+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).
+2 -2
View File
@@ -2,9 +2,9 @@ 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
nbqa==1.4.0
nbqa==1.3.1
+2 -2
View File
@@ -68,7 +68,7 @@ if [ ${#notebooks[@]} -gt 0 ]; then
if [ "$is_test" = true ]; then
echo "Running nbfmt..."
python3 -m tensorflow_docs.tools.nbfmt --test "$notebook"
python3 -m tensorflow_docs.tools.nbfmt --remove_outputs --test "$notebook"
NBFMT_RTN=$?
# echo "Running black..."
# python3 -m nbqa black "$notebook" --check
@@ -93,7 +93,7 @@ if [ ${#notebooks[@]} -gt 0 ]; then
python3 -m nbqa isort "$notebook"
ISORT_RTN=$?
echo "Running nbfmt..."
python3 -m tensorflow_docs.tools.nbfmt "$notebook"
python3 -m tensorflow_docs.tools.nbfmt --remove_outputs "$notebook"
NBFMT_RTN=$?
echo "Running flake8..."
python3 -m nbqa flake8 "$notebook" --show-source --extend-ignore=W391,E501,F821,E402,F404,W503,E203,E722,W293,W291
-2
View File
@@ -1,8 +1,6 @@
* @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
/pluto_on_workbench @wkharold
/cpr-examples @samthrasher
@@ -1,5 +0,0 @@
testdata/*
build.py
test.py
state_dict.pth
config.json
@@ -1,6 +0,0 @@
cpr_model_server.py
entrypoint.py
state_dict.pth
config.json
**/__pycache__
!testdata/**
@@ -1,110 +0,0 @@
# CPR Example: PyTorch Image Models (timm)
## 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.
## Using this example
This code is a self-contained example of a custom model server project built using CPR.
As is, you can use it to serve the ViT-Small image classification model from Ross Wightman's [`timm`](https://github.com/rwightman/pytorch-image-models) library of image model implementations in PyTorch. Both CPU and GPU are supported.
You can also consider using the code here as a template for your own CPR project if you want to use a different model from `timm`, a different PyTorch model, or an entirely different framework.
### Requirements
In order to use this example, you'll need Docker and Python 3 installed on your system.
To get started, first create a virtual environment in an empty directory:
```sh
mkdir cpr-example
python3 -m venv cpr-example
cd cpr-example && source bin/activate
```
Then, clone the [vertex-ai-samples repo](https://github.com/GoogleCloudPlatform/vertex-ai-samples) in that directory:
```sh
git clone https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
cd vertex-ai-samples/community-content/cpr-examples/timm_serving
```
Finally, install the Python modules required to build and run the model server:
```sh
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.
- `load(artifacts_dir)`: The predictor's `load` method is called when the server starts up in order to set up the predictor, usually by loading model weights and any artifacts needed for preprocessing and postprocessing. In this example, we initialize the saved model from the `state_dict.pth` file located inside the `artifacts_dir` folder and create the preprocessing transform from the model config.
- `preprocess`, `predict`, `postprocess`: These methods are applied in sequence to the deserialized JSON data from each request.
- `preprocess` decodes images from base64 and apply cropping, scaling and normalizing transforms.
- `predict` runs the ViT-Small model on the preprocessed images and returns class scores.
- `postprocess` finds the top five classes and packs the class names, probabilities, and indices in a serializable result.
### Building the container
To build the model server locally, run the build command:
```sh
python build.py build
```
You can edit configuration values such as the model server's base image, the name and tag assigned to the image, and the path where model weights are stored locally.
When you run the build command, model weights are downloaded and the model server container is built.
### Running local tests
`test.py` contains a suite of unit tests for the predictor as well as end-to-end tests for the model server.
To run the tests:
```sh
python test.py
```
All of the test images are public domain.
- [Cat](https://commons.wikimedia.org/wiki/File:Stray_cat_on_wall.jpg)
- [Airplane](https://commons.wikimedia.org/wiki/File:Airplanes_jets.jpg)
- The infamous [mandrill](https://commons.wikimedia.org/wiki/File:Wikipedia-sipi-image-db-mandrill-4.2.03.png)
### Deploying to Vertex AI
Before uploading or deploying the container, you'll need to modify `config.py` to set appropriate values for:
- `project_id`: Your GCP project id.
- `region`: Region where the model will be uploaded and deployed.
- `repository`: [Artifact Registry repository](https://cloud.google.com/artifact-registry/docs/repositories/create-repos) in your project where the container image will be uploaded.
- `artifacts_gcs_dir`: Folder in a [Google Cloud Storage bucket](https://cloud.google.com/storage/docs/creating-buckets) where the model weights will be uploaded.
Once this is done, first upload the model:
```sh
python build.py upload
```
Then deploy it:
```sh
python build.py deploy
```
If you run the deploy command again, it will create a new endpoint. If you want to undeploy the model, you can do so using the Vertex AI dashboard on the Google Cloud console, or use `gcloud ai endpoints undeploy` from the command line.
After deploying successfully, you can run `python build.py probe` to send a sample request to the deployed model.
@@ -1,117 +0,0 @@
# Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Build the model server container."""
import json
import logging
import os
import pathlib
from typing import Sequence
from absl import app
from absl import logging
from config import CPRConfig
from google.cloud import aiplatform
from google.cloud.aiplatform import prediction as cpr
import smart_open
import timm
from timm_serving import predictor
import torch
def build_container(config: CPRConfig, tag: str) -> cpr.LocalModel:
"""Build the model server container.
Args:
tag: Output image tag.
Returns:
LocalModel exposing the built model server.
"""
return cpr.LocalModel.build_cpr_model(
src_dir=os.path.join(os.getcwd()),
output_image_uri=tag,
base_image=config.base_image,
predictor=predictor.TimmPredictor,
requirements_path=os.path.join(os.getcwd(), "requirements.txt"),
)
def save_model_artifact(destination: str) -> None:
"""Save a copy of the model state dict."""
model = timm.create_model(predictor.TimmPredictor.TIMM_MODEL_NAME, pretrained=True)
dest_file = os.path.join(destination, predictor.TimmPredictor.WEIGHTS_FILE)
with smart_open.open(dest_file, "wb") as f:
torch.save(model, f)
logging.info("Saved model to %s", dest_file)
logging.info("%s parameters", sum(p.numel() for p in model.parameters()))
def upload_model(config: CPRConfig) -> aiplatform.Model:
"""Tag and upload the model server."""
ar_tag = (
f"{config.region}-docker.pkg.dev/{config.project_id}"
f"/{config.repository}/{config.image}"
)
local_model = build_container(config, tag=ar_tag)
aiplatform.init(project=config.project_id, location=config.region)
local_model.push_image()
aip_model = aiplatform.Model.upload(
local_model=local_model,
display_name=predictor.TimmPredictor.TIMM_MODEL_NAME,
artifact_uri=config.artifact_gcs_dir,
)
config.model_name = aip_model.resource_name
config.save()
return aip_model
def deploy_model(config: CPRConfig) -> aiplatform.Endpoint:
"""Deploy the model server to a Vertex Prediction endpoint."""
aiplatform.init(project=config.project_id, location=config.region)
aip_model = aiplatform.Model(model_name=config.model_name)
endpoint = aip_model.deploy(machine_type=config.machine_type)
config.endpoint_name = endpoint.resource_name
config.save()
return endpoint
def probe_prediction(config: CPRConfig, request_path: str) -> None:
"""Send a sample prediction request to the Vertex Prediction endpoint."""
aiplatform.init(project=config.project_id, location=config.region)
aip_endpoint = aiplatform.Endpoint(endpoint_name=config.endpoint_name)
with open(request_path) as f:
logging.info(aip_endpoint.predict(**json.load(f)))
def main(argv: Sequence[str]):
config = CPRConfig()
if pathlib.Path(config.config_file).exists():
config.load()
actions = set(argv[1:])
if "build" in actions:
build_container(config, config.image)
save_model_artifact(config.artifact_local_dir)
if "upload" in actions:
save_model_artifact(config.artifact_gcs_dir)
upload_model(config)
if "deploy" in actions:
deploy_model(config)
if "probe" in actions:
probe_prediction(config, request_path="sample_request.json")
if __name__ == "__main__":
app.run(main)
@@ -1,76 +0,0 @@
# Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
import json
@dataclasses.dataclass
class CPRConfig(object):
"""Configure the build process by editing the default values here.
config_file: File path used to save values in this config. (Some
values, such as the model name, are generated at build time and
depended on by future steps, so saving it allows this script to
deploy the model without re-uploading it, for example.)
base_image: Base Docker image on top of which the model server will
be built. By default, a Debian-based Python 3 image without GPU
support will be used.
image: Name and tag assigned to the built model server image.
artifact_local_dir: Local directory where a copy of the pretrained model weights
will be saved.
region: Google Cloud Region where the model will be uploaded during the
build process.
project_id: Google Cloud project ID.
repository: Name of the Artifact Registry repository where the container
will be uploaded.
artifact_gcs_dir: Location on GCS where a copy of the pretrained model
weights will be uploaded.
model_name: Full resource path of the uploaded model. This is a write-only
field, the value is generated by Vertex AI when the model is uploaded.
endpoint_name: Full resource path of the created endpoint. This is a
write-only field, the value is generated by Vertex AI when the model is
deployed to an endpoint.
machine_type: Machine type to use when deploying the model.
"""
config_file: str = "config.json"
base_image: str = "python:3.10-bullseye"
image: str = "timm_predictor:latest"
artifact_local_dir: str = ""
region: str = "us-central1"
project_id: str = "<your project ID here>"
repository: str = "cpr-images"
artifact_gcs_dir: str = "gs://<your bucket ID here>/timm-vit224/"
model_name: str = ""
endpoint_name: str = ""
machine_type: str = "n1-standard-2"
def save(self):
with open(self.config_file, "w") as f:
json.dump(dataclasses.asdict(self), f, indent=2)
def load(self):
with open(self.config_file) as f:
self.__init__(**json.load(f))
@@ -1,8 +0,0 @@
absl-py==1.1.0
fastapi==0.75.2
uvicorn==0.18.2
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
File diff suppressed because one or more lines are too long
@@ -1,255 +0,0 @@
"""Test the timm_serving predictor."""
import base64
import json
import logging
import os
import pickle
from typing import List, Dict
from absl import flags
from absl import logging
from absl.testing import absltest
from config import CPRConfig
import fastapi
from google.cloud import aiplatform
from google.cloud.aiplatform import prediction as cpr
import PIL
from timm_serving import predictor
import torch
VIT_SMALL_PARAMS = 22878952
def b64_encode_file(path: str) -> str:
"""Encode a file's contents as base64.
Args:
path: Path to the file.
Returns:
Base64-encoded contents of the file.
"""
with open(path, "rb") as f:
return str(base64.b64encode(f.read()), encoding="utf-8")
def make_instance_dict(
image_paths: List[str], base64_encodings: List[str]
) -> Dict[str, List[str]]:
"""Generate a dictionary similar to a parsed prediction server request.
Args:
image_paths: Paths to image files to include.
base64_encodings: Pre-encoded base64 strings.
Returns:
Dictionary of instances in the format accepted by the preprocessor.
"""
instances = [s for s in base64_encodings]
for path in image_paths:
instances.append(b64_encode_file(path))
return {"instances": instances}
def count_parameters(model: torch.nn.Module):
"""Count the parameters in a Pytorch model.
Args:
model: Pytorch model (nn.Module).
Returns:
Number of parameters in the model.
"""
return sum(p.numel() for p in model.parameters())
class PredictorUnitTests(absltest.TestCase):
"""Unit tests for timm_serving.predictor."""
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.predictor = predictor.TimmPredictor()
def test_load_from_saved_state_dict_ok(self):
self.predictor.load(self.config.artifact_local_dir)
self.assertEqual(count_parameters(self.predictor._model), VIT_SMALL_PARAMS)
def test_load_bad_path(self):
with self.assertRaises(FileNotFoundError):
self.predictor.load("testdata/")
with self.assertRaisesRegex(ValueError, "not a directory"):
self.predictor.load("blah")
def test_load_bad_data(self):
with self.assertRaises(pickle.UnpicklingError):
self.predictor.load("testdata/bad_model_1")
with self.assertRaisesRegex(RuntimeError, "Invalid magic number"):
self.predictor.load("testdata/bad_model_2")
def test_preprocess_ok(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = make_instance_dict(
base64_encodings=[],
image_paths=[
"testdata/airplane.jpg",
"testdata/mandrill.tiff",
"testdata/mandrill.tiff",
"testdata/cat_alpha.png",
],
)
result = self.predictor.preprocess(instance_dict)
self.assertEqual(result.size(), torch.Size([4, 3, 224, 224]))
self.assertEqual(result.dtype, torch.float32)
def test_preprocess_no_instances(self):
self.predictor.load(self.config.artifact_local_dir)
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess({})
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, 'must contain "instances"')
def test_preprocess_wrong_shape_instances(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = {"instances": [[b64_encode_file("testdata/mandrill.tiff")]]}
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess(instance_dict)
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, "not 'list'")
def test_preprocess_bad_base64(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = make_instance_dict(base64_encodings=["!@#$"], image_paths=[])
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess(instance_dict)
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, "[Bb]ase64")
def test_preprocess_not_image_data(self):
self.predictor.load(self.config.artifact_local_dir)
instance_dict = make_instance_dict(
base64_encodings=[], image_paths=["testdata/bad.jpg"]
)
with self.assertRaises(fastapi.HTTPException) as ctx:
self.predictor.preprocess(instance_dict)
self.assertEqual(ctx.exception.status_code, 400)
self.assertRegex(ctx.exception.detail, "image file")
def test_predict_ok(self):
self.predictor.load(self.config.artifact_local_dir)
inputs = torch.zeros(size=[2, 3, 224, 224], dtype=torch.float32)
if torch.cuda.device_count() > 0:
inputs = inputs.cuda()
result = self.predictor.predict(inputs)
self.assertEqual(result.size(), torch.Size([2, 1000]))
self.assertEqual(result.dtype, torch.float32)
def test_postprocess_ok(self):
class_probs = torch.zeros(size=[2, 1000])
class_probs[0, 0] = 1
class_probs[1, 123] = 1
result = self.predictor.postprocess(class_probs)
predictions = result["predictions"]
self.assertLen(predictions[0]["class_names"], 5)
self.assertLen(predictions[0]["indices"], 5)
self.assertLen(predictions[0]["probabilities"], 5)
self.assertLen(predictions[1]["class_names"], 5)
self.assertLen(predictions[1]["indices"], 5)
self.assertLen(predictions[1]["probabilities"], 5)
self.assertContainsSubsequence(predictions[0]["class_names"][0], "tench")
self.assertContainsSubsequence(
predictions[1]["class_names"][0], "spiny lobster"
)
class ServerEndToEndTests(absltest.TestCase):
"""End-to-end tests for the model server, using LocalEndpoint."""
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.local_model = cpr.LocalModel(
serving_container_spec=aiplatform.gapic.ModelContainerSpec(
image_uri=self.config.image
)
)
self.local_endpoint = self.local_model.deploy_to_local_endpoint(
artifact_uri=self.config.artifact_local_dir or os.getcwd()
)
self.local_endpoint.serve()
def tearDown(self):
self.local_endpoint.stop()
super().tearDown()
def test_e2e_healthcheck_ok(self):
health_check_response = self.local_endpoint.run_health_check()
self.assertEqual(health_check_response.status_code, 200)
self.assertEqual(health_check_response.content, b"{}")
def test_e2e_predict_ok(self):
predict_request = json.dumps(
make_instance_dict(
base64_encodings=[],
image_paths=[
"testdata/mandrill.tiff",
],
)
)
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 200)
predictions = response.json()["predictions"]
self.assertContainsSubsequence(predictions[0]["class_names"][0], "baboon")
def test_e2e_predict_bad_json_returns_400(self):
predict_request = "blah"
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
def test_e2e_predict_no_instances_returns_400(self):
predict_request = json.dumps({})
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
def test_e2e_predict_bad_base64_returns_400(self):
predict_request = json.dumps(
make_instance_dict(base64_encodings=["blah"], image_paths=[])
)
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
def test_e2e_predict_bad_image_returns_400(self):
predict_request = json.dumps(
make_instance_dict(base64_encodings=[], image_paths=["testdata/bad.jpg"])
)
response = self.local_endpoint.predict(
request=predict_request, headers={"Content-Type": "application/json"}
)
logging.info(response.content)
self.assertEqual(response.status_code, 400)
if __name__ == "__main__":
absltest.main()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

@@ -1 +0,0 @@
some non-image data
@@ -1 +0,0 @@
some non-image data
@@ -1 +0,0 @@
blah
Binary file not shown.

Before

Width:  |  Height:  |  Size: 348 KiB

File diff suppressed because it is too large Load Diff
@@ -1,178 +0,0 @@
# Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Adapts a pretrained TIMM image classification model to the CPR framework.
Documentation for the TIMM (Torch IMage Models) library is here:
https://rwightman.github.io/pytorch-image-models/
Its source can also be found here:
https://github.com/rwightman/pytorch-image-models
"""
import base64
import binascii
import io
import os
from typing import Dict, List, Union
from fastapi import HTTPException
from google.cloud.aiplatform import prediction as cpr
from pathlib import Path
import PIL
import smart_open
import timm
import torch
import torch.nn.functional as F
with open(Path(__file__).parent.absolute().joinpath("imagenet.txt")) as f:
IMAGENET_CLASSES = f.read().splitlines()
class TimmPredictor(cpr.predictor.Predictor):
"""Predictor class for image models based on TIMM."""
TIMM_MODEL_NAME = os.getenv("TIMM_MODEL_NAME", default="vit_small_patch32_224")
WEIGHTS_FILE = "state_dict.pth"
NUM_TOP_CLASSES_TO_RETURN = 5
def __init__(self):
self._cuda = torch.cuda.device_count() > 0
def load(self, artifacts_uri: str = ""):
"""Initializes the model and preprocessing transforms.
Args:
artifacts_uri: Directory where state dict is stored. Can be a
GCS URI or local path.
"""
if artifacts_uri:
artifact_path = os.path.join(artifacts_uri)
if not (os.path.isdir(artifact_path) or artifact_path.startswith("gs://")):
raise ValueError("Provided artifact_uri is not a directory.")
else:
artifact_path = os.getcwd()
artifact_path = os.path.join(artifact_path, self.WEIGHTS_FILE)
with smart_open.open(artifact_path, "rb") as f:
self._model = torch.load(f)
if self._cuda:
self._model.cuda()
config = timm.data.resolve_data_config(model=self.TIMM_MODEL_NAME, args=[])
self._transform = timm.data.create_transform(
is_training=False, use_prefetcher=False, **config
)
def preprocess(self, request_dict: Dict[str, List[str]]) -> torch.Tensor:
"""Performs preprocessing.
By default, the server expects a request body consisting of a valid JSON
object. This will be parsed by the handler before it's evaluated by the
preprocess method.
Args:
request_dict: Parsed request body. We expect that the input consists of
a list of base64-encoded image files under the "instances" key. (Any
image format that PIL.image.open can handle is okay.)
Returns:
torch.Tensor containing the preprocessed images as a batch. If GPU is
available, the result tensor will be stored on GPU.
"""
if "instances" not in request_dict:
raise HTTPException(
status_code=400,
detail='Request must contain "instances" as a top-level key.',
)
tensors = []
for (i, image) in enumerate(request_dict["instances"]):
# We use Base64 encoding to handle image data.
# This is probably the best we can do while still using JSON input.
# Overriding the input format requires building a custom Handler.
try:
image_bytes = base64.b64decode(image, validate=True)
except (binascii.Error, TypeError) as e:
raise HTTPException(
status_code=400,
detail=f"Base64 decoding of the input image at index {i} failed:"
f" {str(e)}",
)
try:
pil_image = PIL.Image.open(io.BytesIO(image_bytes)).convert("RGB")
except PIL.UnidentifiedImageError:
raise HTTPException(
status_code=400,
detail=f"The input image at index {i} could not be identified as an"
" image file.",
)
tensors.append(self._transform(pil_image))
with torch.inference_mode():
result = torch.stack(tensors)
if self._cuda:
result = result.cuda()
return result
def predict(self, instances: torch.Tensor) -> torch.Tensor:
"""Performs prediction.
Args:
instances: torch.Tensor with type torch.float32 and shape
[?, 3, 224, 224], containing the pre-processed input images.
Returns:
Vector of scores with type torch.float32 and shape [?, 1000],
representing the model's estimate of the likelihood that the
input belongs to the Imagenet class with that index.
"""
with torch.inference_mode():
class_scores = self._model(instances)
return class_scores
def postprocess(
self, class_scores: torch.Tensor
) -> Dict[str, List[Dict[str, Union[str, int, float]]]]:
"""Translate the model output into a classification result.
Args:
class_scores: torch.Tensor with type torch.float32 and shape
[?, 1000], containing the scores assigned to each class by
the model.
Returns:
Dictionary containing the list of classification results. Each
classification result contains the probabilities, class names, and
class indices of the classes with the top class scores as reported by
the model.
"""
class_probs = F.softmax(class_scores, dim=1)
top_k = class_probs.topk(self.NUM_TOP_CLASSES_TO_RETURN)
top_k_values = top_k.values.numpy().tolist()
top_k_indices = top_k.indices.numpy().tolist()
predictions = [
dict(
probabilities=values,
indices=indices,
class_names=[IMAGENET_CLASSES[int(class_num)] for class_num in indices],
)
for (values, indices) in zip(top_k_values, top_k_indices)
]
return {"predictions": predictions}
@@ -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",
+1 -7
View File
@@ -5,13 +5,11 @@
/sdk/sdk_* @andrewferlitsch
/gapic @andrewferlitsch
/gapic/custom/showcase_custom_image_classification_online_explain_example_based_api.ipynb @inardini
/ml_ops @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
@@ -20,11 +18,7 @@
/sdk/pytorch_lightning_custom_container_training.ipynb @brianchunkang
/tensorboard @yfang1
/feature_store @nayaknishant @morgandu
/prediction @googleapis/vertex-prediction-team
/vertex_endpoints/tf_hub_obj_detection/deploy_tfhub_object_detection_on_vertex_endpoints.ipynb @entrpn
/vertex_endpoints/nvidia-triton/nvidia-triton-custom-container-prediction.ipynb @RajeshThallam
/vertex_endpoints/optimized_tensorflow_runtime @vlasenkoalexey
/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_with_visionapi_and_automl.ipynb @mansari
@@ -30,25 +30,17 @@
},
"source": [
"<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://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/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>"
]
},
@@ -60,7 +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). "
"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). "
]
},
{
@@ -71,7 +63,7 @@
"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."
]
},
{
@@ -82,16 +74,16 @@
"source": [
"### Objective\n",
"\n",
"In this notebook, you learn how to:\n",
"In this notebook, you will learn how to:\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",
" * 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",
"You also learn how Vertex AI Feature Store can be useful in the below scenarios:\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."
" * online serving with updated feature values\n",
" * point-in-time correctness to fetch feature values for training"
]
},
{
@@ -105,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."
]
@@ -129,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."
]
},
{
@@ -148,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"
]
},
{
@@ -166,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:"
]
},
{
@@ -223,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,
@@ -242,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)"
]
},
{
@@ -391,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)"
]
},
@@ -409,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."
]
},
{
@@ -438,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."
]
},
{
@@ -476,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."
]
},
{
@@ -560,7 +547,7 @@
"id": "BlqJ-QdTcs6W"
},
"source": [
"#### Get data from source files"
"#### Entity Type Source Files"
]
},
{
@@ -656,7 +643,7 @@
"id": "bgb0WGwX5OW6"
},
"source": [
"#### Ingest Feature Values into _Users_ Entity Type"
"#### Ingest Feature Values into Users Entity Type"
]
},
{
@@ -681,7 +668,7 @@
"id": "PCAdQ3cF5OW6"
},
"source": [
"#### Ingest Feature Values into _Movies_ Entity Type"
"#### Ingest Feature Values into Movies Entity Type"
]
},
{
@@ -747,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."
]
},
{
@@ -758,7 +745,7 @@
"id": "hxsotHUe5OW7"
},
"source": [
"#### Read instances from source file"
"#### Read Instances Source File"
]
},
{
@@ -769,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\""
]
},
{
@@ -790,7 +776,7 @@
"id": "T5DW1MFt5OW7"
},
"source": [
"#### Load CSV file into a Pandas DataFrame"
"#### Load Csv File into a Pandas DataFrame"
]
},
{
@@ -801,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)"
]
},
@@ -833,7 +819,7 @@
"id": "ao1dC5Pc5OW8"
},
"source": [
"#### Batch Serve Feature Values from Movie Predictions Feature Store"
"#### Batch Serve Feature Values from Movie Predictions Featurestore"
]
},
{
@@ -869,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"
]
},
{
@@ -890,7 +875,7 @@
"id": "feTUJjqG5OW9"
},
"source": [
"#### Ingest updated Feature Values"
"#### Ingest Updated Feature Values"
]
},
{
@@ -930,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"
]
},
{
@@ -964,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"
]
},
{
@@ -985,7 +968,7 @@
"id": "abQRF6mx5OW-"
},
"source": [
"#### Backfill/Correct point-in-time data"
"#### Backfill/Correct Point-in-Time Data"
]
},
{
@@ -1026,7 +1009,7 @@
"id": "WXb4JUhu5OW-"
},
"source": [
"#### Ingest backfilled/corrected point-in-time data from dataframe"
"#### Ingest Backfill/Correct Point-in-Time Data"
]
},
{
@@ -1067,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]"
]
}
],
@@ -1,71 +1,13 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {
"id": "c8c4e360024a"
},
"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": "d6728c7e34d2"
},
"source": [
"<table align=\"left\">\n",
"# Taxi fare prediction using the Chicago Taxi Trips dataset\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/chicago_taxi_fare_prediction/chicago_taxi_fare_prediction.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/chicago_taxi_fare_prediction/chicago_taxi_fare_prediction.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/chicago_taxi_fare_prediction/chicago_taxi_fare_prediction.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": "28451b7c3d4b"
},
"source": [
"# Taxi fare prediction using the Chicago Taxi Trips dataset"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eaf8ba4eeea8"
},
"source": [
"## Table of contents\n",
"\n",
"* [Overview](#section-1)\n",
@@ -82,9 +24,9 @@
"## Overview\n",
"<a name=\"section-1\"></a>\n",
"\n",
"This notebook demonstrates analysis, feature selection, model building, and deployment with Explainable AI configured on Vertex AI, using a subset of the Chicago Taxi Trips dataset for taxi-fare prediction.\n",
"This notebook demonstrates analysis, feature selection, model building, and deployment with Vertex Explainable AI configured on Vertex AI, using a subset of the Chicago Taxi Trips dataset for taxi-fare prediction.\n",
"\n",
"*Note: This notebook is 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",
"*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",
@@ -96,7 +38,7 @@
"## Objective\n",
"<a name=\"section-3\"></a>\n",
"\n",
"The goal of this notebook is to provide an overview on the latest Vertex AI features like **Explainable AI** and **BigQuery in Notebooks** by trying to solve a taxi fare prediction problem. The steps followed in this notebook include: \n",
"The goal of this notebook is to provide an overview on the latest Vertex AI features like Explainable AI and \"BigQuery in Notebooks\" by trying to solve a taxi fare prediction problem. The steps followed in this notebook include: \n",
"\n",
"- Loading the dataset using \"BigQuery in Notebooks\".\n",
"- Performing exploratory data analysis on the dataset.\n",
@@ -124,131 +66,6 @@
"to generate a cost estimate based on your projected usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5178273783dd"
},
"source": [
"### Set up your local development environment\n",
"\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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f5494c42606e"
},
"source": [
"**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": "23976b1be293"
},
"source": [
"### Install additional packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1fd00fa70a2a"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Google Cloud Notebook product has specific requirements\n",
"IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
"\n",
"# Google Cloud Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_GOOGLE_CLOUD_NOTEBOOK:\n",
" USER_FLAG = \"--user\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a50fd443a6ce"
},
"outputs": [],
"source": [
"! pip install {USER_FLAG} --upgrade google-cloud-bigquery \\\n",
" google-cloud-aiplatform \\\n",
" google-cloud-storage \\\n",
" seaborn \\\n",
" sklearn \\\n",
" pandas \\\n",
" fsspec \\\n",
" pyarrow"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d3a26cb9b19d"
},
"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": "c1464805870e"
},
"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": {
@@ -257,31 +74,7 @@
"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 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": "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`."
]
@@ -326,175 +119,17 @@
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "30e64c0eda41"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7d43ac19ea91"
"id": "fed4b24ea061"
},
"source": [
"### Region\n",
"## Select or create a Cloud Storage bucket for storing the model\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",
"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 a Vertex AI model and endpoint resources in order to serve online predictions.\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)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3281bedf6d3c"
},
"outputs": [],
"source": [
"REGION = \"[your-region]\" # @param {type: \"string\"}\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0c9906f72b18"
},
"source": [
"### UUID\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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8940c46120e6"
},
"outputs": [],
"source": [
"import random\n",
"import string\n",
"\n",
"\n",
"# Generate a uuid of length 8\n",
"def generate_uuid():\n",
" return \"\".join(random.choices(string.ascii_lowercase + string.digits, k=8))\n",
"\n",
"\n",
"UUID = generate_uuid()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "648aa9824ac6"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Google Cloud Notebooks**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fc52bba17ee3"
},
"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": "535223fa4b84"
},
"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 Google Cloud Notebook product has specific requirements\n",
"IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
"\n",
"# If on Google Cloud Notebooks, then don't execute this code\n",
"if not IS_GOOGLE_CLOUD_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, 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": "0474cb91d91f"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\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 `LOCATION` variable, which is used for operations throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are available."
]
},
{
@@ -505,8 +140,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",
"LOCATION = \"us-central1\""
]
},
{
@@ -517,8 +153,13 @@
},
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + UUID\n",
"from datetime import datetime\n",
"\n",
"# Set a default bucket name in case bucket name is not given\n",
"if BUCKET_NAME == \"\" or BUCKET_NAME == \"[your-bucket-name]\" or BUCKET_NAME is None:\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"
]
},
@@ -539,7 +180,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
"! gsutil mb -l $REGION $BUCKET_NAME"
]
},
{
@@ -559,7 +200,7 @@
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil ls -al $BUCKET_NAME"
]
},
{
@@ -568,7 +209,7 @@
"id": "2e52fd6d4854"
},
"source": [
"### Import libraries"
"## Import the required libraries and define constants"
]
},
{
@@ -597,11 +238,11 @@
"id": "5166f42557ad"
},
"source": [
"The original dataset considered for this tutorial is a large and noisy one and so data from a specific date range will be used. Based on various online resources, the data from around May 2018 gave some really good results compared to the other date ranges. While there are also some complicated models proposed for the same problem, like considering the weather data, holidays and seasons, the current notebook only explores a simple linear regression model. Our main objective is to demonstrate the model deployment with Vertex Explainable AI configured on Vertex AI.\n",
"The dataset is quite a large and noisy one, so data from a specific date range will be used. Based on various blogs and resources that are available online, many of them seem to have used the data from around May 2018 which gave some really good results compared to the other date ranges. While there are also some complicated research models proposed for the same problem, like considering the weather data, holidays and seasons, the current notebook only explores a simple linear regression model, as our main objective is to demonstrate the model deployment with Vertex Explainable AI configured on Vertex AI.\n",
"\n",
"## Accessing the data through BigQuery Integration\n",
"## Accessing the data through \"BigQuery in Notebooks\"\n",
"\n",
"The **BigQuery Integration for Notebooks** feature of Vertex AI Workbench managed notebooks lets you use BigQuery and its features from the notebook itself eliminating the need to switch between tabs everytime. For every cell in the notebook, there is an option for the BigQuery integration at the top right, and selecting it enables you to compose an SQL query that can be executed in BigQuery. \n",
"The \"BigQuery in Notebooks\" feature of Vertex AI Workbench managed notebooks lets you use BigQuery and its features from the notebook itself eliminating the need to switch between tabs everytime. For every cell in the notebook, there is an option for the BigQuery integration at the top right, and selecting it enables you to compose an SQL query that can be executed in BigQuery. \n",
"\n",
"The chosen dataset consists of the following fields:\n",
"\n",
@@ -634,9 +275,7 @@
"- Time taken for the trip > 0.\n",
"- Distance covered during the trip > 0.\n",
"- Total trip charges > 0 and\n",
"- Pickup and dropoff areas are valid (not empty).\n",
"\n",
"Note: The below cell is a Bigquery Integration cell and can only execute on Vertex AI Workbench's managed instances. If your notebook environment is different, you can skip it."
"- Pickup and dropoff areas are valid (not empty)."
]
},
{
@@ -686,7 +325,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 = \"\"\"select \n",
"taxi_id, trip_start_timestamp, \n",
@@ -698,7 +337,7 @@
"where \n",
"trip_start_timestamp >= '2018-05-12' and \n",
"trip_end_timestamp <= '2018-05-18' and\n",
"trip_seconds > 60 and trip_seconds < 6*60*60 and\n",
"trip_seconds > 0 and trip_seconds < 6*60*60 and\n",
"trip_miles > 0 and\n",
"trip_total > 3 and\n",
"pickup_community_area is not NULL and \n",
@@ -850,7 +489,7 @@
"## Analyze numerical data\n",
"<a name=\"section-5\"></a>\n",
"\n",
"To further anaylyze the data, there are various plots that can be used on numerical and categorical fields. In case of numerical data, you can use histograms and box plots. Bar charts are suited for categorical data to better understand the distribution of the data and the outliers in the data."
"To further anaylyze the data, there are various plots that can be used on numerical and categorical fields. In case of numerical data, one can use histograms and box plots while bar charts are suited for categorical data to better understand the distribution of the data and the outliers in the data."
]
},
{
@@ -885,7 +524,7 @@
"id": "c3672976d67b"
},
"source": [
"The field `trip_seconds` describes the time taken for the trip in seconds. For ease of our analysis, let us convert it into hours."
"The field `trip_seconds` describes the time taken for the trip in seconds. Optionally, it can be converted into hours."
]
},
{
@@ -938,7 +577,6 @@
},
"outputs": [],
"source": [
"# generate a pairplot for 10K samples\n",
"sns.pairplot(\n",
" data=df[[\"trip_seconds\", \"trip_miles\", \"trip_total\", \"trip_speed\"]].sample(10000)\n",
")\n",
@@ -951,7 +589,7 @@
"id": "b69e8094ba39"
},
"source": [
"From the box plots and the histograms visualized so far, it is evident that there are some outliers causing skewness in the data which perhaps could be removed. Also, you can see some linear relationships between the independent variables considered in the pair-plot. For example, `trip_seconds` and `trip_miles` and the dependant variable `trip_total`."
"From the box plots and the histograms visualized so far, it is evident that there are some outliers causing skewness in the data which perhaps could be removed. Also, you can see some linear relationships between the independent variables considered in the pair-plot, for example, `trip_seconds` and `trip_miles` and the dependant variable `trip_total`."
]
},
{
@@ -1376,17 +1014,6 @@
"Configure Vertex Explainable AI before deploying the model. For further details, see [Configuring Vertex Explainable AI in Vertex AI models](https://cloud.google.com/vertex-ai/docs/explainable-ai/configuring-explanations#scikit-learn-and-xgboost-pre-built-containers)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a130721a5375"
},
"outputs": [],
"source": [
"MODEL_DISPLAY_NAME = \"[your-model-display-name]\" # @param {type: \"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -1395,11 +1022,7 @@
},
"outputs": [],
"source": [
"# If the model display name is not set, choose the default one\n",
"if MODEL_DISPLAY_NAME == \"[your-model-display-name]\":\n",
" MODEL_DISPLAY_NAME = \"taxi_fare_prediction_model\"\n",
"\n",
"\n",
"MODEL_DISPLAY_NAME = \"taxi_fare_prediction_model\"\n",
"ARTIFACT_GCS_PATH = f\"{BUCKET_URI}/{BLOB_PATH}\"\n",
"\n",
"# Feature-name(Inp_feature) and Output-name(Model_output) can be arbitrary\n",
@@ -1429,7 +1052,7 @@
"\n",
"# Create a Vertex AI model resource with support for Vertex Explainable AI\n",
"\n",
"aiplatform.init(project=PROJECT_ID, location=REGION)\n",
"aiplatform.init(project=PROJECT, location=LOCATION)\n",
"\n",
"model = aiplatform.Model.upload(\n",
" display_name=MODEL_DISPLAY_NAME,\n",
@@ -1453,20 +1076,7 @@
"id": "1ed1bd9f0957"
},
"source": [
"### Create an Endpoint resource for the model\n",
"\n",
"Set a display name for the endpoint and create the endpoint resource."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f0e5cea786b4"
},
"outputs": [],
"source": [
"ENDPOINT_DISPLAY_NAME = \"[your-endpoint-display-name]\" # @param {type: \"string\"}"
"Create an Endpoint resource for the model."
]
},
{
@@ -1477,12 +1087,10 @@
},
"outputs": [],
"source": [
"# If the display name is not set, choose the default one\n",
"if ENDPOINT_DISPLAY_NAME == \"[your-endpoint-display-name]\":\n",
" ENDPOINT_DISPLAY_NAME = \"taxi_fare_prediction_endpoint\"\n",
"ENDPOINT_DISPLAY_NAME = \"taxi_fare_prediction_endpoint\"\n",
"\n",
"endpoint = aiplatform.Endpoint.create(\n",
" display_name=ENDPOINT_DISPLAY_NAME, project=PROJECT_ID, location=REGION\n",
" display_name=ENDPOINT_DISPLAY_NAME, project=PROJECT, location=LOCATION\n",
")\n",
"\n",
"print(endpoint.display_name)\n",
@@ -1492,23 +1100,30 @@
{
"cell_type": "markdown",
"metadata": {
"id": "9eaab1c54d66"
"id": "2a1b280dbec6"
},
"source": [
"### Deploy the model to the created endpoint with the required machine type\n",
"\n",
"Set a name for the deployment and deploy the model to the created endpoint."
"Save the Endpoint Id for inference."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6fd9517c3403"
"id": "6516bfdd5066"
},
"outputs": [],
"source": [
"DEPLOYED_MODEL_NAME = \"[your-deployed-model-name]\" # @param {type: \"string\"}"
"ENDPOINT_ID = \"\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9eaab1c54d66"
},
"source": [
"Deploy the model to the created endpoint with the required machine type."
]
},
{
@@ -1519,14 +1134,10 @@
},
"outputs": [],
"source": [
"# If the deployment name is not set, choose the default one\n",
"if DEPLOYED_MODEL_NAME == \"[your-deployed-model-name]\":\n",
" DEPLOYED_MODEL_NAME = \"taxi_fare_prediction_deployment\"\n",
"\n",
"# Set the machine type to n1-standard2\n",
"DEPLOYED_MODEL_NAME = \"taxi_fare_prediction_deployment\"\n",
"MACHINE_TYPE = \"n1-standard-2\"\n",
"\n",
"# Deploy the model to the endpoint\n",
"# deploy the model to the endpoint\n",
"model.deploy(\n",
" endpoint=endpoint,\n",
" deployed_model_display_name=DEPLOYED_MODEL_NAME,\n",
@@ -1545,18 +1156,18 @@
"id": "686cfdcbaef8"
},
"source": [
"To ensure the model is deployed, the ID of the deployed model can be checked using the `endpoint.list_models()` method."
"Save the ID of the deployed model. The ID of the deployed model can also checked using the `endpoint.list_models()` method."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bab07adf5339"
"id": "018f0fdb1d60"
},
"outputs": [],
"source": [
"endpoint.list_models()"
"DEPLOYED_MODEL_ID = \"\""
]
},
{
@@ -1625,7 +1236,7 @@
" \"\"\"\n",
" aiplatform.init(project=project, location=location)\n",
"\n",
" # endpoint = aiplatform.Endpoint(endpoint_id)\n",
" endpoint = aiplatform.Endpoint(endpoint_id)\n",
"\n",
" response = endpoint.explain(instances=instances)\n",
" print(\"#\" * 10 + \"Explanations\" + \"#\" * 10)\n",
@@ -1655,7 +1266,7 @@
"\n",
"\n",
"test_json = [X_test.iloc[0].tolist(), X_test.iloc[1].tolist()]\n",
"prediction = explain_tabular_sample(PROJECT_ID, REGION, endpoint, test_json)"
"prediction = explain_tabular_sample(PROJECT, LOCATION, ENDPOINT_ID, test_json)"
]
},
{
@@ -1666,7 +1277,7 @@
"source": [
"## Next steps\n",
"\n",
"Since the Chicago Taxi Trips dataset is continuously updating, one can preform the same kind of analysis and model training every time a new set of data is available. The date range can also be increased from a week to a month or more depending on the quality of the data. Most of the steps followed in this notebook would still be valid and can be applied over the new data unless the data is too noisy. In fact, the notebook itself can be scheduled to run at the specified times to retrain the model using the scheduling option of [Vertex AI Workbench's executor](https://console.cloud.google.com/vertex-ai/workbench/list/executions). "
"Since the Chicago Taxi Trips dataset is continuously updating, one can preform the same kind of analysis and model training every time a new set of data is available. The date range can also be increased from a week to a month or more depending on the quality of the data. Most of the steps followed in this notebook would still be valid and can be applied over the new data unless the data is too noisy. Perhaps, the notebook itself can be scheduled to run at the specified times to retrain the model using the scheduling option of [Vertex AI Workbench's executor](https://console.cloud.google.com/vertex-ai/workbench/list/executions). "
]
},
{
@@ -1676,24 +1287,11 @@
},
"source": [
"## Clean up\n",
"<a name=\"section-10\"></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",
"Delete the resources created in this notebook.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial:\n",
"\n",
"- Model\n",
"- Endpoint\n",
"- Cloud Storage Bucket"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f28a9843a13e"
},
"source": [
"Undeploy the model"
"Undeploy the model by specifying the `DEPLOYED_MODEL_ID`."
]
},
{
@@ -1704,7 +1302,7 @@
},
"outputs": [],
"source": [
"endpoint.undeploy_all()"
"endpoint.undeploy(deployed_model_id=DEPLOYED_MODEL_ID)"
]
},
{
@@ -1764,11 +1362,7 @@
},
"outputs": [],
"source": [
"# Set this to true only if you'd like to delete your bucket\n",
"delete_bucket = False\n",
"\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_URI"
"! gsutil -m rm -r $BUCKET_URI"
]
}
],

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,61 +1,10 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {
"id": "12cb1b47a1b7"
},
"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": "565d260c8eda"
},
"source": [
"<table align=\"left\">\n",
"\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/managed_notebooks/inventory-prediction/inventory_prediction.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/managed_notebooks/inventory-prediction/inventory_prediction.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/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",
" </td> \n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "20bc0b8473ae"
},
"source": [
"# Inventory prediction on ecommerce data using Vertex AI\n",
"\n",
@@ -130,177 +79,11 @@
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5d40975adb0b"
},
"source": [
"### Set up your local development environment\n",
"to generate a cost estimate based on your projected usage.\n",
"\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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "892ff77ab6b4"
},
"source": [
"**Otherwise**, make sure your environment meets this notebook's requirements.\n",
"You need the following:\n",
"## Before you begin\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": "0c522634d632"
},
"source": [
"### Install additional packages\n",
"\n",
"Install additional package dependencies not installed in your notebook environment, such as {XGBoost, AdaNet, or TensorFlow Hub TODO: Replace with relevant packages for the tutorial}. Use the latest major GA version of each package."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2b4ef9b72d43"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Google Cloud Notebook product has specific requirements\n",
"IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
"\n",
"# Google Cloud Notebook requires dependencies to be installed with '--user'\n",
"USER_FLAG = \"\"\n",
"if IS_GOOGLE_CLOUD_NOTEBOOK:\n",
" USER_FLAG = \"--user\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "a1edbc2cf821"
},
"outputs": [],
"source": [
"! pip install {USER_FLAG} --upgrade google-cloud-aiplatform \\\n",
" google-cloud-storage \\\n",
" seaborn \\\n",
" sklearn \\\n",
" pandas \\\n",
" fsspec \\\n",
" witwidget \\\n",
" pyarrow \\\n",
" gcsfs -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4257af853f7a"
},
"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": "d18017630513"
},
"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": {
"id": "013daf3de88e"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d1afc945645f"
},
"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). 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). {TODO: Update the APIs needed for your tutorial. Edit the API names, and update the link to append the API IDs, separating each one with a comma. For example, container.googleapis.com,cloudbuild.googleapis.com}\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": "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`."
]
@@ -345,17 +128,6 @@
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "30e64c0eda41"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -379,81 +151,6 @@
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "648aa9824ac6"
},
"source": [
"### Authenticate your Google Cloud account\n",
"\n",
"**If you are using Google Cloud Notebooks**, your environment is already\n",
"authenticated. Skip this step."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fc52bba17ee3"
},
"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": "535223fa4b84"
},
"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 Google Cloud Notebook product has specific requirements\n",
"IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
"\n",
"# If on Google Cloud Notebooks, then don't execute this code\n",
"if not IS_GOOGLE_CLOUD_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, 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": {
@@ -491,12 +188,10 @@
},
"outputs": [],
"source": [
"if BUCKET_URI == \"\" or BUCKET_URI is None or BUCKET_URI == \"gs://[your-bucket-name]\":\n",
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n",
" BUCKET_URI = \"gs://\" + BUCKET_NAME\n",
"\n",
"if REGION == \"[your-region]\":\n",
" REGION = \"us-central1\""
" BUCKET_URI = \"gs://\" + BUCKET_NAME"
]
},
{
@@ -516,7 +211,7 @@
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION $BUCKET_URI"
"! gsutil mb -l $REGION $BUCKET_NAME"
]
},
{
@@ -536,7 +231,7 @@
},
"outputs": [],
"source": [
"! gsutil ls -al $BUCKET_URI"
"! gsutil ls -al $BUCKET_NAME"
]
},
{
@@ -627,7 +322,7 @@
"source": [
"# The following two lines are only necessary to run once.\n",
"# Comment out otherwise for speed-up.\n",
"client = Client(project=PROJECT_ID)\n",
"client = Client()\n",
"\n",
"query = \"\"\"SELECT \n",
" id,\n",
@@ -1485,6 +1180,26 @@
"endpoint.list_models()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0566b8cbd2e8"
},
"source": [
"Note the `DEPLOYED_MODEL_ID` for deleting the deployment during clean up."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2c1f8add7fcb"
},
"outputs": [],
"source": [
"DEPLOYED_MODEL_ID = \"\""
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -1594,25 +1309,14 @@
"id": "d17d23fab0b1"
},
"source": [
"## Cleaning up\n",
"## Clean up\n",
"<a name=\"section-16\"></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",
"To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial:\n",
"\n",
"- Endpoint\n",
"- Model\n",
"- Cloud Storage Bucket"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "481638c98a10"
},
"source": [
"Undeploy the model"
"Undeploy the model."
]
},
{
@@ -1623,7 +1327,7 @@
},
"outputs": [],
"source": [
"endpoint.undeploy_all()"
"endpoint.undeploy(deployed_model_id=DEPLOYED_MODEL_ID)"
]
},
{
@@ -1683,11 +1387,7 @@
},
"outputs": [],
"source": [
"# Set this to true only if you'd like to delete your bucket\n",
"delete_bucket = False\n",
"\n",
"if delete_bucket or os.getenv(\"IS_TESTING\"):\n",
" ! gsutil -m rm -r $BUCKET_URI"
"! gsutil -m rm -r $BUCKET_URI"
]
}
],
@@ -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"
]
}
],
@@ -1,68 +1,16 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {
"id": "d1cc1c1fa076"
},
"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": "9751bc48dbcb"
},
"source": [
"# Analysis of pricing optimization on CDM Pricing Data\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/workbench/pricing_optimization/pricing-optimization.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/pricing_optimization/pricing-optimization.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/workbench/pricing_optimization/pricing-optimization.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": "cd1268747961"
},
"source": [
"# Pricing Optimization \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",
"* [Create a BigQuery dataset](#section-5)\n",
"* [Load the dataset from Cloud Storage](#section-6)\n",
@@ -71,41 +19,24 @@
"* [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"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8414ceb17c47"
},
"source": [
"* [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.*"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "71f69cfdff2b"
},
"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 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 objective of this notebook is to build a pricing optimization model using BigQuery ML. The following steps have been followed: \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",
"This tutorial uses the following Google Cloud ML services and resources:\n",
"## Objective\n",
"<a name=\"section-3\"></a>\n",
"\n",
"- Google Cloud Storage\n",
"- BigQuery\n",
"\n",
"\n",
"The steps performed include:\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",
@@ -113,27 +44,8 @@
"- 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"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d20422a5c34d"
},
"source": [
"## Dataset\n",
"<a name=\"section-3\"></a>\n",
"- Clean up.\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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c05bcd30859d"
},
"source": [
"## Costs\n",
"<a name=\"section-4\"></a>\n",
"\n",
@@ -148,121 +60,7 @@
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f5494c42606e"
},
"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": "2bed1491312f"
},
"source": [
"### Install additional packages\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1fd00fa70a2a"
},
"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": "25fffcad67f0"
},
"outputs": [],
"source": [
"! pip3 install {USER_FLAG} --upgrade pandas-gbq 'google-cloud-bigquery[bqstorage,pandas]' seaborn fsspec gcsfs -q\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d3a26cb9b19d"
},
"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": "c1464805870e"
},
"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)"
"to generate a cost estimate based on your projected usage.\n"
]
},
{
@@ -273,25 +71,6 @@
"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, Cloud Storage, and Compute Engine APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage-component.googleapis.com). \n",
"\n",
"1. [Configure your Google Cloud project for Vertex Pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/configure-project).\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.\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`."
@@ -305,139 +84,36 @@
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
"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,
"cell_type": "markdown",
"metadata": {
"id": "750bf2883c2d"
},
"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)"
"Otherwise, set your project ID here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "30e64c0eda41"
"id": "3c6db1ca88b9"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0e5ca6c89ab7"
},
"source": [
"#### UUID\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.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1105933b5528"
},
"outputs": [],
"source": [
"import random\n",
"import string\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": "67a2b5ee4efb"
},
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e44201253746"
},
"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": "505a908f1d0e"
},
"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 ''"
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
" PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
@@ -464,15 +140,6 @@
"from google.cloud.bigquery import Client"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3d5ff24d3194"
},
"source": [
"#### Set the BigQuery dataset ID and table ID"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -481,10 +148,8 @@
},
"outputs": [],
"source": [
"DATASET = \"pricing_optimization\" + \"_\" + UUID # set the BigQuery dataset-id\n",
"TRAINING_DATA_TABLE = (\n",
" \"training_data_table\" # set the BigQuery table-id to store the training data\n",
")"
"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"
]
},
{
@@ -497,15 +162,6 @@
"<a name=\"section-5\"></a>\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3a063f530682"
},
"source": [
"If you are using ***Vertex AI Workbench managed notebooks instance***, every 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."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -515,44 +171,12 @@
"#@bigquery\n",
"-- create a dataset in BigQuery\n",
"\n",
"CREATE SCHEMA [your-dataset-id]\n",
"CREATE SCHEMA pricing_optimization\n",
"OPTIONS(\n",
" location=\"us\"\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "00bd69008c92"
},
"outputs": [],
"source": [
"# Construct a BigQuery client object.\n",
"client = Client(project=PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5f7acd204413"
},
"outputs": [],
"source": [
"query = \"\"\"\n",
"CREATE SCHEMA {DATASET}\n",
"OPTIONS(\n",
" location=\"us\"\n",
" )\n",
"\"\"\".format(\n",
" DATASET=DATASET\n",
")\n",
"query_job = client.query(query)\n",
"print(query_job.result())"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -583,7 +207,7 @@
"id": "7b98d5f09842"
},
"source": [
"You 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",
"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",
@@ -597,7 +221,7 @@
"\n",
"First, explore the data and distributions.\n",
"\n",
"#### Select the required columns from the dataframe."
"Select the required columns from the dataframe."
]
},
{
@@ -623,7 +247,7 @@
"id": "3d780043ee5b"
},
"source": [
"#### Check the column types and null values in the dataframe."
"Check the column types and null values in the dataframe."
]
},
{
@@ -645,7 +269,7 @@
"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."
"Change the type of the date field to datetime."
]
},
{
@@ -665,7 +289,7 @@
"id": "fb4778578064"
},
"source": [
"#### Plot the distributions for the categorical fields."
"Plot the distributions for the categorical fields."
]
},
{
@@ -688,7 +312,7 @@
"id": "145deed255e0"
},
"source": [
"#### Plot the distributions for the numerical fields."
"Plot the distributions for the numerical fields."
]
},
{
@@ -714,7 +338,7 @@
"id": "f9b9c2e58380"
},
"source": [
"#### Check the maximum date and minimum date in Fiscal_Date column."
"Check the maximum date and minimum date in Fiscal_Date column."
]
},
{
@@ -735,7 +359,7 @@
"id": "4834f63e2e59"
},
"source": [
"#### Check the product distribution across each category."
"Check the product distribution across each category."
]
},
{
@@ -757,7 +381,7 @@
"id": "01ed02b9c8fd"
},
"source": [
"#### Check the percentage changes in the orders based on the percentage changes in the price."
"Check the percentage changes in the orders based on the percentage changes in the price."
]
},
{
@@ -833,7 +457,7 @@
"## Preprocess the data for training\n",
"<a name=\"section-8\"></a>\n",
"\n",
"#### Check which `Product_ID`'s have the maximum orders."
"Check which `Product_ID`'s have the maximum orders."
]
},
{
@@ -877,7 +501,7 @@
"id": "2dbc0d64d157"
},
"source": [
"#### Check the various prices available for these `Product_ID`s."
"Check the various prices available for these `Product_ID`s."
]
},
{
@@ -919,9 +543,9 @@
"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 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",
"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."
"Join the data for all the `Product_ID`s into one dataframe and remove duplicate records."
]
},
{
@@ -955,7 +579,7 @@
"id": "add5063df368"
},
"source": [
"#### Save the data to a BigQuery table."
"Save the data to a BigQuery table."
]
},
{
@@ -991,7 +615,7 @@
" \"{}.{}.{}\".format(PROJECT_ID, DATASET, TRAINING_DATA_TABLE),\n",
" job_config=job_config,\n",
") # Make an API request.\n",
"print(job.result()) # Wait for the job to complete."
"job.result() # Wait for the job to complete."
]
},
{
@@ -1013,7 +637,7 @@
},
"source": [
"#@bigquery\n",
"create or replace model [your-dataset-id].bqml_arima\n",
"create or replace model pricing_optimization.bqml_arima\n",
"options\n",
" (model_type = 'ARIMA_PLUS',\n",
" time_series_timestamp_col = 'Fiscal_Date',\n",
@@ -1025,35 +649,7 @@
" Concat(Product_ID,\"_\" ,Cast(List_Price_Converged as string)) as ID,\n",
" Invoiced_quantity_in_Pieces\n",
"from\n",
" [your-dataset-id].TRAINING_DATA\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e25254d219b7"
},
"outputs": [],
"source": [
"query = \"\"\"\n",
"create or replace model `{PROJECT_ID}.{DATASET}.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",
" `{DATASET}.{TRAINING_DATA_TABLE}`\"\"\".format(\n",
" PROJECT_ID=PROJECT_ID, DATASET=DATASET, TRAINING_DATA_TABLE=TRAINING_DATA_TABLE\n",
")\n",
"query_job = client.query(query)\n",
"print(query_job.result())"
" pricing_optimization.TRAINING_DATA\n"
]
},
{
@@ -1076,6 +672,8 @@
},
"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",
@@ -1084,13 +682,11 @@
" SELECT\n",
" *\n",
" FROM \n",
" ML.FORECAST(MODEL {DATASET}.bqml_arima, \n",
" ML.FORECAST(MODEL pricing_optimization.bqml_arima, \n",
" STRUCT(%s AS horizon, \n",
" %s AS confidence_level)\n",
" )\n",
" \"\"\",HORIZON,CONFIDENCE_LEVEL)'''.format(\n",
" DATASET=DATASET\n",
")\n",
" \"\"\",HORIZON,CONFIDENCE_LEVEL)'''\n",
"job = client.query(query)\n",
"dfforecast = job.to_dataframe()\n",
"dfforecast.head()"
@@ -1105,7 +701,7 @@
"## Interpret the results to choose the best price\n",
"<a name=\"section-11\"></a>\n",
"\n",
"#### Calculate average forecast values for the forecast duration."
"Calculate average forecast values for the forecast duration."
]
},
{
@@ -1127,7 +723,7 @@
"id": "5ce395d652a3"
},
"source": [
"#### Extract the ID and Price fields from the ID field."
"Extract the ID and Price fields from the ID field."
]
},
{
@@ -1148,7 +744,7 @@
"id": "3cee67f4028f"
},
"source": [
"#### Plot the average forecasted sales vs. the price of the product."
"Plot the average forecasted sales vs. the price of the product."
]
},
{
@@ -1177,15 +773,9 @@
"\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"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "01fdc73828af"
},
"source": [
"- SKU 62's price can be 4.23 units\n",
"\n",
"\n",
"## Clean Up\n",
"<a name=\"section-12\"></a>\n",
"\n",
@@ -1202,8 +792,11 @@
},
"outputs": [],
"source": [
"# Set dataset_id to the ID of the dataset to fetch.\n",
"dataset_id = \"{PROJECT_ID}.{DATASET}\".format(PROJECT_ID=PROJECT_ID, DATASET=DATASET)\n",
"# 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",
@@ -32,13 +32,13 @@
"<table align=\"left\">\n",
"\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",
" <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",
@@ -95,185 +95,13 @@
"id": "S5zc4kbEiYCm"
},
"source": [
"## Before you begin"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d1e95a984673"
},
"source": [
"### Set up your Google Cloud project\n",
"## Before you begin\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": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Your browser has been opened to visit:\n",
"\n",
" https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsqlservice.login+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=UY9jjYfhoSedWWUOWXp5Pmicq0Ic04&access_type=offline&code_challenge=OQefcewSwkT7ZwfzzOVidtngvZspdY1NgN6rltw8x7A&code_challenge_method=S256\n",
"\n"
]
}
],
"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": 1,
"metadata": {
"id": "beb72f394541"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Project ID: python-docs-samples-tests\n"
]
}
],
"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."
"* **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. The following section describes how to setup a VPC Peering connection if you don't have one. This is a one-time initial setup task. You can also reuse existing VPC network and skip this section.\n",
"* **WARNING:** The MatchingIndexEndpoint.match method (to create online queries against your deployed index) has to be executed in a Vertex AI Workbench notebook instance that is created with the following requirements:\n",
" * **In the same region as where your ANN service is deployed** (for example, if you set `REGION = \"us-central1\"` as same as the tutorial, the notebook instance has to be in `us-central1`).\n",
" * **Make sure you select the VPC network you created for ANN service** (instead of using the \"default\" one). That is, you will have to create the VPC network below and then create a new notebook instance that uses that VPC. \n",
" * If you run it in the colab or a Vertex AI Workbench notebook instance in a different VPC network or region, the gRPC API will fail to peer the network (InactiveRPCError)."
]
},
{
@@ -284,9 +112,11 @@
},
"outputs": [],
"source": [
"VPC_NETWORK = \"[your-vpc-network-name]\" # @param {type:\"string\"}\n",
"PROJECT_ID = \"<your_project_id>\" # @param {type:\"string\"}\n",
"\n",
"PEERING_RANGE_NAME = \"ann-haystack-range\""
"NETWORK_NAME = \"my-vpc-network\" # @param {type:\"string\"}\n",
"\n",
"PEERING_RANGE_NAME = \"my-haystack-range\""
]
},
{
@@ -297,28 +127,23 @@
},
"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",
"! gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com --network={NETWORK_NAME} --ranges={PEERING_RANGE_NAME} --project={PROJECT_ID}"
]
},
{
@@ -330,20 +155,6 @@
"* Authentication: Rerun the `gcloud auth login` command in the Vertex AI Workbench notebook terminal when you are logged out and need the credential again."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d5de53b31bf1"
},
"source": [
"## Make sure the following cells are run from inside the VPC network that you created in the previous step.\n",
"\n",
"* **WARNING:** The MatchingIndexEndpoint.match method (to create online queries against your deployed index) has to be executed in a Vertex AI Workbench notebook instance that is created with the following requirements:\n",
" * **In the same region as where your ANN service is deployed** (for example, if you set `REGION = \"us-central1\"` as same as the tutorial, the notebook instance has to be in `us-central1`).\n",
" * **Make sure you select the VPC network you created for ANN service** (instead of using the \"default\" one). That is, you will have to create the VPC network below and then create a new notebook instance that uses that VPC. \n",
" * If you run it in the colab or a Vertex AI Workbench notebook instance in a different VPC network or region, \"Create Online Queries\" section will fail."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -406,6 +217,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 +228,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 = \"\"\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 +320,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 +440,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 +515,6 @@
"import h5py"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "76f7b9ffde0b"
},
"source": [
"Use gcloud to retrieve the project number."
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -782,26 +734,6 @@
"INDEX_RESOURCE_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0f1a9fbecabb"
},
"source": [
"Using the resource name, you can retrieve an existing MatchingEngineIndex."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1ddb70647d98"
},
"outputs": [],
"source": [
"tree_ah_index = aiplatform.MatchingEngineIndex(index_name=INDEX_RESOURCE_NAME)"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -810,7 +742,7 @@
"source": [
"### Create Brute Force Index (for Ground Truth)\n",
"\n",
"The brute force index uses a naive brute force method to find the nearest neighbors. This method is not fast or efficient. Hence brute force indices are not recommended for production usage. They are to be used to find the \"ground truth\" set of neighbors, so that the \"ground truth\" set can be used to measure recall of the indices being tuned for production usage. To ensure an apples to apples comparison, the `distanceMeasureType` and `dimensions` of the brute force index should match those of the production indices being tuned.\n",
"The brute force index uses a naive brute force method to find the nearest neighbors. This method is not fast or efficient. Hence brute force indices are not recommended for production usage. They are to be used to find the \"ground truth\" set of neighbors, so that the \"ground truth\" set can be used to measure recall of the indices being tuned for production usage. To ensure an apples to apples comparison, the `distanceMeasureType` and `featureNormType`, `dimensions` of the brute force index should match those of the production indices being tuned.\n",
"\n",
"Create the brute force index configuration:"
]
@@ -845,19 +777,6 @@
"INDEX_BRUTE_FORCE_RESOURCE_NAME"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "865fcad494d7"
},
"outputs": [],
"source": [
"brute_force_index = aiplatform.MatchingEngineIndex(\n",
" index_name=INDEX_BRUTE_FORCE_RESOURCE_NAME\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -965,9 +884,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 +899,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 +941,7 @@
},
"outputs": [],
"source": [
"DEPLOYED_INDEX_ID = f\"tree_ah_glove_deployed_{RANDOM_ID}\""
"DEPLOYED_INDEX_ID = \"tree_ah_glove_deployed\""
]
},
{
@@ -1058,7 +976,7 @@
},
"outputs": [],
"source": [
"DEPLOYED_BRUTE_FORCE_INDEX_ID = f\"glove_brute_force_deployed_{RANDOM_ID}\""
"DEPLOYED_BRUTE_FORCE_INDEX_ID = \"glove_brute_force_deployed\""
]
},
{
@@ -1105,13 +1023,344 @@
"outputs": [],
"source": [
"# Test query\n",
"query = [\n",
" -0.11333,\n",
" 0.48402,\n",
" 0.090771,\n",
" -0.22439,\n",
" 0.034206,\n",
" -0.55831,\n",
" 0.041849,\n",
" -0.53573,\n",
" 0.18809,\n",
" -0.58722,\n",
" 0.015313,\n",
" -0.014555,\n",
" 0.80842,\n",
" -0.038519,\n",
" 0.75348,\n",
" 0.70502,\n",
" -0.17863,\n",
" 0.3222,\n",
" 0.67575,\n",
" 0.67198,\n",
" 0.26044,\n",
" 0.4187,\n",
" -0.34122,\n",
" 0.2286,\n",
" -0.53529,\n",
" 1.2582,\n",
" -0.091543,\n",
" 0.19716,\n",
" -0.037454,\n",
" -0.3336,\n",
" 0.31399,\n",
" 0.36488,\n",
" 0.71263,\n",
" 0.1307,\n",
" -0.24654,\n",
" -0.52445,\n",
" -0.036091,\n",
" 0.55068,\n",
" 0.10017,\n",
" 0.48095,\n",
" 0.71104,\n",
" -0.053462,\n",
" 0.22325,\n",
" 0.30917,\n",
" -0.39926,\n",
" 0.036634,\n",
" -0.35431,\n",
" -0.42795,\n",
" 0.46444,\n",
" 0.25586,\n",
" 0.68257,\n",
" -0.20821,\n",
" 0.38433,\n",
" 0.055773,\n",
" -0.2539,\n",
" -0.20804,\n",
" 0.52522,\n",
" -0.11399,\n",
" -0.3253,\n",
" -0.44104,\n",
" 0.17528,\n",
" 0.62255,\n",
" 0.50237,\n",
" -0.7607,\n",
" -0.071786,\n",
" 0.0080131,\n",
" -0.13286,\n",
" 0.50097,\n",
" 0.18824,\n",
" -0.54722,\n",
" -0.42664,\n",
" 0.4292,\n",
" 0.14877,\n",
" -0.0072514,\n",
" -0.16484,\n",
" -0.059798,\n",
" 0.9895,\n",
" -0.61738,\n",
" 0.054169,\n",
" 0.48424,\n",
" -0.35084,\n",
" -0.27053,\n",
" 0.37829,\n",
" 0.11503,\n",
" -0.39613,\n",
" 0.24266,\n",
" 0.39147,\n",
" -0.075256,\n",
" 0.65093,\n",
" -0.20822,\n",
" -0.17456,\n",
" 0.53571,\n",
" -0.16537,\n",
" 0.13582,\n",
" -0.56016,\n",
" 0.016964,\n",
" 0.1277,\n",
" 0.94071,\n",
" -0.22608,\n",
" -0.021106,\n",
"]\n",
"\n",
"response = my_index_endpoint.match(\n",
" deployed_index_id=DEPLOYED_INDEX_ID, queries=test[:1], num_neighbors=NUM_NEIGHBOURS\n",
" deployed_index_id=DEPLOYED_INDEX_ID, queries=[query], num_neighbors=NUM_NEIGHBOURS\n",
")\n",
"\n",
"response"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_mNwdU9_B_Ez"
},
"source": [
"### Batch Query\n",
"\n",
"You can run multiple queries in a single match call:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "A0XL0PJ1GoM9"
},
"outputs": [],
"source": [
"# Test query\n",
"queries = [\n",
" [\n",
" -0.11333,\n",
" 0.48402,\n",
" 0.090771,\n",
" -0.22439,\n",
" 0.034206,\n",
" -0.55831,\n",
" 0.041849,\n",
" -0.53573,\n",
" 0.18809,\n",
" -0.58722,\n",
" 0.015313,\n",
" -0.014555,\n",
" 0.80842,\n",
" -0.038519,\n",
" 0.75348,\n",
" 0.70502,\n",
" -0.17863,\n",
" 0.3222,\n",
" 0.67575,\n",
" 0.67198,\n",
" 0.26044,\n",
" 0.4187,\n",
" -0.34122,\n",
" 0.2286,\n",
" -0.53529,\n",
" 1.2582,\n",
" -0.091543,\n",
" 0.19716,\n",
" -0.037454,\n",
" -0.3336,\n",
" 0.31399,\n",
" 0.36488,\n",
" 0.71263,\n",
" 0.1307,\n",
" -0.24654,\n",
" -0.52445,\n",
" -0.036091,\n",
" 0.55068,\n",
" 0.10017,\n",
" 0.48095,\n",
" 0.71104,\n",
" -0.053462,\n",
" 0.22325,\n",
" 0.30917,\n",
" -0.39926,\n",
" 0.036634,\n",
" -0.35431,\n",
" -0.42795,\n",
" 0.46444,\n",
" 0.25586,\n",
" 0.68257,\n",
" -0.20821,\n",
" 0.38433,\n",
" 0.055773,\n",
" -0.2539,\n",
" -0.20804,\n",
" 0.52522,\n",
" -0.11399,\n",
" -0.3253,\n",
" -0.44104,\n",
" 0.17528,\n",
" 0.62255,\n",
" 0.50237,\n",
" -0.7607,\n",
" -0.071786,\n",
" 0.0080131,\n",
" -0.13286,\n",
" 0.50097,\n",
" 0.18824,\n",
" -0.54722,\n",
" -0.42664,\n",
" 0.4292,\n",
" 0.14877,\n",
" -0.0072514,\n",
" -0.16484,\n",
" -0.059798,\n",
" 0.9895,\n",
" -0.61738,\n",
" 0.054169,\n",
" 0.48424,\n",
" -0.35084,\n",
" -0.27053,\n",
" 0.37829,\n",
" 0.11503,\n",
" -0.39613,\n",
" 0.24266,\n",
" 0.39147,\n",
" -0.075256,\n",
" 0.65093,\n",
" -0.20822,\n",
" -0.17456,\n",
" 0.53571,\n",
" -0.16537,\n",
" 0.13582,\n",
" -0.56016,\n",
" 0.016964,\n",
" 0.1277,\n",
" 0.94071,\n",
" -0.22608,\n",
" -0.021106,\n",
" ],\n",
" [\n",
" -0.99544,\n",
" -2.3651,\n",
" -0.24332,\n",
" -1.0321,\n",
" 0.42052,\n",
" -1.1817,\n",
" -0.16451,\n",
" -1.683,\n",
" 0.49673,\n",
" -0.27258,\n",
" -0.025397,\n",
" 0.34188,\n",
" 1.5523,\n",
" 1.3532,\n",
" 0.33297,\n",
" -0.0056677,\n",
" -0.76525,\n",
" 0.49587,\n",
" 1.2211,\n",
" 0.83394,\n",
" -0.20031,\n",
" -0.59657,\n",
" 0.38485,\n",
" -0.23487,\n",
" -1.0725,\n",
" 0.95856,\n",
" 0.16161,\n",
" -1.2496,\n",
" 1.6751,\n",
" 0.73899,\n",
" 0.051347,\n",
" -0.42702,\n",
" 0.16257,\n",
" -0.16772,\n",
" 0.40146,\n",
" 0.29837,\n",
" 0.96204,\n",
" -0.36232,\n",
" -0.47848,\n",
" 0.78278,\n",
" 0.14834,\n",
" 1.3407,\n",
" 0.47834,\n",
" -0.39083,\n",
" -1.037,\n",
" -0.24643,\n",
" -0.75841,\n",
" 0.7669,\n",
" -0.37363,\n",
" 0.52741,\n",
" 0.018563,\n",
" -0.51301,\n",
" 0.97674,\n",
" 0.55232,\n",
" 1.1584,\n",
" 0.73715,\n",
" 1.3055,\n",
" -0.44743,\n",
" -0.15961,\n",
" 0.85006,\n",
" -0.34092,\n",
" -0.67667,\n",
" 0.2317,\n",
" 1.5582,\n",
" 1.2308,\n",
" -0.62213,\n",
" -0.032801,\n",
" 0.1206,\n",
" -0.25899,\n",
" -0.02756,\n",
" -0.52814,\n",
" -0.93523,\n",
" 0.58434,\n",
" -0.24799,\n",
" 0.37692,\n",
" 0.86527,\n",
" 0.069626,\n",
" 1.3096,\n",
" 0.29975,\n",
" -1.3651,\n",
" -0.32048,\n",
" -0.13741,\n",
" 0.33329,\n",
" -1.9113,\n",
" -0.60222,\n",
" -0.23921,\n",
" 0.12664,\n",
" -0.47961,\n",
" -0.89531,\n",
" 0.62054,\n",
" 0.40869,\n",
" -0.08503,\n",
" 0.6413,\n",
" -0.84044,\n",
" -0.74325,\n",
" -0.19426,\n",
" 0.098722,\n",
" 0.32648,\n",
" -0.67621,\n",
" -0.62692,\n",
" ],\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -1120,7 +1369,7 @@
"source": [
"### Compute Recall\n",
"\n",
"Use the deployed brute force Index as the ground truth to calculate the recall of ANN Index. Note that you can run multiple queries in a single match call."
"Use deployed brute force Index as the ground truth to calculate the recall of ANN Index:"
]
},
{
@@ -1153,20 +1402,18 @@
"outputs": [],
"source": [
"# Calculate recall by determining how many neighbors were correctly retrieved as compared to the brute-force option.\n",
"recalled_neighbors = 0\n",
"correct_neighbors = 0\n",
"for tree_ah_neighbors, brute_force_neighbors in zip(\n",
" tree_ah_response_test, brute_force_response_test\n",
"):\n",
" tree_ah_neighbor_ids = [neighbor.id for neighbor in tree_ah_neighbors]\n",
" brute_force_neighbor_ids = [neighbor.id for neighbor in brute_force_neighbors]\n",
"\n",
" recalled_neighbors += len(\n",
" correct_neighbors += len(\n",
" set(tree_ah_neighbor_ids).intersection(brute_force_neighbor_ids)\n",
" )\n",
"\n",
"recall = recalled_neighbors / len(\n",
" [neighbor for neighbors in brute_force_response_test for neighbor in neighbors]\n",
")\n",
"recall = correct_neighbors / (len(test) * NUM_NEIGHBOURS)\n",
"\n",
"print(\"Recall: {}\".format(recall))"
]
@@ -1205,8 +1452,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)"
]
}
],
+40 -44
View File
@@ -28,50 +28,11 @@ The first stage in MLOps is the collection and preparation for the purpose of de
### Get Started
[Get started with Vertex AI datasets](get_started_vertex_datasets.ipynb)
[Get Started with BQ datasets](get_started_bq_datasets.ipynb)
```
The steps performed include:
- Create a Vertex AI `Dataset` resource for:
- image data
- text data
- video data
- tabular data
- forecasting data
- Search `Dataset` resources using a filter.
- Read a sample of a `BigQuery` dataset into a dataframe.
- Generate statistics and data schema using TensorFlow Data Validation from the samples in the dataframe.
- 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 Dataflow](get_started_dataflow.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 an unlabelled Vertex AI AutoML text entity extraction dataset from pdfs using Vision API](get_started_with_visionapi_and_vertex_datasets.ipynb)
```
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`.
```
[Get started with BigQuery datasets](get_started_bq_datasets.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.
@@ -81,25 +42,59 @@ The steps performed include:
- Extract data from `BigQuery` table into a `DMatrix` -- compatible for custom training `XGBoost` models.
```
[Get started with Vertex AI data labeling](get_started_with_data_labeling.ipynb)
[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
- video data
- tabular data
- forecasting data
- Search `Dataset` resources using a filter.
- Read a sample of a `BigQuery` dataset into a dataframe.
- Generate statistics and data schema using TensorFlow Data Validation from the samples in the dataframe.
- 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 Dataflow](get_started_dataflow.ipynb)
```
The steps performed include:
- Offline preprocessing of data:
- Serially - w/o dataflow
- Parallel - with dataflow
- Upstream preprocessing of data:
- tabular data
- image data
```
[Get Started with Data Labeling](get_started_with_data_labeling.ipynb)
```
The steps performed include:
- Create a Specialist Pool for data labelers.
- Create a data labeling job.
- Submit the data labeling job.
- List data labeling jobs.
- Cancel a data labeling job.
```
### 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.
@@ -109,3 +104,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": {
@@ -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",
@@ -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": {
@@ -29,7 +29,7 @@
"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",
@@ -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"
]
@@ -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,
@@ -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."
]
},
{
"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": {
@@ -109,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": {
@@ -171,19 +154,18 @@
"\n",
"ONCE_ONLY = True\n",
"if ONCE_ONLY:\n",
" ! 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[tensorboard] $USER_FLAG -q\n",
" ! pip3 install --upgrade google-cloud-pipeline-components $USER_FLAG -q\n",
" ! pip3 install --upgrade google-cloud-bigquery $USER_FLAG -q\n",
" ! pip3 install --upgrade google-cloud-logging $USER_FLAG -q\n",
" ! pip3 install --upgrade apache-beam[gcp]==2.33.0 $USER_FLAG -q\n",
" ! pip3 install --upgrade pyarrow $USER_FLAG -q\n",
" ! pip3 install --upgrade cloudml-hypertune $USER_FLAG -q\n",
" ! pip3 install --upgrade kfp $USER_FLAG -q\n",
" ! pip3 install future $USER_FLAG -q"
" ! 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"
]
},
{
@@ -391,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",
@@ -666,7 +649,7 @@
},
"outputs": [],
"source": [
"bqclient = bigquery.Client(project=PROJECT_ID)"
"bqclient = bigquery.Client()"
]
},
{
@@ -789,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",
@@ -1234,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",
+146 -165
View File
@@ -35,144 +35,79 @@ The second stage in MLOps is experimenting in developing one or more baseline mo
### Get Started
[Get started with Vertex AI Training for Pytorch](get_started_vertex_training_pytorch.ipynb)
[Get Started with Vertex Experiments and Vertex ML Metadata](get_started_vertex_experiments.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.
- Create a Vertex AI `Experiment` resource.
- Instantiate an experiment run.
- Log parameters for the run.
- Log metrics for the run.
- Display the logged experiment run.
```
[Get Started with Vertex TensorBoard](get_started_vertex_tensorboard.ipynb)
```
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 Custom Training Packages (Tensorflow)](get_started_vertex_training.ipynb)
```
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 Custom Training Packages (Scikit-Learn)](get_started_vertex_training_sklearn.ipynb)
```
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 (XGBoost)](get_started_vertex_training_xgboost.ipynb)
```
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 prebuilt TFHub models](get_started_with_tfhub_models.ipynb)
[Get Started with Custom Training Packages (R)](get_started_vertex_training_r.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 TensorBoard](get_started_vertex_tensorboard.ipynb)
```
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 TabNet builtin algorithm for training tabular models](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 Vertex AI Vizier](get_started_vertex_vizier.ipynb)
```
The steps performed include:
- Hyperparameter tuning with Random algorithm.
- Hyperparameter tuning with Vizier (Bayesian) algorithm.
```
[Automl image classfication training with customer managed encryption keys (CMEK)](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 Vertex AI distributed training](get_started_vertex_distributed_training.ipynb)
```
The steps performed include:
- `MirroredStrategy`: Train on a single VM with multiple GPUs.
- `MultiWorkerMirroredStrategy`: Train on multiple VMs with automatic setup of replicas.
- `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 Vertex AI Training for scikit-learn](get_started_vertex_training_sklearn.ipynb)
```
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 Experiments](get_started_vertex_experiments.ipynb)
```
The steps performed include:
- Local (notebook) Training
- Create an experiment
- Create a first run in the experiment
- Log parameters and metrics
- Create artifact lineage
- Visualize the experiment results
- Execute a second run
- Compare the two runs in the experiment
- Cloud (`Vertex AI`) Training
- Within the training script:
- Create an experiment
- Log parameters and metrics
- Create artifact lineage
- Create a `Vertex AI Training` custom job
- Execute the custom job
- Visualize the experiment results
```
[Get started with Vertex AI Hyperparameter Tuning for XGBoost](get_started_vertex_hpt_xgboost.ipynb)
```
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 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 a Cloud Storage location.
- From a pandas DataFrame.
- Perform online serving from a `Featurestore` resource.
- Perform batch serving from a `Featurestore` resource.
```
[Get started with Vertex AI Training for 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.
@@ -184,32 +119,70 @@ The steps performed include:
- Train a R model using `Vertex AI Trainingh` service with the R-to-Python training package.
```
[Get started with logging](get_started_with_logging.ipynb)
[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:
- 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 Training for R using R Kernel](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` resouce.
- Create an `Endpoint` resource.
- Deploy the `Model` resource (trained R model) to the `Endpoint` resource.
- Make an online prediction.
```
[Get started with BigQuery ML training](get_started_bqml_training.ipynb)
[Get Started with Custom Training Packages (LightGBM)](get_started_vertex_training_lightgbm.ipynb)
```
The steps performed include:
- Training using a Python package.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Construct a FastAPI prediction server.
- Construct a Dockerfile deployment image.
- Test the deployment image locally.
- Create a `Vertex AI Model` resource.
```
[Get Started with Distributed Training](get_started_vertex_distributed_training.ipynb)
```
The steps performed include:
- `MirroredStrategy`: Train on a single VM with multiple GPUs.
- `MultiWorkerMirroredStrategy`: Train on multiple VMs with automatic setup of replicas.
- `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
@@ -217,59 +190,65 @@ The steps performed include:
- 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 AutoML training](get_started_automl_training.ipynb)
[Get Started with Vertex Feature Store](get_started_vertex_feature_store.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
- 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 Vertex AI Training for XGBoost](get_started_vertex_training_xgboost.ipynb)
[Get Started with Google CMEK Training](get_started_with_cmek_training.ipynb)
```
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.
- Creating a customer managed encryption key.
- Creating an image dataset with CMEK encryption.
- Train an AutoML model with CMEK encryption.
```
[Get started with Vertex AI Training](get_started_vertex_training.ipynb)
[Get Started with TensorFlow Hub models](get_started_with_tfhub_models.ipynb)
```
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.
- 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 Training for LightGBM](get_started_vertex_training_lightgbm.ipynb)
[Get Started with Vertex AI TabNet builtin algorithm](get_started_with_tabnet.ipynb)
```
The steps performed include:
- Training using a Python package.
- Save the model artifacts to Cloud Storage using GCSFuse.
- Construct a FastAPI prediction server.
- Construct a Dockerfile deployment image.
- Test the deployment image locally.
- Create a `Vertex AI Model` resource.
- 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 Vision API test preprocessing and AutoML text model generation](get_started_with_visionapi_and_automl.ipynb)
[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.
@@ -280,12 +259,14 @@ The steps performed include:
- Undeploy the `Model`.
```
### E2E Stage Example
[Stage 2: Experimentation](mlops_experimentation.ipynb)
```
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": {
@@ -104,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": {
@@ -217,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",
@@ -234,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`."
@@ -40,11 +40,11 @@
" </td>\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_bqml_training.ipynb\">\n",
" <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\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/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,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 BigQuery ML Training."
]
},
{
"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). This version of the dataset is used to predict the species of penguins from the available features like culmen-length, flipper-depth etc."
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -89,26 +100,8 @@
"- 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`"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dataset:penguins,lcn,bq"
},
"source": [
"### Dataset\n",
"- Automatically register a BQML model to `Vertex AI Model Registry`\n",
"\n",
"The dataset used for this tutorial is the Penguins dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). This version of the dataset is used to predict the species of penguins from the available features like culmen-length, flipper-depth etc."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "81c777b8ad32"
},
"source": [
"### 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`."
@@ -1225,7 +1209,7 @@
"\n",
"You need to set some additional IAM permissions for BigQuery ML to automatically upload and register the model after training. Depending on your service account, the setting of the permissions below may fail. In this case, we recommend executing the permissions in a Cloud Shell.\n",
"\n",
"Learn more about [Setting permissions for Model Registry](https://cloud.google.com/bigquery-ml/docs/managing-models-vertex)\n"
"Learn more about [Setting permissions for Model Registry](https://cloud.devsite.corp.google.com/bigquery-ml/docs/managing-models-vertex\n"
]
},
{
@@ -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\"}"
]
},
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 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
@@ -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",
@@ -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/tree/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",
@@ -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."
]
},
{
@@ -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."
]
},
@@ -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.sandbox.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 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"
]
},
{
"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",
@@ -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",
@@ -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."
]
},
{
@@ -123,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": {
@@ -187,7 +166,7 @@
"if IS_WORKBENCH_NOTEBOOK:\n",
" USER_FLAG = \"--user\"\n",
"\n",
"! pip3 install --upgrade google-cloud-aiplatform[tensorboard] $USER_FLAG -q"
"! pip3 install --upgrade google-cloud-aiplatform[tensorboard] $USER_FLAG"
]
},
{
@@ -237,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",
@@ -1296,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."
]
},
{
@@ -1309,9 +1287,7 @@
"outputs": [],
"source": [
"job = aip.CustomJob(\n",
" display_name=\"boston_\" + TIMESTAMP,\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",
")"
]
},
@@ -1444,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": {
@@ -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",
@@ -1,710 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "copyright"
},
"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": "title:generic,gcp"
},
"source": [
"# E2E ML on GCP: MLOps stage 2 : experimentation: get started with Logging\n",
"\n",
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage2/get_started_with_logging.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/community/ml_ops/stage2/get_started_with_logging.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/get_started_with_logging.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/>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "overview:mlops"
},
"source": [
"## 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 Logging."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "objective:mlops,stage2,get_started_vertex_experiments"
},
"source": [
"### Objective\n",
"\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",
"- `Cloud Logging`\n",
"\n",
"The steps performed include:\n",
"\n",
"- Use Python logging to log training configuration/results locally.\n",
"- Use Google Cloud Logging to log training configuration/results in cloud storage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "recommendation:mlops,stage2,logging"
},
"source": [
"### Recommendations\n",
"\n",
"When doing E2E MLOps on Google Cloud, the following are some of the best practices for logging data when experimenting or formally training a model.\n",
"\n",
"#### Python Logging\n",
"\n",
"Use Python's logging package when doing ad-hoc training locally.\n",
"\n",
"#### Cloud Logging\n",
"\n",
"Use `Google Cloud Logging` when doing training on the cloud.\n",
"\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",
"\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",
"- Vertex AI\n",
"\n",
"Learn about [Vertex AI pricing](https://cloud.google.com/vertex-ai/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": {
"id": "install_mlops"
},
"source": [
"## Installations\n",
"\n",
"Install the following packages for executing this notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "install_mlops"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# The Vertex AI Workbench Notebook product has specific requirements\n",
"IS_WORKBENCH_NOTEBOOK = os.getenv(\"DL_ANACONDA_HOME\") and not os.getenv(\"VIRTUAL_ENV\")\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 --upgrade google-cloud-logging $USER_FLAG -q"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "restart"
},
"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": "restart"
},
"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": "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",
"\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, Compute Engine, Cloud Storage and Cloud Logging APIs](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage_component,logging).\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",
"\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": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"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)"
]
},
{
"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",
"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)."
]
},
{
"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": "f3bd8c0d0469"
},
"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": "e0953a00668e"
},
"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": {
"id": "setup_vars"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_aip:mbsdk"
},
"outputs": [],
"source": [
"import logging\n",
"\n",
"import google.cloud.aiplatform as aiplatform"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "init_aip:mbsdk,region"
},
"source": [
"### Initialize Vertex AI SDK for Python\n",
"\n",
"Initialize the Vertex AI SDK for Python for your project and corresponding bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "init_aip:mbsdk,region"
},
"outputs": [],
"source": [
"aiplatform.init(project=PROJECT_ID, location=REGION)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "python_logging"
},
"source": [
"## Python Logging\n",
"\n",
"The Python logging package is widely used for logging within Python scripts. Commonly used features:\n",
"\n",
"- Set logging levels.\n",
"- Send log output to console.\n",
"- Send log output to a file.\n",
"\n",
"### Logging Levels in Python Logging\n",
"\n",
"The logging levels in order (from least to highest) and each level inclusive of the previous level are :\n",
"\n",
"1. Informational\n",
"2. Warnings\n",
"3. Errors\n",
"4. Debugging\n",
"\n",
"By default, the logging level is set to error level.\n",
"\n",
"### Logging output to console\n",
"\n",
"By default, the Python logging package outputs to the console. Note, in the example the debug log message is not outputted since the default logging level is set to error."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "python_logging"
},
"outputs": [],
"source": [
"def logging_examples():\n",
" logging.info(\"Model training started...\")\n",
" logging.warning(\"Using older version of package ...\")\n",
" logging.error(\"Training was terminated ...\")\n",
" logging.debug(\"Hyperparameters were ...\")\n",
"\n",
"\n",
"logging_examples()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "python_logging_level"
},
"source": [
"### Setting logging level\n",
"\n",
"To set the logging level, you get the logging handler using `getLogger()`. You can have multiple logging handles. When `getLogger()` is called without any arguments, it gets the default handler named ROOT. With the handler, you set the logging level with the method `setLevel()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "python_logging_level"
},
"outputs": [],
"source": [
"logging.getLogger().setLevel(logging.DEBUG)\n",
"\n",
"logging_examples()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "python_logging_remove"
},
"source": [
"### Clearing handlers\n",
"\n",
"At times, you may desire to reconfigure your logging. A common practice in this case is to first remove all existing logging handles for a fresh start."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "python_logging_remove"
},
"outputs": [],
"source": [
"for handler in logging.root.handlers[:]:\n",
" logging.root.removeHandler(handler)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "python_logging_file"
},
"source": [
"### Output to a local file\n",
"\n",
"You can preserve your logging output to a file that is local to where the Python script is running with the method `BasicConfig()`, that takes the following parameters:\n",
"\n",
"- `filename`: The file path to the local file to write the log output to.\n",
"- `level`: Sets the level of logging that is written to the logging file.\n",
"\n",
"*Note:* You cannot use a Cloud Storage bucket as the output file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "python_logging_file"
},
"outputs": [],
"source": [
"logging.basicConfig(filename=\"mylog.log\", level=logging.DEBUG)\n",
"\n",
"logging_examples()\n",
"\n",
"! cat mylog.log"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cloud_logging"
},
"source": [
"## Logging with Google Cloud Logging\n",
"\n",
"You can preserve and retrieve your logging output to `Google Cloud Logging` service. Commonly used features:\n",
"\n",
"- Set logging levels.\n",
"- Send log output to storage.\n",
"- Retrieve log output from storage.\n",
"\n",
"### Logging Levels in Cloud Logging\n",
"\n",
"The logging levels in order (from least to highest) are, with each level inclusive of the previous level:\n",
"\n",
"1. Informational\n",
"2. Warnings\n",
"3. Errors\n",
"4. Debugging\n",
"\n",
"By default, the logging level is set to warning level.\n",
"\n",
"### Configurable and storing log data.\n",
"\n",
"To use the `Google Cloud Logging` service, you do the following steps:\n",
"\n",
"1. Create a client to the service.\n",
"2. Obtain a handler for the service.\n",
"3. Create a logger instance and set logging level.\n",
"4. Attach logger instance to the service.\n",
"\n",
"Learn more about [Logging client libraries](https://cloud.google.com/logging/docs/reference/libraries)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cloud_logging"
},
"outputs": [],
"source": [
"import google.cloud.logging\n",
"from google.cloud.logging.handlers import CloudLoggingHandler\n",
"\n",
"# Connect to the Cloud Logging service\n",
"cl_client = google.cloud.logging.Client(project=PROJECT_ID)\n",
"handler = CloudLoggingHandler(cl_client, name=\"mylog\")\n",
"\n",
"# Create a logger instance and logging level\n",
"cloud_logger = logging.getLogger(\"cloudLogger\")\n",
"cloud_logger.setLevel(logging.INFO)\n",
"\n",
"# Attach the logger instance to the service.\n",
"cloud_logger.addHandler(handler)\n",
"\n",
"# Log something\n",
"cloud_logger.error(\"bad news\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cloud_logging_write"
},
"source": [
"### Logging output\n",
"\n",
"Logging output at specific levels is identical to Python logging with respect to method and method names. The only difference is that you use your instance of the cloud logger in place of logging."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cloud_logging_write"
},
"outputs": [],
"source": [
"cloud_logger.info(\"Model training started...\")\n",
"cloud_logger.warning(\"Using older version of package ...\")\n",
"cloud_logger.error(\"Training was terminated ...\")\n",
"cloud_logger.debug(\"Hyperparameters were ...\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cloud_logging_list"
},
"source": [
"### Get logging entries\n",
"\n",
"To get the logged output, you:\n",
"\n",
"1. Retrieve the log handle to the service.\n",
"2. Using the handle, call the method `list_entries()`.\n",
"3. Iterate through the entries."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cloud_logging_list"
},
"outputs": [],
"source": [
"logger = cl_client.logger(\"mylog\")\n",
"\n",
"for entry in logger.list_entries():\n",
" timestamp = entry.timestamp.isoformat()\n",
" print(\"* {}: {}: {}\".format(timestamp, entry.severity, entry.payload))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cleanup:mbsdk"
},
"source": [
"# Cleaning up\n",
"\n",
"To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial."
]
}
],
"metadata": {
"colab": {
"name": "get_started_with_logging.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -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 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": {
@@ -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,
@@ -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."
]
},
{
"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": {
@@ -149,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": {
@@ -216,20 +194,20 @@
"\n",
"ONCE_ONLY = False\n",
"if ONCE_ONLY:\n",
" ! 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[tensorboard] $USER_FLAG -q\n",
" ! pip3 install --upgrade google-cloud-pipeline-components $USER_FLAG -q\n",
" ! pip3 install --upgrade google-cloud-bigquery $USER_FLAG -q\n",
" ! pip3 install --upgrade google-cloud-logging $USER_FLAG -q\n",
" ! pip3 install --upgrade apache-beam[gcp] $USER_FLAG -q\n",
" ! pip3 install --upgrade pyarrow $USER_FLAG -q\n",
" ! pip3 install --upgrade cloudml-hypertune $USER_FLAG -q\n",
" ! pip3 install --upgrade kfp $USER_FLAG -q\n",
" ! pip3 install --upgrade torchvision $USER_FLAG -q\n",
" ! pip3 install --upgrade rpy2 $USER_FLAG -q"
" ! 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"
]
},
{
@@ -279,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",
+85 -114
View File
@@ -33,60 +33,79 @@ The third stage in MLOps is formalization to develop an automated pipeline proce
### Get Started
[Get started with AutoML Tabular Pipeline Workflows](get_started_with_automl_tabular_pipeline_workflow.ipynb)
[Get Started with Kubeflow pipelines](get_started_with_kubeflow_pipelines.ipynb)
```
The steps performed include:
- Define training specification.
- Dataset specification
- Hyperparameter overide specification
- machine specifications
- Construct tabular workflow pipeline.
- Compile and execute pipeline.
- View evaluation metrics artifact.
- Export AutoML model as an OSS TF model.
- Create `Endpoint` resource.
- Deploy exported OSS TF model.
- Make a prediction.
- Building KFP lightweight Python function components.
- Assembling and compiling KFP components into a pipeline.
- Executing a KFP pipeline using Vertex AI Pipelines.
- 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 Model Registry](get_started_with_model_registry.ipynb)
[Get Started with BQ and TFDV components](get_started_with_bq_tfdv_pipeline_components.ipynb)
```
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.
- 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 Dataproc serverless pipeline components](get_started_with_dataproc_serverless_pipeline_components.ipynb)
[Get Started with Dataflow components](get_started_with_dataflow_pipeline_components.ipynb)
```
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.
- 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 TFX pipelines](get_started_with_tfx_pipeline.ipynb)
[Get Started with Dataproc components](get_started_with_dataproc_pipeline_components.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`.
- 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 Hyperparameter Tuning pipeline components](get_started_with_hpt_pipeline_components.ipynb)
[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:
- Training a Vertex AI custom trained model.
- Test the serving binary with a batch prediction job.
- Deploying a Vertex AI custom trained model.
- Execute a Vertex AI pipeline.
```
[Get Started with Vertex AI Hyperparameter Tuning components](get_started_with_hpt_pipeline_components.ipynb)
```
The steps performed include:
- Construct a pipeline for:
- Hyperparameter tune/train a custom model.
- Retrieve the tuned hyperparameter values and metrics to optimize.
@@ -94,95 +113,13 @@ 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 Apache Airflow and Vertex AI Pipelines](get_started_with_airflow_and_vertex_pipelines.ipynb)
[Get Started with BQML components](get_started_with_bqml_pipeline_components.ipynb)
```
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 Vertex AI custom training pipeline components](get_started_with_custom_training_pipeline_components.ipynb)
```
The steps performed include:
- Construct a pipeline for:
- Training a Vertex AI custom trained model.
- 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 AutoML pipeline 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 Kubeflow pipelines](get_started_with_kubeflow_pipelines.ipynb)
```
The steps performed include:
- Building KFP lightweight Python function components.
- Assembling and compiling KFP components into a pipeline.
- Executing a KFP pipeline using Vertex AI Pipelines.
- Loading component and pipeline definitions from a source code repository.
- Building sequential, parallel, multiple output components.
- Building control flow into pipelines.
```
[Get started with machine management for Vertex AI Pipelines](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 component into a `Vertex AI CustomJob`.
- Execute pipeline using customjob-level settings for machine resources
```
[Get started with BigQuery and TFDV pipeline components](get_started_with_bq_tfdv_pipeline_components.ipynb)
```
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 pipeline 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 BigQuery ML pipeline components](get_started_with_bqml_pipeline_components.ipynb)
```
The steps performed include:
- Construct a pipeline for:
- Training BigQuery ML model.
- Evaluating the BigQuery ML model.
@@ -193,10 +130,12 @@ The steps performed include:
- Make a prediction with the deployed Vertex AI model.
```
[Get started with rapid prototyping with AutoML and BigQuery ML](get_started_with_rapid_prototyping_bqml_automl.ipynb)
[Get Started with rapid prototyping with BQML and AutoML components](get_started_with_rapid_prototyping_bqml_automl.ipynb)
```
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.
@@ -205,6 +144,38 @@ The steps performed include:
- 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`.
```
### E2E Stage Example
@@ -212,6 +183,7 @@ The steps performed include:
```
The steps performed include:
- Obtain resources from the experimentation stage.
- Baseline model.
- Dataset schema/statistics for baseline model.
@@ -224,4 +196,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",
@@ -759,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",
@@ -989,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",
@@ -1000,9 +988,10 @@
" from google.auth.transport.requests import Request\n",
" from google.oauth2 import id_token\n",
"\n",
" IAM_SCOPE = \"https://www.googleapis.com/auth/iam\"\n",
" OAUTH_TOKEN_URI = \"https://www.googleapis.com/oauth2/v4/token\"\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",
@@ -1019,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",
@@ -1039,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",
@@ -1050,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]"
]
},
@@ -1114,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)"
@@ -1141,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",
@@ -1161,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",
" )"
]
},
@@ -1192,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",
@@ -1233,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",
@@ -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