Files
model_garden/notebooks/official/pipelines/metrics_viz_run_compare_kfp.ipynb
T
Morgan DuandGitHub e54cd9c495 sync with ai-platform-samples (#25)
* sync with ai-platform-samples

* fix: update links
2021-08-16 12:26:14 -07:00

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

Metrics visualization and run comparison using the KFP SDK

Overview

In this notebook, you will learn how to use the Kubeflow Pipelines (KFP) SDK to build Vertex Pipelines that generate model metrics and metrics visualizations; and how to compare pipeline runs.

Objective

In this example, you'll learn:

  • how to generate ROC curve and confusion matrix visualizations for classification results
  • how to write metrics
  • how to compare metrics across pipeline runs

Costs

This tutorial uses billable components of Google Cloud:

  • Vertex AI Training
  • Cloud Storage

Learn about pricing for Vertex AI and Cloud Storage, 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 Google Cloud 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 pip 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.

Install additional packages

Install the KFP SDK and the Vertex SDK for Python.

In [ ]:
import os

# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")

# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
    USER_FLAG = "--user"
In [ ]:
! pip install {USER_FLAG} kfp google-cloud-aiplatform matplotlib --upgrade

Restart the kernel

After you install the additional packages, you need to restart the notebook kernel so it can find the packages.

In [ ]:
# Automatically restart kernel after installs
import os

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

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

Check the version of the package you installed. The KFP SDK version should be >=1.6.

In [ ]:
!python3 -c "import kfp; print('KFP SDK version: {}'.format(kfp.__version__))"

Before you begin

This notebook does not require a GPU runtime.

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, Cloud Storage, and Compute Engine APIs.

  4. Follow the "Configuring your project" instructions from the Vertex Pipelines documentation.

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

  6. 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 may be able to get your project ID using gcloud.

In [ ]:
import os

PROJECT_ID = ""

# Get your Google Cloud project ID from gcloud
if not os.getenv("IS_TESTING"):
    shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null
    PROJECT_ID = shell_output[0]
    print("Project ID: ", PROJECT_ID)

Otherwise, set your project ID here.

In [ ]:
if PROJECT_ID == "" or PROJECT_ID is None:
    PROJECT_ID = "python-docs-samples-tests"  # @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 it onto the name of resources you create in this tutorial.

In [ ]:
from datetime import datetime

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

Authenticate your Google Cloud account

If you are using Google Cloud 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 [ ]:
import os
import sys

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

# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")

# If on Google Cloud Notebooks, then don't execute this code
if not IS_GOOGLE_CLOUD_NOTEBOOK:
    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 as necessary

You will need a Cloud Storage bucket for this example. If you don't have one that you want to use, you can make one now.

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

You may also change the REGION variable, which is used for operations throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are available. You may not use a Multi-Regional Storage bucket for training with Vertex AI.

In [ ]:
BUCKET_NAME = "gs://[your-bucket-name]"  # @param {type:"string"}
REGION = "us-central1"  # @param {type:"string"}
In [ ]:
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
    BUCKET_NAME = "gs://" + 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 $BUCKET_NAME

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

In [ ]:
! gsutil ls -al $BUCKET_NAME

Import libraries and define constants

Define some constants.

In [ ]:
PATH=%env PATH
%env PATH={PATH}:/home/jupyter/.local/bin

USER = "your-user-name"  # <---CHANGE THIS
PIPELINE_ROOT = "{}/pipeline_root/{}".format(BUCKET_NAME, USER)

PIPELINE_ROOT

Do some imports:

In [ ]:
from google.cloud import aiplatform
from kfp import dsl
from kfp.v2 import compiler
from kfp.v2.dsl import ClassificationMetrics, Metrics, Output, component
from kfp.v2.google.client import AIPlatformClient

Initialize the Vertex SDK for Python

In [ ]:
aiplatform.init(project=PROJECT_ID)

Define a pipeline

In this section, you define a pipeline that demonstrates some of the metrics logging and visualization features.

The example pipeline has three steps. First define three pipeline components, then define a pipeline that uses them.

Define Pipeline components

In this section, you define some Python function-based components that use scikit-learn to train some classifiers and produce evaluations that can be visualized.

Note the use of the @component() decorator in the definitions below. You can optionally set a list of packages for the component to install; the base image to use (the default is a Python 3.7 image); and the name of a component YAML file to generate, so that the component definition can be shared and reused.

The first component shows how to visualize an ROC curve. Note that the function definition includes an output called wmetrics, of type Output[ClassificationMetrics]. You can visualize the metrics in the Pipelines user interface in the Cloud Console.

To do this, this example uses the artifact's log_roc_curve() method. This method takes as input arrays with the false positive rates, true positive rates, and thresholds, as generated by the sklearn.metrics.roc_curve function.

When you evaluate the cell below, a task factory function called wine_classification is created, that is used to construct the pipeline definition. In addition, a component YAML file is created, which can be shared and loaded via file or URL to create the same task factory function.

In [ ]:
@component(
    packages_to_install=["sklearn"],
    base_image="python:3.9",
    output_component_file="wine_classif_component.yaml",
)
def wine_classification(wmetrics: Output[ClassificationMetrics]):
    from sklearn.datasets import load_wine
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.metrics import roc_curve
    from sklearn.model_selection import cross_val_predict, train_test_split

    X, y = load_wine(return_X_y=True)
    # Binary classification problem for label 1.
    y = y == 1

    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    rfc = RandomForestClassifier(n_estimators=10, random_state=42)
    rfc.fit(X_train, y_train)
    y_scores = cross_val_predict(rfc, X_train, y_train, cv=3, method="predict_proba")
    fpr, tpr, thresholds = roc_curve(
        y_true=y_train, y_score=y_scores[:, 1], pos_label=True
    )
    wmetrics.log_roc_curve(fpr, tpr, thresholds)

The second component shows how to visualize a confusion matrix, in this case for a model trained using SGDClassifier.

As with the previous component, you create a metricsc output artifact of type Output[ClassificationMetrics]. Then, use the artifact's log_confusion_matrix method to visualize the confusion matrix results, as generated by the sklearn.metrics.confusion_matrix function.

In [ ]:
@component(packages_to_install=["sklearn"], base_image="python:3.9")
def iris_sgdclassifier(
    test_samples_fraction: float,
    metricsc: Output[ClassificationMetrics],
):
    from sklearn import datasets, model_selection
    from sklearn.linear_model import SGDClassifier
    from sklearn.metrics import confusion_matrix

    iris_dataset = datasets.load_iris()
    train_x, test_x, train_y, test_y = model_selection.train_test_split(
        iris_dataset["data"],
        iris_dataset["target"],
        test_size=test_samples_fraction,
    )

    classifier = SGDClassifier()
    classifier.fit(train_x, train_y)
    predictions = model_selection.cross_val_predict(classifier, train_x, train_y, cv=3)
    metricsc.log_confusion_matrix(
        ["Setosa", "Versicolour", "Virginica"],
        confusion_matrix(
            train_y, predictions
        ).tolist(),  # .tolist() to convert np array to list.
    )

The following component also uses the "iris" dataset, but trains a LogisticRegression model. It logs model accuracy in the metrics output artifact.

In [ ]:
@component(
    packages_to_install=["sklearn"],
    base_image="python:3.9",
)
def iris_logregression(
    input_seed: int,
    split_count: int,
    metrics: Output[Metrics],
):
    from sklearn import datasets, model_selection
    from sklearn.linear_model import LogisticRegression

    # Load digits dataset
    iris = datasets.load_iris()
    # # Create feature matrix
    X = iris.data
    # Create target vector
    y = iris.target
    # test size
    test_size = 0.20

    # cross-validation settings
    kfold = model_selection.KFold(
        n_splits=split_count, random_state=input_seed, shuffle=True
    )
    # Model instance
    model = LogisticRegression()
    scoring = "accuracy"
    results = model_selection.cross_val_score(model, X, y, cv=kfold, scoring=scoring)
    print(f"results: {results}")

    # split data
    X_train, X_test, y_train, y_test = model_selection.train_test_split(
        X, y, test_size=test_size, random_state=input_seed
    )
    # fit model
    model.fit(X_train, y_train)

    # accuracy on test set
    result = model.score(X_test, y_test)
    print(f"result: {result}")
    metrics.log_metric("accuracy", (result * 100.0))

Define a pipeline that uses the components

Next, define a simple pipeline that uses the components that were created in the previous section.

In [ ]:
@dsl.pipeline(
    # Default pipeline root. You can override it when submitting the pipeline.
    pipeline_root=PIPELINE_ROOT,
    # A name for the pipeline.
    name="metrics-pipeline-v2",
)
def pipeline(seed: int, splits: int):
    wine_classification_op = wine_classification()  # noqa: F841
    iris_logregression_op = iris_logregression(  # noqa: F841
        input_seed=seed, split_count=splits
    )
    iris_sgdclassifier_op = iris_sgdclassifier(test_samples_fraction=0.3)  # noqa: F841

Compile and run the pipeline

Now, you're ready to compile the pipeline:

In [ ]:
from kfp.v2 import compiler  # noqa: F811

compiler.Compiler().compile(
    pipeline_func=pipeline, package_path="metrics_pipeline_job.json"
)

The pipeline compilation generates the metrics_pipeline_job.json job spec file.

Next, instantiate an API client object:

In [ ]:
from kfp.v2.google.client import AIPlatformClient  # noqa: F811

api_client = AIPlatformClient(
    project_id=PROJECT_ID,
    region=REGION,
)

Then, you run the defined pipeline like this:

In [ ]:
response = api_client.create_run_from_job_spec(
    job_spec_path="metrics_pipeline_job.json",
    job_id=f"metrics-pipeline-v2{TIMESTAMP}-1",
    # pipeline_root=PIPELINE_ROOT  # this argument is necessary if you did not specify PIPELINE_ROOT as part of the pipeline definition.
    parameter_values={"seed": 7, "splits": 10},
)

Click on the generated link to see your run in the Cloud Console.

Pipeline run comparisons

Next, generate another pipeline run that uses a different seed and split for the iris_logregression step.

Submit the new pipeline run:

Comparing pipeline runs in the UI

Next, generate another pipeline run that uses a different seed and split for the iris_logregression step.

Submit the new pipeline run:

In [ ]:
response = api_client.create_run_from_job_spec(
    job_spec_path="metrics_pipeline_job.json",
    job_id=f"metrics-pipeline-v2{TIMESTAMP}-2",
    # pipeline_root=PIPELINE_ROOT  # this argument is necessary if you did not specify PIPELINE_ROOT as part of the pipeline definition.
    parameter_values={"seed": 5, "splits": 7},
)

When both pipeline runs have finished, compare their results by navigating to the pipeline runs list in the Cloud Console, selecting both of them, and clicking COMPARE at the top of the Console panel.

Comparing the parameters and metrics of pipeline runs from their tracked metadata

In this section, you use the Vertex SDK for Python to compare the parameters and metrics of the pipeline runs. Wait until the pipeline runs have finished to run this section.

Extract metrics and parameters into a pandas dataframe for run comparison

Ingest the metadata for all runs of pipelines named metrics-pipeline-v2 into a pandas dataframe.

In [ ]:
pipeline_df = aiplatform.get_pipeline_df(pipeline="metrics-pipeline-v2")
pipeline_df

Parallel coordinates plot of parameters and metrics

With the metric and parameters in a dataframe, you can perform further analysis to exetract useful information. The following example compares data from each run using a parallel coordinate plot.

In [ ]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

plt.rcParams["figure.figsize"] = [15, 5]

pipeline_df["param.input:seed"] = pipeline_df["param.input:seed"].astype(np.float16)
pipeline_df["param.input:splits"] = pipeline_df["param.input:splits"].astype(np.float16)

ax = pd.plotting.parallel_coordinates(
    pipeline_df.reset_index(level=0),
    "run_name",
    cols=["param.input:seed", "param.input:splits", "metric.accuracy"],
    # color=['blue', 'green', 'pink', 'red'],
)
ax.set_yscale("symlog")
ax.legend(bbox_to_anchor=(1.0, 0.5))

Plot ROC curve and calculate AUC number

In addition to basic metrics, you can extract complex metrics and perform further analysis using the get_pipeline_df method.

In [ ]:
pipeline_df = aiplatform.get_pipeline_df(pipeline="metrics-pipeline-v2")
pipeline_df
In [ ]:
df = pd.DataFrame(pipeline_df["metric.confidenceMetrics"][0])
auc = np.trapz(df["recall"], df["falsePositiveRate"])
plt.plot(df["falsePositiveRate"], df["recall"], label="auc=" + str(auc))
plt.legend(loc=4)
plt.show()

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:

  • delete Cloud Storage objects that were created. Uncomment and run the command in the cell below only if you are not using the PIPELINE_ROOT path for any other purpose.
In [ ]:
# Warning: this command will delete ALL Cloud Storage objects under the PIPELINE_ROOT path.
# ! gsutil -m rm -r $PIPELINE_ROOT