<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Vertex SDK
Step1:  Install the Google cloud-storage library as well.
Step2:  Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.
Step3:  Before you begin
GPU run-time
Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU
Set up your GCP project
The following steps are required, regardless of your notebook environment.
Select or create a GCP project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex APIs and Compute Engine APIs.
Google Cloud SDK is already installed in Google Cloud Notebooks.
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
Step4:  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 when possible, to choose the region closest to you.
Americas
Step5:  Timestamp
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 onto the name of resources which will be created in this tutorial.
Step6:  Authenticate your GCP account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
Note
Step7:  Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
Step8:  Only if your bucket doesn't already exist
Step9:  Finally, validate access to your Cloud Storage bucket by examining its contents
Step10:  Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
Import Vertex SDK
Import the Vertex SDK into our Python environment.
Step11:  Vertex AI constants
Setup up the following constants for Vertex AI
Step12:  Clients
The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).
You will use several clients in this tutorial, so set them all up upfront.
Model Service for managed models.
Endpoint Service for deployment.
Job Service for batch jobs and custom training.
Prediction Service for serving.
Step13:  Prepare a trainer script
Package assembly
Step14:  Task.py contents
Step15:  Store training script on your Cloud Storage bucket
Step16:  Train a model
projects.locations.customJobs.create
Request
Step17:  Example output
Step18:  Response
Step19:  Example output
Step20:  projects.locations.customJobs.get
Call
Step21:  Response
Step22:  Example output
Step23:  Deploy the model
projects.locations.models.upload
Request
Step24:  Example output
Step25:  Response
Step26:  Example output
Step27:  Make batch predictions
Make a batch prediction file
Step28:  Example output
Step29:  Example output
Step30:  Response
Step31:  Example output
Step32:  projects.locations.batchPredictionJobs.get
Call
Step33:  Response
Step35:  Example output
Step36:  Example output
Step37:  Example output
Step38:  Response
Step39:  Example output
Step40:  projects.locations.endpoints.deployModel
Request
Step41:  Example output
Step42:  Response
Step43:  Example output
Step44:  projects.locations.endpoints.predict
Prepare file for online prediction
Step45:  Request
Step46:  Example output
Step47:  Response
Step48:  Example output
Step49:  Response
Step50:  Example output
<ASSISTANT_TASK:>
Python Code:
! pip3 install -U google-cloud-aiplatform --user
Explanation: Vertex SDK: Train and deploy an SKLearn model with pre-built containers (formerly hosted runtimes)
Installation
Install the latest (preview) version of Vertex SDK.
End of explanation
! pip3 install google-cloud-storage
Explanation: Install the Google cloud-storage library as well.
End of explanation
import os
if not os.getenv("AUTORUN"):
    # Automatically restart kernel after installs
    import IPython
    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)
Explanation: Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.
End of explanation
PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
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)
! gcloud config set project $PROJECT_ID
Explanation: Before you begin
GPU run-time
Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU
Set up your GCP project
The following steps are required, regardless of your notebook environment.
Select or create a GCP project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex APIs and Compute Engine APIs.
Google Cloud SDK is already installed in Google Cloud Notebooks.
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.
End of explanation
REGION = "us-central1"  # @param {type: "string"}
Explanation: 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 when possible, to choose the region closest to you.
Americas: us-central1
Europe: europe-west4
Asia Pacific: asia-east1
You cannot use a Multi-Regional Storage bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see Region support for Vertex AI services
End of explanation
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
Explanation: Timestamp
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 onto the name of resources which will be created in this tutorial.
End of explanation
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your Google Cloud account. This provides access
# to your Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# If on Vertex, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
    if "google.colab" in sys.modules:
        from google.colab import auth as google_auth
        google_auth.authenticate_user()
    # If you are running this tutorial in a notebook locally, replace the string
    # below with the path to your service account key and run this cell to
    # authenticate your Google Cloud account.
    else:
        %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json
    # Log in to your account on Google Cloud
    ! gcloud auth login
Explanation: Authenticate your GCP account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
Note: If you are on an Vertex notebook and run the cell, the cell knows to skip executing the authentication steps.
End of explanation
BUCKET_NAME = "[your-bucket-name]"  # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
    BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP
Explanation: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
End of explanation
! gsutil mb -l $REGION gs://$BUCKET_NAME
Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.
End of explanation
! gsutil ls -al gs://$BUCKET_NAME
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
import os
import sys
import time
from google.cloud.aiplatform import gapic as aip
from google.protobuf.json_format import MessageToJson, ParseDict
from google.protobuf.struct_pb2 import Struct, Value
Explanation: Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
Import Vertex SDK
Import the Vertex SDK into our Python environment.
End of explanation
# API Endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)
# Vertex AI location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION
Explanation: Vertex AI constants
Setup up the following constants for Vertex AI:
API_ENDPOINT: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.
PARENT: The Vertex AI location root path for dataset, model and endpoint resources.
End of explanation
# client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}
def create_model_client():
    client = aip.ModelServiceClient(client_options=client_options)
    return client
def create_endpoint_client():
    client = aip.EndpointServiceClient(client_options=client_options)
    return client
def create_prediction_client():
    client = aip.PredictionServiceClient(client_options=client_options)
    return client
def create_job_client():
    client = aip.JobServiceClient(client_options=client_options)
    return client
clients = {}
clients["model"] = create_model_client()
clients["endpoint"] = create_endpoint_client()
clients["prediction"] = create_prediction_client()
clients["job"] = create_job_client()
for client in clients.items():
    print(client)
Explanation: Clients
The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).
You will use several clients in this tutorial, so set them all up upfront.
Model Service for managed models.
Endpoint Service for deployment.
Job Service for batch jobs and custom training.
Prediction Service for serving.
End of explanation
# Make folder for python training script
! rm -rf custom
! mkdir custom
# Add package information
! touch custom/README.md
setup_cfg = "[egg_info]\n\
tag_build =\n\
tag_date = 0"
! echo "$setup_cfg" > custom/setup.cfg
setup_py = "import setuptools\n\
setuptools.setup(\n\
    install_requires=[\n\
    ],\n\
    packages=setuptools.find_packages())"
! echo "$setup_py" > custom/setup.py
pkg_info = "Metadata-Version: 1.0\n\
Name: Custom Census Income\n\
Version: 0.0.0\n\
Summary: Demonstration training script\n\
Home-page: www.google.com\n\
Author: Google\n\
Author-email: aferlitsch@google.com\n\
License: Public\n\
Description: Demo\n\
Platform: Vertex AI"
! echo "$pkg_info" > custom/PKG-INFO
# Make the training subfolder
! mkdir custom/trainer
! touch custom/trainer/__init__.py
Explanation: Prepare a trainer script
Package assembly
End of explanation
%%writefile custom/trainer/task.py
# Single Instance Training for Census Income
from sklearn.ensemble import RandomForestClassifier
import joblib
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import FeatureUnion
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import LabelBinarizer
import datetime
import pandas as pd
from google.cloud import storage
import numpy as np
import argparse
import os
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--model-dir', dest='model_dir',
                    default=os.getenv('AIP_MODEL_DIR'), type=str, help='Model dir.')
args = parser.parse_args()
print('Python Version = {}'.format(sys.version))
# Public bucket holding the census data
bucket = storage.Client().bucket('cloud-samples-data')
# Path to the data inside the public bucket
blob = bucket.blob('ai-platform/sklearn/census_data/adult.data')
# Download the data
blob.download_to_filename('adult.data')
# Define the format of your input data including unused columns (These are the columns from the census data files)
COLUMNS = (
    'age',
    'workclass',
    'fnlwgt',
    'education',
    'education-num',
    'marital-status',
    'occupation',
    'relationship',
    'race',
    'sex',
    'capital-gain',
    'capital-loss',
    'hours-per-week',
    'native-country',
    'income-level'
)
# Categorical columns are columns that need to be turned into a numerical value to be used by scikit-learn
CATEGORICAL_COLUMNS = (
    'workclass',
    'education',
    'marital-status',
    'occupation',
    'relationship',
    'race',
    'sex',
    'native-country'
)
# Load the training census dataset
with open('./adult.data', 'r') as train_data:
    raw_training_data = pd.read_csv(train_data, header=None, names=COLUMNS)
# Remove the column we are trying to predict ('income-level') from our features list
# Convert the Dataframe to a lists of lists
train_features = raw_training_data.drop('income-level', axis=1).values.tolist()
# Create our training labels list, convert the Dataframe to a lists of lists
train_labels = (raw_training_data['income-level'] == ' >50K').values.tolist()
# Since the census data set has categorical features, we need to convert
# them to numerical values. We'll use a list of pipelines to convert each
# categorical column and then use FeatureUnion to combine them before calling
# the RandomForestClassifier.
categorical_pipelines = []
# Each categorical column needs to be extracted individually and converted to a numerical value.
# To do this, each categorical column will use a pipeline that extracts one feature column via
# SelectKBest(k=1) and a LabelBinarizer() to convert the categorical value to a numerical one.
# A scores array (created below) will select and extract the feature column. The scores array is
# created by iterating over the COLUMNS and checking if it is a CATEGORICAL_COLUMN.
for i, col in enumerate(COLUMNS[:-1]):
    if col in CATEGORICAL_COLUMNS:
        # Create a scores array to get the individual categorical column.
        # Example:
        #  data = [39, 'State-gov', 77516, 'Bachelors', 13, 'Never-married', 'Adm-clerical',
        #         'Not-in-family', 'White', 'Male', 2174, 0, 40, 'United-States']
        #  scores = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        #
        # Returns: [['State-gov']]
        # Build the scores array.
        scores = [0] * len(COLUMNS[:-1])
        # This column is the categorical column we want to extract.
        scores[i] = 1
        skb = SelectKBest(k=1)
        skb.scores_ = scores
        # Convert the categorical column to a numerical value
        lbn = LabelBinarizer()
        r = skb.transform(train_features)
        lbn.fit(r)
        # Create the pipeline to extract the categorical feature
        categorical_pipelines.append(
            ('categorical-{}'.format(i), Pipeline([
                ('SKB-{}'.format(i), skb),
                ('LBN-{}'.format(i), lbn)])))
        
# Create pipeline to extract the numerical features
skb = SelectKBest(k=6)
# From COLUMNS use the features that are numerical
skb.scores_ = [1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0]
categorical_pipelines.append(('numerical', skb))
# Combine all the features using FeatureUnion
preprocess = FeatureUnion(categorical_pipelines)
# Create the classifier
classifier = RandomForestClassifier()
# Transform the features and fit them to the classifier
classifier.fit(preprocess.transform(train_features), train_labels)
# Create the overall model as a single pipeline
pipeline = Pipeline([
    ('union', preprocess),
    ('classifier', classifier)
])
# Split path into bucket and subdirectory
bucket = args.model_dir.split('/')[2]
subdir = args.model_dir.split('/')[-1]
# Write model to a local file
joblib.dump(pipeline, 'model.joblib')
# Upload the model to GCS
bucket = storage.Client().bucket(bucket)
blob = bucket.blob(subdir + '/model.joblib')
blob.upload_from_filename('model.joblib')
Explanation: Task.py contents
End of explanation
! rm -f custom.tar custom.tar.gz
! tar cvf custom.tar custom
! gzip custom.tar
! gsutil cp custom.tar.gz gs://$BUCKET_NAME/census.tar.gz
Explanation: Store training script on your Cloud Storage bucket
End of explanation
TRAIN_IMAGE = "gcr.io/cloud-aiplatform/training/scikit-learn-cpu.0-23:latest"
JOB_NAME = "custom_job_SKL" + TIMESTAMP
WORKER_POOL_SPEC = [
    {
        "replica_count": 1,
        "machine_spec": {"machine_type": "n1-standard-4"},
        "python_package_spec": {
            "executor_image_uri": TRAIN_IMAGE,
            "package_uris": ["gs://" + BUCKET_NAME + "/census.tar.gz"],
            "python_module": "trainer.task",
            "args": ["--model-dir=" + "gs://{}/{}".format(BUCKET_NAME, JOB_NAME)],
        },
    }
]
training_job = aip.CustomJob(
    display_name=JOB_NAME, job_spec={"worker_pool_specs": WORKER_POOL_SPEC}
)
print(
    MessageToJson(
        aip.CreateCustomJobRequest(parent=PARENT, custom_job=training_job).__dict__[
            "_pb"
        ]
    )
)
Explanation: Train a model
projects.locations.customJobs.create
Request
End of explanation
request = clients["job"].create_custom_job(parent=PARENT, custom_job=training_job)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "customJob": {
    "displayName": "custom_job_SKL20210323185534",
    "jobSpec": {
      "workerPoolSpecs": [
        {
          "machineSpec": {
            "machineType": "n1-standard-4"
          },
          "replicaCount": "1",
          "pythonPackageSpec": {
            "executorImageUri": "gcr.io/cloud-aiplatform/training/scikit-learn-cpu.0-23:latest",
            "packageUris": [
              "gs://migration-ucaip-trainingaip-20210323185534/census.tar.gz"
            ],
            "pythonModule": "trainer.task",
            "args": [
              "--model-dir=gs://migration-ucaip-trainingaip-20210323185534/custom_job_SKL20210323185534"
            ]
          }
        }
      ]
    }
  }
}
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
# The full unique ID for the custom training job
custom_training_id = request.name
# The short numeric ID for the custom training job
custom_training_short_id = custom_training_id.split("/")[-1]
print(custom_training_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/customJobs/3216493723709865984",
  "displayName": "custom_job_SKL20210323185534",
  "jobSpec": {
    "workerPoolSpecs": [
      {
        "machineSpec": {
          "machineType": "n1-standard-4"
        },
        "replicaCount": "1",
        "diskSpec": {
          "bootDiskType": "pd-ssd",
          "bootDiskSizeGb": 100
        },
        "pythonPackageSpec": {
          "executorImageUri": "gcr.io/cloud-aiplatform/training/scikit-learn-cpu.0-23:latest",
          "packageUris": [
            "gs://migration-ucaip-trainingaip-20210323185534/census.tar.gz"
          ],
          "pythonModule": "trainer.task",
          "args": [
            "--model-dir=gs://migration-ucaip-trainingaip-20210323185534/custom_job_SKL20210323185534"
          ]
        }
      }
    ]
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2021-03-23T18:55:41.688375Z",
  "updateTime": "2021-03-23T18:55:41.688375Z"
}
End of explanation
request = clients["job"].get_custom_job(name=custom_training_id)
Explanation: projects.locations.customJobs.get
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
while True:
    response = clients["job"].get_custom_job(name=custom_training_id)
    if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:
        print("Training job has not completed:", response.state)
        if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:
            break
    else:
        print("Training Time:", response.end_time - response.start_time)
        break
    time.sleep(60)
# model artifact output directory on Google Cloud Storage
model_artifact_dir = (
    response.job_spec.worker_pool_specs[0].python_package_spec.args[0].split("=")[-1]
)
print("artifact location  " + model_artifact_dir)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/customJobs/3216493723709865984",
  "displayName": "custom_job_SKL20210323185534",
  "jobSpec": {
    "workerPoolSpecs": [
      {
        "machineSpec": {
          "machineType": "n1-standard-4"
        },
        "replicaCount": "1",
        "diskSpec": {
          "bootDiskType": "pd-ssd",
          "bootDiskSizeGb": 100
        },
        "pythonPackageSpec": {
          "executorImageUri": "gcr.io/cloud-aiplatform/training/scikit-learn-cpu.0-23:latest",
          "packageUris": [
            "gs://migration-ucaip-trainingaip-20210323185534/census.tar.gz"
          ],
          "pythonModule": "trainer.task",
          "args": [
            "--model-dir=gs://migration-ucaip-trainingaip-20210323185534/custom_job_SKL20210323185534"
          ]
        }
      }
    ]
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2021-03-23T18:55:41.688375Z",
  "updateTime": "2021-03-23T18:55:41.688375Z"
}
End of explanation
DEPLOY_IMAGE = "gcr.io/cloud-aiplatform/prediction/sklearn-cpu.0-23:latest"
model = {
    "display_name": "custom_job_SKL" + TIMESTAMP,
    "artifact_uri": model_artifact_dir,
    "container_spec": {"image_uri": DEPLOY_IMAGE, "ports": [{"container_port": 8080}]},
}
print(MessageToJson(aip.UploadModelRequest(parent=PARENT, model=model).__dict__["_pb"]))
Explanation: Deploy the model
projects.locations.models.upload
Request
End of explanation
request = clients["model"].upload_model(parent=PARENT, model=model)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "model": {
    "displayName": "custom_job_SKL20210323185534",
    "containerSpec": {
      "imageUri": "gcr.io/cloud-aiplatform/prediction/sklearn-cpu.0-23:latest",
      "ports": [
        {
          "containerPort": 8080
        }
      ]
    },
    "artifactUri": "gs://migration-ucaip-trainingaip-20210323185534/custom_job_SKL20210323185534"
  }
}
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
model_id = result.model
Explanation: Example output:
{
  "model": "projects/116273516712/locations/us-central1/models/5984808915752189952"
}
End of explanation
import json
import tensorflow as tf
INSTANCES = [
    [
        25,
        "Private",
        226802,
        "11th",
        7,
        "Never-married",
        "Machine-op-inspct",
        "Own-child",
        "Black",
        "Male",
        0,
        0,
        40,
        "United-States",
    ],
    [
        38,
        "Private",
        89814,
        "HS-grad",
        9,
        "Married-civ-spouse",
        "Farming-fishing",
        "Husband",
        "White",
        "Male",
        0,
        0,
        50,
        "United-States",
    ],
    [
        28,
        "Local-gov",
        336951,
        "Assoc-acdm",
        12,
        "Married-civ-spouse",
        "Protective-serv",
        "Husband",
        "White",
        "Male",
        0,
        0,
        40,
        "United-States",
    ],
    [
        44,
        "Private",
        160323,
        "Some-college",
        10,
        "Married-civ-spouse",
        "Machine-op-inspct",
        "Husband",
        "Black",
        "Male",
        7688,
        0,
        40,
        "United-States",
    ],
    [
        18,
        "?",
        103497,
        "Some-college",
        10,
        "Never-married",
        "?",
        "Own-child",
        "White",
        "Female",
        0,
        0,
        30,
        "United-States",
    ],
    [
        34,
        "Private",
        198693,
        "10th",
        6,
        "Never-married",
        "Other-service",
        "Not-in-family",
        "White",
        "Male",
        0,
        0,
        30,
        "United-States",
    ],
    [
        29,
        "?",
        227026,
        "HS-grad",
        9,
        "Never-married",
        "?",
        "Unmarried",
        "Black",
        "Male",
        0,
        0,
        40,
        "United-States",
    ],
    [
        63,
        "Self-emp-not-inc",
        104626,
        "Prof-school",
        15,
        "Married-civ-spouse",
        "Prof-specialty",
        "Husband",
        "White",
        "Male",
        3103,
        0,
        32,
        "United-States",
    ],
    [
        24,
        "Private",
        369667,
        "Some-college",
        10,
        "Never-married",
        "Other-service",
        "Unmarried",
        "White",
        "Female",
        0,
        0,
        40,
        "United-States",
    ],
    [
        55,
        "Private",
        104996,
        "7th-8th",
        4,
        "Married-civ-spouse",
        "Craft-repair",
        "Husband",
        "White",
        "Male",
        0,
        0,
        10,
        "United-States",
    ],
]
gcs_input_uri = "gs://" + BUCKET_NAME + "/" + "test.jsonl"
with tf.io.gfile.GFile(gcs_input_uri, "w") as f:
    for i in INSTANCES:
        f.write(json.dumps(i) + "\n")
! gsutil cat $gcs_input_uri
Explanation: Make batch predictions
Make a batch prediction file
End of explanation
model_parameters = Value(
    struct_value=Struct(
        fields={
            "confidence_threshold": Value(number_value=0.5),
            "max_predictions": Value(number_value=10000.0),
        }
    )
)
batch_prediction_job = {
    "display_name": "custom_job_SKL" + TIMESTAMP,
    "model": model_id,
    "input_config": {
        "instances_format": "jsonl",
        "gcs_source": {"uris": [gcs_input_uri]},
    },
    "model_parameters": model_parameters,
    "output_config": {
        "predictions_format": "jsonl",
        "gcs_destination": {
            "output_uri_prefix": "gs://" + f"{BUCKET_NAME}/batch_output/"
        },
    },
    "dedicated_resources": {
        "machine_spec": {"machine_type": "n1-standard-2"},
        "starting_replica_count": 1,
        "max_replica_count": 1,
    },
}
print(
    MessageToJson(
        aip.CreateBatchPredictionJobRequest(
            parent=PARENT, batch_prediction_job=batch_prediction_job
        ).__dict__["_pb"]
    )
)
Explanation: Example output:
[25, "Private", 226802, "11th", 7, "Never-married", "Machine-op-inspct", "Own-child", "Black", "Male", 0, 0, 40, "United-States"]
[38, "Private", 89814, "HS-grad", 9, "Married-civ-spouse", "Farming-fishing", "Husband", "White", "Male", 0, 0, 50, "United-States"]
[28, "Local-gov", 336951, "Assoc-acdm", 12, "Married-civ-spouse", "Protective-serv", "Husband", "White", "Male", 0, 0, 40, "United-States"]
[44, "Private", 160323, "Some-college", 10, "Married-civ-spouse", "Machine-op-inspct", "Husband", "Black", "Male", 7688, 0, 40, "United-States"]
[18, "?", 103497, "Some-college", 10, "Never-married", "?", "Own-child", "White", "Female", 0, 0, 30, "United-States"]
[34, "Private", 198693, "10th", 6, "Never-married", "Other-service", "Not-in-family", "White", "Male", 0, 0, 30, "United-States"]
[29, "?", 227026, "HS-grad", 9, "Never-married", "?", "Unmarried", "Black", "Male", 0, 0, 40, "United-States"]
[63, "Self-emp-not-inc", 104626, "Prof-school", 15, "Married-civ-spouse", "Prof-specialty", "Husband", "White", "Male", 3103, 0, 32, "United-States"]
[24, "Private", 369667, "Some-college", 10, "Never-married", "Other-service", "Unmarried", "White", "Female", 0, 0, 40, "United-States"]
[55, "Private", 104996, "7th-8th", 4, "Married-civ-spouse", "Craft-repair", "Husband", "White", "Male", 0, 0, 10, "United-States"]
projects.locations.batchPredictionJobs.create
Request
End of explanation
request = clients["job"].create_batch_prediction_job(
    parent=PARENT, batch_prediction_job=batch_prediction_job
)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "batchPredictionJob": {
    "displayName": "custom_job_SKL20210323185534",
    "model": "projects/116273516712/locations/us-central1/models/5984808915752189952",
    "inputConfig": {
      "instancesFormat": "jsonl",
      "gcsSource": {
        "uris": [
          "gs://migration-ucaip-trainingaip-20210323185534/test.jsonl"
        ]
      }
    },
    "modelParameters": {
      "confidence_threshold": 0.5,
      "max_predictions": 10000.0
    },
    "outputConfig": {
      "predictionsFormat": "jsonl",
      "gcsDestination": {
        "outputUriPrefix": "gs://migration-ucaip-trainingaip-20210323185534/batch_output/"
      }
    },
    "dedicatedResources": {
      "machineSpec": {
        "machineType": "n1-standard-2"
      },
      "startingReplicaCount": 1,
      "maxReplicaCount": 1
    }
  }
}
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
# The fully qualified ID for the batch job
batch_job_id = request.name
# The short numeric ID for the batch job
batch_job_short_id = batch_job_id.split("/")[-1]
print(batch_job_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/batchPredictionJobs/2509428582212698112",
  "displayName": "custom_job_SKL20210323185534",
  "model": "projects/116273516712/locations/us-central1/models/5984808915752189952",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "gs://migration-ucaip-trainingaip-20210323185534/test.jsonl"
      ]
    }
  },
  "modelParameters": {
    "max_predictions": 10000.0,
    "confidence_threshold": 0.5
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "gs://migration-ucaip-trainingaip-20210323185534/batch_output/"
    }
  },
  "dedicatedResources": {
    "machineSpec": {
      "machineType": "n1-standard-2"
    },
    "startingReplicaCount": 1,
    "maxReplicaCount": 1
  },
  "manualBatchTuningParameters": {},
  "state": "JOB_STATE_PENDING",
  "createTime": "2021-03-23T19:05:07.344290Z",
  "updateTime": "2021-03-23T19:05:07.344290Z"
}
End of explanation
request = clients["job"].get_batch_prediction_job(name=batch_job_id)
Explanation: projects.locations.batchPredictionJobs.get
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
def get_latest_predictions(gcs_out_dir):
     Get the latest prediction subfolder using the timestamp in the subfolder name
    folders = !gsutil ls $gcs_out_dir
    latest = ""
    for folder in folders:
        subfolder = folder.split("/")[-2]
        if subfolder.startswith("prediction-"):
            if subfolder > latest:
                latest = folder[:-1]
    return latest
while True:
    response = clients["job"].get_batch_prediction_job(name=batch_job_id)
    if response.state != aip.JobState.JOB_STATE_SUCCEEDED:
        print("The job has not completed:", response.state)
        if response.state == aip.JobState.JOB_STATE_FAILED:
            break
    else:
        folder = get_latest_predictions(
            response.output_config.gcs_destination.output_uri_prefix
        )
        ! gsutil ls $folder/prediction*
        ! gsutil cat -h $folder/prediction*
        break
    time.sleep(60)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/batchPredictionJobs/2509428582212698112",
  "displayName": "custom_job_SKL20210323185534",
  "model": "projects/116273516712/locations/us-central1/models/5984808915752189952",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "gs://migration-ucaip-trainingaip-20210323185534/test.jsonl"
      ]
    }
  },
  "modelParameters": {
    "confidence_threshold": 0.5,
    "max_predictions": 10000.0
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "gs://migration-ucaip-trainingaip-20210323185534/batch_output/"
    }
  },
  "dedicatedResources": {
    "machineSpec": {
      "machineType": "n1-standard-2"
    },
    "startingReplicaCount": 1,
    "maxReplicaCount": 1
  },
  "manualBatchTuningParameters": {},
  "state": "JOB_STATE_PENDING",
  "createTime": "2021-03-23T19:05:07.344290Z",
  "updateTime": "2021-03-23T19:05:07.344290Z"
}
End of explanation
endpoint = {"display_name": "custom_job_SKL" + TIMESTAMP}
print(
    MessageToJson(
        aip.CreateEndpointRequest(parent=PARENT, endpoint=endpoint).__dict__["_pb"]
    )
)
Explanation: Example output:
```
==> gs://migration-ucaip-trainingaip-20210323185534/batch_output/prediction-custom_job_SKL20210323185534-2021_03_23T12_05_07_282Z/prediction.errors_stats-00000-of-00001 <==
==> gs://migration-ucaip-trainingaip-20210323185534/batch_output/prediction-custom_job_SKL20210323185534-2021_03_23T12_05_07_282Z/prediction.results-00000-of-00001 <==
{"instance": [25, "Private", 226802, "11th", 7, "Never-married", "Machine-op-inspct", "Own-child", "Black", "Male", 0, 0, 40, "United-States"], "prediction": false}
{"instance": [38, "Private", 89814, "HS-grad", 9, "Married-civ-spouse", "Farming-fishing", "Husband", "White", "Male", 0, 0, 50, "United-States"], "prediction": false}
{"instance": [28, "Local-gov", 336951, "Assoc-acdm", 12, "Married-civ-spouse", "Protective-serv", "Husband", "White", "Male", 0, 0, 40, "United-States"], "prediction": false}
{"instance": [44, "Private", 160323, "Some-college", 10, "Married-civ-spouse", "Machine-op-inspct", "Husband", "Black", "Male", 7688, 0, 40, "United-States"], "prediction": true}
{"instance": [18, "?", 103497, "Some-college", 10, "Never-married", "?", "Own-child", "White", "Female", 0, 0, 30, "United-States"], "prediction": false}
{"instance": [34, "Private", 198693, "10th", 6, "Never-married", "Other-service", "Not-in-family", "White", "Male", 0, 0, 30, "United-States"], "prediction": false}
{"instance": [29, "?", 227026, "HS-grad", 9, "Never-married", "?", "Unmarried", "Black", "Male", 0, 0, 40, "United-States"], "prediction": false}
{"instance": [63, "Self-emp-not-inc", 104626, "Prof-school", 15, "Married-civ-spouse", "Prof-specialty", "Husband", "White", "Male", 3103, 0, 32, "United-States"], "prediction": false}
{"instance": [24, "Private", 369667, "Some-college", 10, "Never-married", "Other-service", "Unmarried", "White", "Female", 0, 0, 40, "United-States"], "prediction": false}
{"instance": [55, "Private", 104996, "7th-8th", 4, "Married-civ-spouse", "Craft-repair", "Husband", "White", "Male", 0, 0, 10, "United-States"], "prediction": false}
```
Make online predictions
projects.locations.endpoints.create
Request
End of explanation
request = clients["endpoint"].create_endpoint(parent=PARENT, endpoint=endpoint)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "endpoint": {
    "displayName": "custom_job_SKL20210323185534"
  }
}
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
# The full unique ID for the endpoint
endpoint_id = result.name
# The short numeric ID for the endpoint
endpoint_short_id = endpoint_id.split("/")[-1]
print(endpoint_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/endpoints/695823734614786048"
}
End of explanation
deployed_model = {
    "model": model_id,
    "display_name": "custom_job_SKL" + TIMESTAMP,
    "dedicated_resources": {
        "min_replica_count": 1,
        "max_replica_count": 1,
        "machine_spec": {"machine_type": "n1-standard-4", "accelerator_count": 0},
    },
}
print(
    MessageToJson(
        aip.DeployModelRequest(
            endpoint=endpoint_id,
            deployed_model=deployed_model,
            traffic_split={"0": 100},
        ).__dict__["_pb"]
    )
)
Explanation: projects.locations.endpoints.deployModel
Request
End of explanation
request = clients["endpoint"].deploy_model(
    endpoint=endpoint_id, deployed_model=deployed_model, traffic_split={"0": 100}
)
Explanation: Example output:
{
  "endpoint": "projects/116273516712/locations/us-central1/endpoints/695823734614786048",
  "deployedModel": {
    "model": "projects/116273516712/locations/us-central1/models/5984808915752189952",
    "displayName": "custom_job_SKL20210323185534",
    "dedicatedResources": {
      "machineSpec": {
        "machineType": "n1-standard-4"
      },
      "minReplicaCount": 1,
      "maxReplicaCount": 1
    }
  },
  "trafficSplit": {
    "0": 100
  }
}
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
# The unique ID for the deployed model
deployed_model_id = result.deployed_model.id
print(deployed_model_id)
Explanation: Example output:
{
  "deployedModel": {
    "id": "6653241616695820288"
  }
}
End of explanation
INSTANCES = [
    [
        25,
        "Private",
        226802,
        "11th",
        7,
        "Never-married",
        "Machine-op-inspct",
        "Own-child",
        "Black",
        "Male",
        0,
        0,
        40,
        "United-States",
    ],
    [
        38,
        "Private",
        89814,
        "HS-grad",
        9,
        "Married-civ-spouse",
        "Farming-fishing",
        "Husband",
        "White",
        "Male",
        0,
        0,
        50,
        "United-States",
    ],
    [
        28,
        "Local-gov",
        336951,
        "Assoc-acdm",
        12,
        "Married-civ-spouse",
        "Protective-serv",
        "Husband",
        "White",
        "Male",
        0,
        0,
        40,
        "United-States",
    ],
    [
        44,
        "Private",
        160323,
        "Some-college",
        10,
        "Married-civ-spouse",
        "Machine-op-inspct",
        "Husband",
        "Black",
        "Male",
        7688,
        0,
        40,
        "United-States",
    ],
    [
        18,
        "?",
        103497,
        "Some-college",
        10,
        "Never-married",
        "?",
        "Own-child",
        "White",
        "Female",
        0,
        0,
        30,
        "United-States",
    ],
    [
        34,
        "Private",
        198693,
        "10th",
        6,
        "Never-married",
        "Other-service",
        "Not-in-family",
        "White",
        "Male",
        0,
        0,
        30,
        "United-States",
    ],
    [
        29,
        "?",
        227026,
        "HS-grad",
        9,
        "Never-married",
        "?",
        "Unmarried",
        "Black",
        "Male",
        0,
        0,
        40,
        "United-States",
    ],
    [
        63,
        "Self-emp-not-inc",
        104626,
        "Prof-school",
        15,
        "Married-civ-spouse",
        "Prof-specialty",
        "Husband",
        "White",
        "Male",
        3103,
        0,
        32,
        "United-States",
    ],
    [
        24,
        "Private",
        369667,
        "Some-college",
        10,
        "Never-married",
        "Other-service",
        "Unmarried",
        "White",
        "Female",
        0,
        0,
        40,
        "United-States",
    ],
    [
        55,
        "Private",
        104996,
        "7th-8th",
        4,
        "Married-civ-spouse",
        "Craft-repair",
        "Husband",
        "White",
        "Male",
        0,
        0,
        10,
        "United-States",
    ],
]
Explanation: projects.locations.endpoints.predict
Prepare file for online prediction
End of explanation
prediction_request = aip.PredictRequest(endpoint=endpoint_id)
prediction_request.instances.append(INSTANCES)
print(MessageToJson(prediction_request.__dict__["_pb"]))
Explanation: Request
End of explanation
request = clients["prediction"].predict(endpoint=endpoint_id, instances=INSTANCES)
Explanation: Example output:
{
  "endpoint": "projects/116273516712/locations/us-central1/endpoints/695823734614786048",
  "instances": [
    [
      [
        25.0,
        "Private",
        226802.0,
        "11th",
        7.0,
        "Never-married",
        "Machine-op-inspct",
        "Own-child",
        "Black",
        "Male",
        0.0,
        0.0,
        40.0,
        "United-States"
      ],
      [
        38.0,
        "Private",
        89814.0,
        "HS-grad",
        9.0,
        "Married-civ-spouse",
        "Farming-fishing",
        "Husband",
        "White",
        "Male",
        0.0,
        0.0,
        50.0,
        "United-States"
      ],
      [
        28.0,
        "Local-gov",
        336951.0,
        "Assoc-acdm",
        12.0,
        "Married-civ-spouse",
        "Protective-serv",
        "Husband",
        "White",
        "Male",
        0.0,
        0.0,
        40.0,
        "United-States"
      ],
      [
        44.0,
        "Private",
        160323.0,
        "Some-college",
        10.0,
        "Married-civ-spouse",
        "Machine-op-inspct",
        "Husband",
        "Black",
        "Male",
        7688.0,
        0.0,
        40.0,
        "United-States"
      ],
      [
        18.0,
        "?",
        103497.0,
        "Some-college",
        10.0,
        "Never-married",
        "?",
        "Own-child",
        "White",
        "Female",
        0.0,
        0.0,
        30.0,
        "United-States"
      ],
      [
        34.0,
        "Private",
        198693.0,
        "10th",
        6.0,
        "Never-married",
        "Other-service",
        "Not-in-family",
        "White",
        "Male",
        0.0,
        0.0,
        30.0,
        "United-States"
      ],
      [
        29.0,
        "?",
        227026.0,
        "HS-grad",
        9.0,
        "Never-married",
        "?",
        "Unmarried",
        "Black",
        "Male",
        0.0,
        0.0,
        40.0,
        "United-States"
      ],
      [
        63.0,
        "Self-emp-not-inc",
        104626.0,
        "Prof-school",
        15.0,
        "Married-civ-spouse",
        "Prof-specialty",
        "Husband",
        "White",
        "Male",
        3103.0,
        0.0,
        32.0,
        "United-States"
      ],
      [
        24.0,
        "Private",
        369667.0,
        "Some-college",
        10.0,
        "Never-married",
        "Other-service",
        "Unmarried",
        "White",
        "Female",
        0.0,
        0.0,
        40.0,
        "United-States"
      ],
      [
        55.0,
        "Private",
        104996.0,
        "7th-8th",
        4.0,
        "Married-civ-spouse",
        "Craft-repair",
        "Husband",
        "White",
        "Male",
        0.0,
        0.0,
        10.0,
        "United-States"
      ]
    ]
  ]
}
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
request = clients["endpoint"].undeploy_model(
    endpoint=endpoint_id, deployed_model_id=deployed_model_id, traffic_split={}
)
Explanation: Example output:
{
  "predictions": [
    false,
    false,
    false,
    true,
    false,
    false,
    false,
    false,
    false,
    false
  ],
  "deployedModelId": "6653241616695820288"
}
projects.locations.endpoints.undeployModel
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
delete_model = True
delete_endpoint = True
delete_pipeline = True
delete_batchjob = True
delete_bucket = True
# Delete the model using the Vertex AI fully qualified identifier for the model
try:
    if delete_model:
        clients["model"].delete_model(name=model_id)
except Exception as e:
    print(e)
# Delete the endpoint using the Vertex AI fully qualified identifier for the endpoint
try:
    if delete_endpoint:
        clients["endpoint"].delete_endpoint(name=endpoint_id)
except Exception as e:
    print(e)
# Delete the custom training using the Vertex AI fully qualified identifier for the custome training
try:
    if custom_training_id:
        clients["job"].delete_custom_job(name=custom_training_id)
except Exception as e:
    print(e)
# Delete the batch job using the Vertex AI fully qualified identifier for the batch job
try:
    if delete_batchjob:
        clients["job"].delete_batch_prediction_job(name=batch_job_id)
except Exception as e:
    print(e)
if delete_bucket and "BUCKET_NAME" in globals():
    ! gsutil rm -r gs://$BUCKET_NAME
Explanation: Example output:
{}
Cleaning up
To clean up all GCP resources used in this project, you can delete the GCP
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial.
End of explanation
<END_TASK>