Files
model_garden/notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb
T
8275ea6c49 fix: correct the download_url (#923)
* fix: correct the download_url

* fix: fixed formatting issue

Co-authored-by: Andrew Ferlitsch <aferlitsch@google.com>
2022-09-02 17:04:42 -04:00

62 KiB

In [ ]:
# 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.

Training a TensorFlow model on BigQuery data

Colab logo Run in Colab GitHub logo View on GitHub Vertex AI logo Open in Vertex AI Workbench

Overview

This tutorial demonstrates how to use the Vertex AI SDK for Python to train and deploy a custom tabular classification model for online prediction.

Objective

In this notebook, you create a custom-trained model from a Python script in a Docker container using the Vertex AI SDK for Python, and then get a prediction from the deployed model by sending data. Alternatively, you can create custom-trained models using gcloud command-line tool, or online using the Cloud Console.

This tutorial uses the following Google Cloud ML services and resources:

  • BigQuery
  • Cloud Storage
  • Vertex AI managed Datasets
  • Vertex AI Training
  • Vertex AI Endpoints

The steps performed include:

  • Create a Vertex AI custom TrainingPipeline for training a model.
  • Train a TensorFlow model.
  • Deploy the Model resource to a serving Endpoint resource.
  • Make a prediction.
  • Undeploy the Model resource.

Dataset

The dataset used for this tutorial is the penguins dataset from BigQuery public datasets. For this tutorial, you use only the fields culmen_length_mm, culmen_depth_mm, flipper_length_mm, body_mass_g from the dataset to predict the penguins species (species).

Costs

This tutorial uses billable components of Google Cloud:

  • Vertex AI
  • Cloud Storage
  • BigQuery

Learn about Vertex AI pricing, Cloud Storage pricing, BigQuery pricing and use the Pricing Calculator to generate a cost estimate based on your projected usage.

Set up your local development environment

If you are using Colab or Vertex AI Workbench Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step.

Otherwise, make sure your environment meets this notebook's requirements. You need the following:

  • The Google Cloud SDK
  • Git
  • Python 3
  • virtualenv
  • Jupyter notebook running in a virtual environment with Python 3

The Google Cloud guide to Setting up a Python development environment and the Jupyter installation guide provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:

  1. Install and initialize the Cloud SDK.

  2. Install Python 3.

  3. Install virtualenv and create a virtual environment that uses Python 3. Activate the virtual environment.

  4. To install Jupyter, run pip3 install jupyter on the command-line in a terminal shell.

  5. To launch Jupyter, run jupyter notebook on the command-line in a terminal shell.

  6. Open this notebook in the Jupyter Notebook Dashboard.

Installation

Install the latest version of Cloud Storage, Bigquery and Vertex AI SDKs for Python.

In [ ]:
import os

# The Vertex AI Workbench Notebook product has specific requirements
IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME")
IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(
    "/opt/deeplearning/metadata/env_version"
)

# Vertex AI Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_WORKBENCH_NOTEBOOK:
    USER_FLAG = "--user"

# Install the packages
! pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform \
                                    google-cloud-storage \
                                    google-cloud-bigquery \
                                    pyarrow -q

Restart the kernel

Once you've installed everything, you need to restart the notebook kernel so it can find the packages.

In [ ]:
import os

if not os.getenv("IS_TESTING"):
    # Automatically restart kernel after installs
    import IPython

    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)

Before you begin

Set up your Google Cloud project

The following steps are required, regardless of your notebook environment.

  1. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.

  2. Make sure that billing is enabled for your project.

  3. Enable the Vertex AI API.

  4. If you are running this notebook locally, you need to install the Cloud SDK.

  5. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook.

Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.

Set your project ID

If you don't know your project ID, you might be able to get your project ID using gcloud.

In [ ]:
PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
In [ ]:
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
    # Get your GCP project id from gcloud
    shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null
    PROJECT_ID = shell_output[0]
    print("Project ID:", PROJECT_ID)
In [ ]:
! gcloud config set project $PROJECT_ID

Region

You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.

  • Americas: us-central1
  • Europe: europe-west4
  • Asia Pacific: asia-east1

You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.

Learn more about Vertex AI regions.

In [ ]:
REGION = "[your-region]"  # @param {type: "string"}

if REGION == "[your-region]":
    REGION = "us-central1"

UUID

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.

In [ ]:
import random
import string


# Generate a uuid of length 8
def generate_uuid():
    return "".join(random.choices(string.ascii_lowercase + string.digits, k=8))


UUID = generate_uuid()

Authenticate your Google Cloud account

If you are using Vertex AI Workbench Notebooks, your environment is already authenticated. Skip this step.

If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.

Otherwise, follow these steps:

  1. In the Cloud Console, go to the Create service account key page.

  2. Click Create service account.

  3. In the Service account name field, enter a name, and click Create.

  4. 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.

  5. Click Create. A JSON file that contains your key downloads to your local environment.

  6. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.

In [ ]:
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.

import os
import sys

# If on Vertex AI Workbench, then don't execute this code
IS_COLAB = "google.colab" in sys.modules
if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv(
    "DL_ANACONDA_HOME"
):
    if "google.colab" in sys.modules:
        from google.colab import auth as google_auth

        google_auth.authenticate_user()

    # If you are running this notebook locally, replace the string below with the
    # path to your service account key and run this cell to authenticate your GCP
    # account.
    elif not os.getenv("IS_TESTING"):
        %env GOOGLE_APPLICATION_CREDENTIALS ''

Create a Cloud Storage bucket

The following steps are required, regardless of your notebook environment.

When you submit a training job using the Cloud SDK, you upload a Python package containing your training code to a Cloud Storage bucket. Vertex AI runs the code from this package. In this tutorial, Vertex AI also saves the trained model that results from your job in the same bucket. Using this model artifact, you can then create Vertex AI model and endpoint resources in order to serve online predictions.

Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.

In [ ]:
BUCKET_NAME = "[your-bucket-name]"  # @param {type:"string"}
BUCKET_URI = f"gs://{BUCKET_NAME}"
In [ ]:
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
    BUCKET_NAME = PROJECT_ID + "aip-" + UUID
    BUCKET_URI = f"gs://{BUCKET_NAME}"

Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.

In [ ]:
! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI

Finally, validate access to your Cloud Storage bucket by examining its contents:

In [ ]:
! gsutil ls -al $BUCKET_URI

Import libraries

In [ ]:
import json
import os
import sys

import numpy as np
from google.cloud import aiplatform, bigquery

Initialize Vertex AI SDK for Python

Initialize the Vertex AI SDK for Python for your project and corresponding bucket.

In [ ]:
# Initialize the Vertex AI SDK
aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)

Initialize BigQuery Client

Initialize the BigQuery Python client for your project.

In [ ]:
# Set up BigQuery client
bqclient = bigquery.Client(project=PROJECT_ID)

Set hardware accelerators

You can set hardware accelerators for both training and prediction.

Set the variables TRAIN_GPU/TRAIN_NGPU and DEPLOY_GPU/DEPLOY_NGPU to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Tesla K80 GPUs allocated to each VM, you would specify:

(aip.AcceleratorType.NVIDIA_TESLA_K80, 4)

See the locations where accelerators are available.

Otherwise specify (None, None) to use a container image to run on a CPU.

Learn which accelerators are available in your region.

In [ ]:
TRAIN_GPU, TRAIN_NGPU = (aiplatform.gapic.AcceleratorType.NVIDIA_TESLA_K80, 1)

DEPLOY_GPU, DEPLOY_NGPU = (aiplatform.gapic.AcceleratorType.NVIDIA_TESLA_K80, 1)

Set pre-built containers

Vertex AI provides pre-built containers to run training and prediction.

For the latest list, see Pre-built containers for training and Pre-built containers for prediction

In [ ]:
TRAIN_VERSION = "tf-gpu.2-8"
DEPLOY_VERSION = "tf2-gpu.2-8"

TRAIN_IMAGE = "us-docker.pkg.dev/vertex-ai/training/{}:latest".format(TRAIN_VERSION)
DEPLOY_IMAGE = "us-docker.pkg.dev/vertex-ai/prediction/{}:latest".format(DEPLOY_VERSION)

print("Training:", TRAIN_IMAGE, TRAIN_GPU, TRAIN_NGPU)
print("Deployment:", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU)

Set machine types

Next, set the machine types to use for training and prediction.

  • Set the variables TRAIN_COMPUTE and DEPLOY_COMPUTE to configure your compute resources for training and prediction.
  • machine type
    • n1-standard: 3.75GB of memory per vCPU
    • n1-highmem: 6.5GB of memory per vCPU
    • n1-highcpu: 0.9 GB of memory per vCPU
  • vCPUs: number of [2, 4, 8, 16, 32, 64, 96 ]

Note: The following is not supported for training:

  • standard: 2 vCPUs
  • highcpu: 2, 4 and 8 vCPUs

Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs.

Learn which machine types are available for training and which machine types are available for prediction

In [ ]:
MACHINE_TYPE = "n1-standard"

VCPU = "4"
TRAIN_COMPUTE = MACHINE_TYPE + "-" + VCPU
print("Train machine type", TRAIN_COMPUTE)

MACHINE_TYPE = "n1-standard"

VCPU = "4"
DEPLOY_COMPUTE = MACHINE_TYPE + "-" + VCPU
print("Deploy machine type", DEPLOY_COMPUTE)

Prepare the data

To improve the convergence of the custom deep learning model, normalize the data. To prepare for this, calculate the mean and standard deviation for each numeric column.

Pass these summary statistics to the training script to normalize the data before training. Later, during prediction, use these summary statistics again to normalize the testing data.

In [ ]:
# Calculate mean and std across all rows

# Define the BigQuery source dataset
BQ_SOURCE = "bq://bigquery-public-data.ml_datasets.penguins"

# Define NA values
NA_VALUES = ["NA", "."]

# Download a table


def download_table(bq_table_uri: str):
    # Remove bq:// prefix if present
    prefix = "bq://"
    if bq_table_uri.startswith(prefix):
        bq_table_uri = bq_table_uri[len(prefix) :]

    table = bigquery.TableReference.from_string(bq_table_uri)
    rows = bqclient.list_rows(
        table,
    )
    return rows.to_dataframe()


# Remove NA values
def clean_dataframe(df):
    return df.replace(to_replace=NA_VALUES, value=np.NaN).dropna()


def calculate_mean_and_std(df):
    # Calculate mean and std for each applicable column
    mean_and_std = {}
    dtypes = list(zip(df.dtypes.index, map(str, df.dtypes)))
    # Normalize numeric columns.
    for column, dtype in dtypes:
        if dtype == "float32" or dtype == "float64":
            mean_and_std[column] = {
                "mean": df[column].mean(),
                "std": df[column].std(),
            }

    return mean_and_std


dataframe = download_table(BQ_SOURCE)
dataframe = clean_dataframe(dataframe)
mean_and_std = calculate_mean_and_std(dataframe)

print("The mean and stds for each column are: " + str(mean_and_std))

# Write to a file
MEAN_AND_STD_JSON_FILE = "mean_and_std.json"

with open(MEAN_AND_STD_JSON_FILE, "w") as outfile:
    json.dump(mean_and_std, outfile)

# Save to the staging bucket
! gsutil cp {MEAN_AND_STD_JSON_FILE} {BUCKET_URI}

Create a Vertex AI Tabular Dataset from BigQuery dataset

Your first step in training the model is to create a Vertex AI tabular dataset resource.

In [ ]:
dataset = aiplatform.TabularDataset.create(
    display_name="sample-penguins", bq_source=BQ_SOURCE
)

Train a model

There are two ways you can train a model using a container image:

  • Use a Vertex AI pre-built container. If you use a pre-built training container, you must additionally specify a Python package to install into the container image. This Python package contains your training code.

  • Use your own custom container image. If you use your own container, the container image must contain your training code.

Define the command args for the training script

Prepare the command-line arguments to pass to your training script.

  • args: The command line arguments to pass to the corresponding Python module. In this example, they are:
    • "--epochs=" + EPOCHS: The number of epochs for training.
    • "--batch_size=" + BATCH_SIZE: The number of batch size for training.
    • "--distribute=" + TRAIN_STRATEGY : The training distribution strategy to use for single or distributed training.
      • "single": single device.
      • "mirror": all GPU devices on a single compute instance.
      • "multi": all GPU devices on all compute instances.
    • "--mean_and_std_json_file=" + FILE_PATH: The file on Cloud Storage with pre-calculated means and standard deviations.
In [ ]:
JOB_NAME = "custom_job_" + UUID

if not TRAIN_NGPU or TRAIN_NGPU < 2:
    TRAIN_STRATEGY = "single"
else:
    TRAIN_STRATEGY = "mirror"

EPOCHS = 20
BATCH_SIZE = 10

CMDARGS = [
    "--epochs=" + str(EPOCHS),
    "--batch_size=" + str(BATCH_SIZE),
    "--distribute=" + TRAIN_STRATEGY,
    "--mean_and_std_json_file=" + f"{BUCKET_URI}/{MEAN_AND_STD_JSON_FILE}",
]

Training script

In the next cell, write the contents of the training script, task.py. In summary, the script does the following:

  • Loads the data from the BigQuery table using the BigQuery Python client library.
  • Loads the pre-calculated mean and standard deviation from the Cloud Storage bucket.
  • Builds a model using TF.Keras model API.
  • Compiles the model (compile()).
  • Sets a training distribution strategy according to the argument args.distribute.
  • Trains the model (fit()) with epochs and batch size according to the arguments args.epochs and args.batch_size
  • Gets the directory where to save the model artifacts from the environment variable AIP_MODEL_DIR. This variable is set by the training service.
  • Saves the trained model to the model directory.
In [ ]:
%%writefile task.py

import argparse
import tensorflow as tf
import numpy as np
import os

import pandas as pd
import tensorflow as tf

from google.cloud import bigquery
from google.cloud import storage

# Read environmental variables
training_data_uri = os.getenv("AIP_TRAINING_DATA_URI")
validation_data_uri = os.getenv("AIP_VALIDATION_DATA_URI")
test_data_uri = os.getenv("AIP_TEST_DATA_URI")

# Read args
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', dest='epochs',
                    default=10, type=int,
                    help='Number of epochs.')
parser.add_argument('--batch_size', dest='batch_size',
                    default=10, type=int,
                    help='Batch size.')
parser.add_argument('--distribute', dest='distribute', type=str, default='single',
                    help='Distributed training strategy.')
parser.add_argument('--mean_and_std_json_file', dest='mean_and_std_json_file', type=str,
                    help='GCS URI to the JSON file with pre-calculated column means and standard deviations.')
args = parser.parse_args()

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Construct a client side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
    # any content from Cloud Storage. As we don't need additional data,
    # using `Bucket.blob` is preferred here.
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )

def extract_bucket_and_prefix_from_gcs_path(gcs_path: str):
    """Given a complete GCS path, return the bucket name and prefix as a tuple.

    Example Usage:

        bucket, prefix = extract_bucket_and_prefix_from_gcs_path(
            "gs://example-bucket/path/to/folder"
        )

        # bucket = "example-bucket"
        # prefix = "path/to/folder"

    Args:
        gcs_path (str):
            Required. A full path to a Cloud Storage folder or resource.
            Can optionally include "gs://" prefix or end in a trailing slash "/".

    Returns:
        Tuple[str, Optional[str]]
            A (bucket, prefix) pair from provided GCS path. If a prefix is not
            present, None is returned in its place.
    """
    if gcs_path.startswith("gs://"):
        gcs_path = gcs_path[5:]
    if gcs_path.endswith("/"):
        gcs_path = gcs_path[:-1]

    gcs_parts = gcs_path.split("/", 1)
    gcs_bucket = gcs_parts[0]
    gcs_blob_prefix = None if len(gcs_parts) == 1 else gcs_parts[1]

    return (gcs_bucket, gcs_blob_prefix)

# Download means and std
def download_mean_and_std(mean_and_std_json_file):
    """Download mean and std for each column"""
    import json
    
    bucket, file_path = extract_bucket_and_prefix_from_gcs_path(mean_and_std_json_file)
    download_blob(bucket_name=bucket, source_blob_name=file_path, destination_file_name=file_path)
    
    with open(file_path, 'r') as file:
        return json.loads(file.read())
    
mean_and_std = download_mean_and_std(args.mean_and_std_json_file)

# Single Machine, single compute device
if args.distribute == 'single':
    if tf.test.is_gpu_available():
        strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0")
    else:
        strategy = tf.distribute.OneDeviceStrategy(device="/cpu:0")
# Single Machine, multiple compute device
elif args.distribute == 'mirror':
    strategy = tf.distribute.MirroredStrategy()
# Multiple Machine, multiple compute device
elif args.distribute == 'multi':
    strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()

# Set up training variables
LABEL_COLUMN = "species"
UNUSED_COLUMNS = []
NA_VALUES = ["NA", "."]

# Possible categorical values
SPECIES = ['Adelie Penguin (Pygoscelis adeliae)',
           'Chinstrap penguin (Pygoscelis antarctica)',
           'Gentoo penguin (Pygoscelis papua)']
ISLANDS = ['Dream', 'Biscoe', 'Torgersen']
SEXES = ['FEMALE', 'MALE']

# Set up BigQuery clients
bqclient = bigquery.Client()

# Download a table
def download_table(bq_table_uri: str):
    # Remove bq:// prefix if present
    prefix = "bq://"
    if bq_table_uri.startswith(prefix):
        bq_table_uri = bq_table_uri[len(prefix):]

    table = bigquery.TableReference.from_string(bq_table_uri)
    rows = bqclient.list_rows(
        table,
    )
    return rows.to_dataframe(create_bqstorage_client=False)


df_train = download_table(training_data_uri)
df_validation = download_table(validation_data_uri)
df_test = download_table(test_data_uri)

# Remove NA values
def clean_dataframe(df):
    return df.replace(to_replace=NA_VALUES, value=np.NaN).dropna()


df_train = clean_dataframe(df_train)
df_validation = clean_dataframe(df_validation)

_CATEGORICAL_TYPES = {
    "island": pd.api.types.CategoricalDtype(categories=ISLANDS),
    "species": pd.api.types.CategoricalDtype(categories=SPECIES),
    "sex": pd.api.types.CategoricalDtype(categories=SEXES),
}


def standardize(df, mean_and_std):
    """Scales numerical columns using their means and standard deviation to get
    z-scores: the mean of each numerical column becomes 0, and the standard
    deviation becomes 1. This can help the model converge during training.

    Args:
      df: Pandas df

    Returns:
      Input df with the numerical columns scaled to z-scores
    """
    dtypes = list(zip(df.dtypes.index, map(str, df.dtypes)))
    # Normalize numeric columns.
    for column, dtype in dtypes:
        if dtype == "float32":
            df[column] -= mean_and_std[column]["mean"]
            df[column] /= mean_and_std[column]["std"]
    return df

def preprocess(df):
    """Converts categorical features to numeric. Removes unused columns.

    Args:
      df: Pandas df with raw data

    Returns:
      df with preprocessed data
    """
    df = df.drop(columns=UNUSED_COLUMNS)

    # Drop rows with NaN's
    df = df.dropna()

    # Convert integer valued (numeric) columns to floating point
    numeric_columns = df.select_dtypes(["int32", "float32", "float64"]).columns
    df[numeric_columns] = df[numeric_columns].astype("float32")

    # Convert categorical columns to numeric
    cat_columns = df.select_dtypes(["object"]).columns

    df[cat_columns] = df[cat_columns].apply(
        lambda x: x.astype(_CATEGORICAL_TYPES[x.name])
    )
    df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
    return df


def convert_dataframe_to_dataset(
    df_train,
    df_validation,
    mean_and_std
):
    df_train = preprocess(df_train)
    df_validation = preprocess(df_validation)

    df_train_x, df_train_y = df_train, df_train.pop(LABEL_COLUMN)
    df_validation_x, df_validation_y = df_validation, df_validation.pop(LABEL_COLUMN)

    # Join train_x and eval_x to normalize on overall means and standard
    # deviations. Then separate them again.
    all_x = pd.concat([df_train_x, df_validation_x], keys=["train", "eval"])
    all_x = standardize(all_x, mean_and_std)
    df_train_x, df_validation_x = all_x.xs("train"), all_x.xs("eval")

    y_train = np.asarray(df_train_y).astype("float32")
    y_validation = np.asarray(df_validation_y).astype("float32")

    # Convert to numpy representation
    x_train = np.asarray(df_train_x)
    x_test = np.asarray(df_validation_x)

    # Convert to one-hot representation
    y_train = tf.keras.utils.to_categorical(y_train, num_classes=len(SPECIES))
    y_validation = tf.keras.utils.to_categorical(y_validation, num_classes=len(SPECIES))

    dataset_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
    dataset_validation = tf.data.Dataset.from_tensor_slices((x_test, y_validation))
    return (dataset_train, dataset_validation)

# Create datasets
dataset_train, dataset_validation = convert_dataframe_to_dataset(df_train, df_validation, mean_and_std)

# Shuffle train set
dataset_train = dataset_train.shuffle(len(df_train))

def create_model(num_features):
    # Create model
    Dense = tf.keras.layers.Dense
    model = tf.keras.Sequential(
        [
            Dense(
                100,
                activation=tf.nn.relu,
                kernel_initializer="uniform",
                input_dim=num_features,
            ),
            Dense(75, activation=tf.nn.relu),
            Dense(50, activation=tf.nn.relu),
            Dense(25, activation=tf.nn.relu),
            Dense(3, activation=tf.nn.softmax),
        ]
    )
    
    # Compile Keras model
    optimizer = tf.keras.optimizers.RMSprop(lr=0.001)
    model.compile(
        loss="categorical_crossentropy", metrics=["accuracy"], optimizer=optimizer
    )
    
    return model

# Create the model
with strategy.scope():
    model = create_model(num_features=dataset_train._flat_shapes[0].dims[0].value)

# Set up datasets
NUM_WORKERS = strategy.num_replicas_in_sync
# Here the batch size scales up by number of workers since
# `tf.data.Dataset.batch` expects the global batch size.
GLOBAL_BATCH_SIZE = args.batch_size * NUM_WORKERS
dataset_train = dataset_train.batch(GLOBAL_BATCH_SIZE)
dataset_validation = dataset_validation.batch(GLOBAL_BATCH_SIZE)

# Train the model
model.fit(dataset_train, epochs=args.epochs, validation_data=dataset_validation)

tf.saved_model.save(model, os.getenv("AIP_MODEL_DIR"))

df_test.head()

Train the model

Define your custom TrainingPipeline on Vertex AI.

Use the CustomTrainingJob class to define the TrainingPipeline. The class takes the following parameters:

  • display_name: The user-defined name of this training pipeline.
  • script_path: The local path to the training script.
  • container_uri: The URI of the training container image.
  • requirements: The list of Python package dependencies of the script.
  • model_serving_container_image_uri: The URI of a container that can serve predictions for your model — either a pre-built container or a custom container.

Use the run function to start training. The function takes the following parameters:

  • args: The command line arguments to be passed to the Python script.
  • replica_count: The number of worker replicas.
  • model_display_name: The display name of the Model if the script produces a managed Model.
  • machine_type: The type of machine to use for training.
  • accelerator_type: The hardware accelerator type.
  • accelerator_count: The number of accelerators to attach to a worker replica.

The run function creates a training pipeline that trains and creates a Model object. After the training pipeline completes, the run function returns the Model object.

In [ ]:
job = aiplatform.CustomTrainingJob(
    display_name=JOB_NAME,
    script_path="task.py",
    container_uri=TRAIN_IMAGE,
    requirements=["google-cloud-bigquery>=2.20.0", "db-dtypes"],
    model_serving_container_image_uri=DEPLOY_IMAGE,
)

MODEL_DISPLAY_NAME = "penguins-" + UUID

# Start the training
if TRAIN_GPU:
    model = job.run(
        dataset=dataset,
        model_display_name=MODEL_DISPLAY_NAME,
        bigquery_destination=f"bq://{PROJECT_ID}",
        args=CMDARGS,
        replica_count=1,
        machine_type=TRAIN_COMPUTE,
        accelerator_type=TRAIN_GPU.name,
        accelerator_count=TRAIN_NGPU,
    )
else:
    model = job.run(
        dataset=dataset,
        model_display_name=MODEL_DISPLAY_NAME,
        bigquery_destination=f"bq://{PROJECT_ID}",
        args=CMDARGS,
        replica_count=1,
        machine_type=TRAIN_COMPUTE,
        accelerator_count=0,
    )

Deploy the model

Before you use your model to make predictions, you must deploy it to an Endpoint. You can do this by calling the deploy function on the Model resource. This does two things:

  1. Create an Endpoint resource for deploying the Model resource to.
  2. Deploy the Model resource to the Endpoint resource.

The function takes the following parameters:

  • deployed_model_display_name: A human readable name for the deployed model.
  • traffic_split: Percent of traffic at the endpoint that goes to this model, which is specified as a dictionary of one or more key/value pairs.
    • If only one model, then specify { "0": 100 }, where "0" refers to this model being uploaded and 100 means 100% of the traffic.
    • If there are existing models on the endpoint, for which the traffic is split, then use model_id to specify { "0": percent, model_id: percent, ... }, where model_id is the ID of an existing DeployedModel on the endpoint. The percentages must add up to 100.
  • machine_type: The type of machine to use for training.
  • accelerator_type: The hardware accelerator type.
  • accelerator_count: The number of accelerators to attach to a worker replica.
  • starting_replica_count: The number of compute instances to initially provision.
  • max_replica_count: The maximum number of compute instances to scale to. In this tutorial, only one instance is provisioned.

Traffic split

The traffic_split parameter is specified as a Python dictionary. You can deploy more than one instance of your model to an endpoint, and then set the percentage of traffic that goes to each instance.

You can use a traffic split to introduce a new model gradually into production. For example, if you had one existing model in production with 100% of the traffic, you could deploy a new model to the same endpoint, direct 10% of traffic to it, and reduce the original model's traffic to 90%. This allows you to monitor the new model's performance while minimizing the distruption to the majority of users.

Compute instance scaling

You can specify a single instance (or node) to serve your online prediction requests. This tutorial uses a single node, so the variables MIN_NODES and MAX_NODES are both set to 1.

If you want to use multiple nodes to serve your online prediction requests, set MAX_NODES to the maximum number of nodes you want to use. Vertex AI autoscales the number of nodes used to serve your predictions, up to the maximum number you set. Refer to the pricing page to understand the costs of autoscaling with multiple nodes.

Endpoint

The deploy method waits until the model is deployed and eventually returns an Endpoint object. If this is the first time a model is deployed to the endpoint, it may take a few additional minutes to complete provisioning of resources.

In [ ]:
DEPLOYED_NAME = "penguins_deployed-" + UUID

TRAFFIC_SPLIT = {"0": 100}

MIN_NODES = 1
MAX_NODES = 1

if DEPLOY_GPU:
    endpoint = model.deploy(
        deployed_model_display_name=DEPLOYED_NAME,
        traffic_split=TRAFFIC_SPLIT,
        machine_type=DEPLOY_COMPUTE,
        accelerator_type=DEPLOY_GPU.name,
        accelerator_count=DEPLOY_NGPU,
        min_replica_count=MIN_NODES,
        max_replica_count=MAX_NODES,
    )
else:
    endpoint = model.deploy(
        deployed_model_display_name=DEPLOYED_NAME,
        traffic_split=TRAFFIC_SPLIT,
        machine_type=DEPLOY_COMPUTE,
        accelerator_type=DEPLOY_COMPUTE.name,
        accelerator_count=0,
        min_replica_count=MIN_NODES,
        max_replica_count=MAX_NODES,
    )

Make an online prediction request

Send an online prediction request to your deployed model.

Prepare test data

Prepare test data by normalizing it and converting categorical values to numeric values. You must normalize these values in the same way that your normalized training data.

In this example, perform testing with the same dataset that you used for training. In practice, you generally want to use a separate test dataset to verify your results.

In [ ]:
import pandas as pd
from google.cloud import bigquery

UNUSED_COLUMNS = []
LABEL_COLUMN = "species"

# Possible categorical values
SPECIES = [
    "Adelie Penguin (Pygoscelis adeliae)",
    "Chinstrap penguin (Pygoscelis antarctica)",
    "Gentoo penguin (Pygoscelis papua)",
]
ISLANDS = ["Dream", "Biscoe", "Torgersen"]
SEXES = ["FEMALE", "MALE"]

_CATEGORICAL_TYPES = {
    "island": pd.api.types.CategoricalDtype(categories=ISLANDS),
    "species": pd.api.types.CategoricalDtype(categories=SPECIES),
    "sex": pd.api.types.CategoricalDtype(categories=SEXES),
}


def standardize(df, mean_and_std):
    """Scales numerical columns using their means and standard deviation to get
    z-scores: the mean of each numerical column becomes 0, and the standard
    deviation becomes 1. This can help the model converge during training.

    Args:
      df: Pandas df

    Returns:
      Input df with the numerical columns scaled to z-scores
    """
    dtypes = list(zip(df.dtypes.index, map(str, df.dtypes)))
    # Normalize numeric columns.
    for column, dtype in dtypes:
        if dtype == "float32":
            df[column] -= mean_and_std[column]["mean"]
            df[column] /= mean_and_std[column]["std"]
    return df


def preprocess(df, mean_and_std):
    """Converts categorical features to numeric. Removes unused columns.

    Args:
      df: Pandas df with raw data

    Returns:
      df with preprocessed data
    """
    df = df.drop(columns=UNUSED_COLUMNS)

    # Drop rows with NaN's
    df = df.dropna()

    # Convert integer valued (numeric) columns to floating point
    numeric_columns = df.select_dtypes(["int32", "float32", "float64"]).columns
    df[numeric_columns] = df[numeric_columns].astype("float32")

    # Convert categorical columns to numeric
    cat_columns = df.select_dtypes(["object"]).columns

    df[cat_columns] = df[cat_columns].apply(
        lambda x: x.astype(_CATEGORICAL_TYPES[x.name])
    )
    df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
    return df


def convert_dataframe_to_list(df, mean_and_std):
    df = preprocess(df, mean_and_std)

    df_x, df_y = df, df.pop(LABEL_COLUMN)

    # Normalize on overall means and standard deviations.
    df = standardize(df, mean_and_std)

    y = np.asarray(df_y).astype("float32")

    # Convert to numpy representation
    x = np.asarray(df_x)

    # Convert to one-hot representation
    return x.tolist(), y.tolist()


x_test, y_test = convert_dataframe_to_list(dataframe, mean_and_std)

Send the prediction request

Now that you have test data, you can use it to send a prediction request. Use the Endpoint object's predict function, which takes the following parameters:

  • instances: A list of penguin measurement instances. According to your custom model, each instance should be an array of numbers. You prepared this list in the previous step.

The predict function returns a list, where each element in the list corresponds to the an instance in the request. In the output for each prediction, you see the following:

  • Confidence level for the prediction (predictions), between 0 and 1, for each of the ten classes.

You can then run a quick evaluation on the prediction results:

  1. np.argmax: Convert each list of confidence levels to a label
  2. Compare the predicted labels to the actual labels
  3. Calculate accuracy as correct/total
In [ ]:
predictions = endpoint.predict(instances=x_test)
y_predicted = np.argmax(predictions.predictions, axis=1)

correct = sum(y_predicted == np.array(y_test))
accuracy = len(y_predicted)
print(
    f"Correct predictions = {correct}, Total predictions = {accuracy}, Accuracy = {correct/accuracy}"
)

Undeploy the model

To undeploy your Model resource from the serving Endpoint resource, use the endpoint's undeploy method with the following parameter:

  • deployed_model_id: The model deployment identifier returned by the endpoint service when the Model resource was deployed. You can retrieve the deployed models using the endpoint's deployed_models property.

Since this is the only deployed model on the Endpoint resource, you can omit traffic_split.

In [ ]:
deployed_model_id = endpoint.list_models()[0].id
endpoint.undeploy(deployed_model_id=deployed_model_id)

Cleaning up

To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial.

Otherwise, you can delete the individual resources you created in this tutorial:

  • Training Job
  • Model
  • Endpoint
  • Cloud Storage Bucket
In [ ]:
# Warning: Setting this to true deletes everything in your bucket
delete_bucket = False

# Delete the training job
job.delete()

# Delete the model
model.delete()

# Delete the endpoint
endpoint.delete()

if delete_bucket or os.getenv("IS_TESTING"):
    ! gsutil rm -r $BUCKET_URI