Files
model_garden/notebooks/community/migration/UJ10 legacy Custom Training Prebuilt Container SKLearn.ipynb
T

58 KiB

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

Vertex SDK: Train and deploy an SKLearn model with pre-built containers (formerly hosted runtimes)

Installation

Install the Google cloud-storage library as well.

In [ ]:
! pip3 install google-cloud-storage

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.

In [ ]:
import os

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

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

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.

  1. Select or create a GCP 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 APIs and Compute Engine APIs.

  4. Google Cloud SDK is already installed in Google Cloud Notebooks.

  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.

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

In [ ]:
REGION = "us-central1"  # @param {type: "string"}

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.

In [ ]:
from datetime import datetime

TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")

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.

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

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.

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

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

In [ ]:
! gsutil mb -l $REGION gs://$BUCKET_NAME

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

In [ ]:
! gsutil ls -al gs://$BUCKET_NAME

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.

In [ ]:
import json
import os
import sys
import time

from googleapiclient import discovery

Vertex constants

Setup up the following constants for Vertex:

  • PARENT: The Vertex location root path for dataset, model and endpoint resources.
In [ ]:
# Vertex location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION

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.

In [ ]:
client = discovery.build("ml", "v1")

Prepare a trainer script

Package assembly

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

Task.py contents

In [ ]:
%%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')

Store training script on your Cloud Storage bucket

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

Train a model

Request

In [ ]:
JOB_NAME = "custom_job_SKL" + TIMESTAMP

training_input = {
    "scaleTier": "BASIC",
    "packageUris": ["gs://" + BUCKET_NAME + "/census.tar.gz"],
    "pythonModule": "trainer.task",
    "args": ["--model-dir=" + "gs://{}/{}".format(BUCKET_NAME, JOB_NAME)],
    "region": REGION,
    "runtimeVersion": "2.4",
    "pythonVersion": "3.7",
}

body = {"jobId": JOB_NAME, "trainingInput": training_input}

request = client.projects().jobs().create(parent="projects/" + PROJECT_ID)
request.body = body

print(json.dumps(json.loads(request.to_json()), indent=2))

request = client.projects().jobs().create(parent="projects/" + PROJECT_ID, body=body)

Example output:

{
  "uri": "https://ml.googleapis.com/v1/projects/migration-ucaip-training/jobs?alt=json",
  "method": "POST",
  "body": {
    "jobId": "custom_job_SKL20210302140139",
    "trainingInput": {
      "scaleTier": "BASIC",
      "packageUris": [
        "gs://migration-ucaip-trainingaip-20210302140139/census.tar.gz"
      ],
      "pythonModule": "trainer.task",
      "args": [
        "--model-dir=gs://migration-ucaip-trainingaip-20210302140139/custom_job_SKL20210302140139"
      ],
      "region": "us-central1",
      "runtimeVersion": "2.4",
      "pythonVersion": "3.7"
    }
  },
  "headers": {
    "accept": "application/json",
    "accept-encoding": "gzip, deflate",
    "user-agent": "(gzip)",
    "x-goog-api-client": "gdcl/1.12.8 gl-python/3.7.8"
  },
  "methodId": "ml.projects.jobs.create",
  "resumable": null,
  "response_callbacks": [],
  "_in_error_state": false,
  "body_size": 0,
  "resumable_uri": null,
  "resumable_progress": 0
}

Call

In [ ]:
result = request.execute()

Response

In [ ]:
print(json.dumps(result, indent=2))

Example output:

{
  "jobId": "custom_job_SKL20210302140139",
  "trainingInput": {
    "packageUris": [
      "gs://migration-ucaip-trainingaip-20210302140139/census.tar.gz"
    ],
    "pythonModule": "trainer.task",
    "args": [
      "--model-dir=gs://migration-ucaip-trainingaip-20210302140139/custom_job_SKL20210302140139"
    ],
    "region": "us-central1",
    "runtimeVersion": "2.4",
    "pythonVersion": "3.7"
  },
  "createTime": "2021-03-02T14:09:33Z",
  "state": "QUEUED",
  "trainingOutput": {},
  "etag": "YQ/mo0C8EUg="
}
In [ ]:
# The short numeric ID for the custom training job
custom_training_short_id = result["jobId"]
# The full unique ID for the custom training job
custom_training_id = "projects/" + PROJECT_ID + "/jobs/" + result["jobId"]

print(custom_training_id)

Call

In [ ]:
request = client.projects().jobs().get(name=custom_training_id)

result = request.execute()

Response

In [ ]:
print(json.dumps(result, indent=2))

Example output:

{
  "jobId": "custom_job_SKL20210302140139",
  "trainingInput": {
    "packageUris": [
      "gs://migration-ucaip-trainingaip-20210302140139/census.tar.gz"
    ],
    "pythonModule": "trainer.task",
    "args": [
      "--model-dir=gs://migration-ucaip-trainingaip-20210302140139/custom_job_SKL20210302140139"
    ],
    "region": "us-central1",
    "runtimeVersion": "2.4",
    "pythonVersion": "3.7"
  },
  "createTime": "2021-03-02T14:09:33Z",
  "state": "PREPARING",
  "trainingOutput": {},
  "etag": "/X2Bt4OWbWU="
}
In [ ]:
while True:
    response = client.projects().jobs().get(name=custom_training_id).execute()

    if response["state"] != "SUCCEEDED":
        print("Training job has not completed:", response["state"])
        if response["state"] == "FAILED":
            break
    else:
        break
    time.sleep(60)

# model artifact output directory on Google Cloud Storage
model_artifact_dir = response["trainingInput"]["args"][0].split("=")[-1]
print("artifact location  " + model_artifact_dir)

Deploy the model

Request

In [ ]:
body = {"name": "custom_job_SKL" + TIMESTAMP}

request = client.projects().models().create(parent="projects/" + PROJECT_ID)
request.body = json.loads(json.dumps(body, indent=2))

print(json.dumps(json.loads(request.to_json()), indent=2))

request = client.projects().models().create(parent="projects/" + PROJECT_ID, body=body)

Example output:

{
  "uri": "https://ml.googleapis.com/v1/projects/migration-ucaip-training/models?alt=json",
  "method": "POST",
  "body": {
    "name": "custom_job_SKL20210302140139"
  },
  "headers": {
    "accept": "application/json",
    "accept-encoding": "gzip, deflate",
    "user-agent": "(gzip)",
    "x-goog-api-client": "gdcl/1.12.8 gl-python/3.7.8"
  },
  "methodId": "ml.projects.models.create",
  "resumable": null,
  "response_callbacks": [],
  "_in_error_state": false,
  "body_size": 0,
  "resumable_uri": null,
  "resumable_progress": 0
}

Call

In [ ]:
result = request.execute()

Response

In [ ]:
print(json.dumps(result, indent=2))

Example output:

{
  "name": "projects/migration-ucaip-training/models/custom_job_SKL20210302140139",
  "regions": [
    "us-central1"
  ],
  "etag": "Lmd8u9MSSIA="
}
In [ ]:
model_id = result["name"]

Request

In [ ]:
version = {
    "name": "custom_job_SKL" + TIMESTAMP,
    "deploymentUri": model_artifact_dir,
    "runtimeVersion": "2.1",
    "framework": "SCIKIT_LEARN",
    "pythonVersion": "3.7",
    "machineType": "mls1-c1-m2",
}

request = client.projects().models().versions().create(parent=model_id)
request.body = version

print(json.dumps(json.loads(request.to_json()), indent=2))

request = client.projects().models().versions().create(parent=model_id, body=version)

Example output:

{
  "uri": "https://ml.googleapis.com/v1/projects/migration-ucaip-training/models/custom_job_SKL20210302140139/versions?alt=json",
  "method": "POST",
  "body": {
    "name": "custom_job_SKL20210302140139",
    "deploymentUri": "gs://migration-ucaip-trainingaip-20210302140139/custom_job_SKL20210302140139",
    "runtimeVersion": "2.1",
    "framework": "SCIKIT_LEARN",
    "pythonVersion": "3.7",
    "machineType": "mls1-c1-m2"
  },
  "headers": {
    "accept": "application/json",
    "accept-encoding": "gzip, deflate",
    "user-agent": "(gzip)",
    "x-goog-api-client": "gdcl/1.12.8 gl-python/3.7.8"
  },
  "methodId": "ml.projects.models.versions.create",
  "resumable": null,
  "response_callbacks": [],
  "_in_error_state": false,
  "body_size": 0,
  "resumable_uri": null,
  "resumable_progress": 0
}

Call

In [ ]:
result = request.execute()

Response

In [ ]:
print(json.dumps(result, indent=2))

Example output:

{
  "name": "projects/migration-ucaip-training/operations/create_custom_job_SKL20210302140139_custom_job_SKL20210302140139-1614695138432",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.ml.v1.OperationMetadata",
    "createTime": "2021-03-02T14:25:38Z",
    "operationType": "CREATE_VERSION",
    "modelName": "projects/migration-ucaip-training/models/custom_job_SKL20210302140139",
    "version": {
      "name": "projects/migration-ucaip-training/models/custom_job_SKL20210302140139/versions/custom_job_SKL20210302140139",
      "deploymentUri": "gs://migration-ucaip-trainingaip-20210302140139/custom_job_SKL20210302140139",
      "createTime": "2021-03-02T14:25:38Z",
      "runtimeVersion": "2.1",
      "etag": "ilPQVTiR+IM=",
      "framework": "SCIKIT_LEARN",
      "machineType": "mls1-c1-m2",
      "pythonVersion": "3.7"
    }
  }
}
In [ ]:
# The full unique ID for the model version
model_version_name = result["metadata"]["version"]["name"]

print(model_version_name)
In [ ]:
while True:
    response = (
        client.projects().models().versions().get(name=model_version_name).execute()
    )
    if response["state"] == "READY":
        print("Model version created.")
        break
    time.sleep(60)

Make batch predictions

Batch prediction only supports Tensorflow. FRAMEWORK_SCIKIT_LEARN is not currently available.

Make online predictions

Prepare data item for online prediction

In [ ]:
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",
    ],
]

Request

In [ ]:
request = client.projects().predict(name=model_version_name)
request.body = json.loads(json.dumps({"instances": INSTANCES}, indent=2))

print(json.dumps(json.loads(request.to_json()), indent=2))

request = client.projects().predict(
    name=model_version_name, body={"instances": INSTANCES}
)

Example output:

{
  "uri": "https://ml.googleapis.com/v1/projects/migration-ucaip-training/models/custom_job_SKL20210302140139/versions/custom_job_SKL20210302140139:predict?alt=json",
  "method": "POST",
  "body": {
    "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"
      ]
    ]
  },
  "headers": {
    "accept": "application/json",
    "accept-encoding": "gzip, deflate",
    "user-agent": "(gzip)",
    "x-goog-api-client": "gdcl/1.12.8 gl-python/3.7.8"
  },
  "methodId": "ml.projects.predict",
  "resumable": null,
  "response_callbacks": [],
  "_in_error_state": false,
  "body_size": 0,
  "resumable_uri": null,
  "resumable_progress": 0
}

Call

In [ ]:
result = request.execute()

Response

In [ ]:
print(json.dumps(result, indent=2))

Example output:

{
  "predictions": [
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false,
    false
  ]
}

Request

In [ ]:
request = client.projects().models().versions().delete(name=model_version_name)

Call

In [ ]:
response = request.execute()

Response

In [ ]:
print(json.dumps(response, indent=2))

Example output:

{
  "name": "projects/migration-ucaip-training/operations/delete_custom_job_SKL20210302140139_custom_job_SKL20210302140139-1614695211809",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.ml.v1.OperationMetadata",
    "createTime": "2021-03-02T14:26:51Z",
    "operationType": "DELETE_VERSION",
    "modelName": "projects/migration-ucaip-training/models/custom_job_SKL20210302140139",
    "version": {
      "name": "projects/migration-ucaip-training/models/custom_job_SKL20210302140139/versions/custom_job_SKL20210302140139",
      "deploymentUri": "gs://migration-ucaip-trainingaip-20210302140139/custom_job_SKL20210302140139",
      "createTime": "2021-03-02T14:25:38Z",
      "runtimeVersion": "2.1",
      "state": "READY",
      "etag": "5R4YqeqWMk8=",
      "framework": "SCIKIT_LEARN",
      "machineType": "mls1-c1-m2",
      "pythonVersion": "3.7"
    }
  }
}
Warning:
Output truncated. This notebook contains too many cells to display efficiently.