<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Build a fraud detection model on Vertex AI
Step1:  <table align="left">
  <td>
    <a href="https
Step2:  Install the latest version of the Vertex AI client library.
Run the following command in your notebook environment to install the Vertex SDK for Python
Step3:  Run the following command in your notebook environment to install witwidget
Step4:  Run the following command in your notebook environment to install joblib
Step5:  Run the following command in your notebook environment to install scikit-learn
Step6:  Run the following command in your notebook environment to install fsspec
Step7:  Run the following command in your notebook environment to install gcsfs
Step8:  Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step9:  Before you begin
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud 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 AI API. {TODO
Step10:  Otherwise, set your project ID here.
Step11:  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.
Step12:  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
Step13:  Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you create a model in Vertex AI using the Cloud SDK, you give a Cloud Storage path where the trained model is saved. 
In this tutorial, Vertex AI saves the trained model to a Cloud Storage bucket. Using this model artifact, you can then
create Vertex AI model and endpoint resources in order to serve
online predictions.
Set the name of your Cloud Storage bucket below. It must be unique across all
Cloud Storage buckets.
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.
Step14:  Only if your bucket doesn't already exist
Step15:  Finally, validate access to your Cloud Storage bucket by examining its contents
Step16:  Tutorial
Import required libraries
Step17:  Analyze the dataset
<a name="section-5"></a>
Take a quick look at the dataset and the number of rows.
Step18:  Check for null values.
Step19:  Check the type of transactions involved.
Step20:  Working with imbalanced data
Althuogh the outcome variable "isFraud" seems to be very imbalanced in the current dataset, a base model can be trained on it to check the quality of fraudulent transactions in the data and if needed, counter measures like undersampling of majority class or oversampling of the minority class can be considered.
Step21:  Prepare data for modeling
To prepare the dataset for training, a few columns need to be dropped that contain either unique data ('nameOrig','nameDest') or redundant fields ('isFlaggedFraud'). The categorical field "type" which describes the type of transaction and is important for fraud detection needs to be one-hot encoded.
Step22:  Remove the outcome variable from the training data.
Step23:  Split the data and assign 70% for training and 30% for testing.
Step24:  Fit a random forest model
<a name="section-6"></a>
Fit a simple random forest classifier on the preprocessed training dataset.
Step25:  Analyzing Results
<a name="section-7"></a>
The model returns good scores and the confusion matrix confirms that this model can indeed work with imbalanced data.
Step26:  Use RandomForestClassifier's feature_importances_ function to get a better understanding about which features were the most useful to the model.
Step27:  Save the model to a Cloud Storage path
<a name="section-8"></a>
Step28:  Create a model in Vertex AI
<a name="section-9"></a>
Step29:  Create an Endpoint
<a name="section-10"></a>
Step30:  Deploy the model to the created Endpoint
Configure the deployment name, machine type, and other parameters for the deployment.
Step31:  What-If Tool
<a name="section-11"></a>
The What-If Tool can be used to analyze the model predictions on a test data. See a brief introduction to the What-If Tool. In this tutorial, the What-If Tool will be configured and run on the model trained locally, and on the model deployed on Vertex AI Endpoint in the previous steps.
WitConfigBuilder provides the  set_ai_platform_model() method to configure the What-If Tool with a model deployed as a version on Ai Platform models. This feature currently supports Ai Platform only but not Vertex AI models. Fortunately, there is also an option to pass a custom function for generating predictions through the set_custom_predict_fn() method where either the locally trained model or a function that returns predictions from a Vertex AI model can be passed.
Prepare test samples
Save some samples from the test data for both the available classes (Fraud/not-Fraud) to analyze the model using the What-If Tool.
Step32:  Running the What-If Tool on the local model
Step33:  Running the What-If Tool on the deployed Vertex AI model
Step34:  Undeploy the model
When you are done doing predictions, you undeploy the model from the Endpoint resouce. This deprovisions all compute resources and ends billing for the deployed model.
Step35:  Clean up
<a name="section-12"></a>
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
<ASSISTANT_TASK:>
Python Code:
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Explanation: Build a fraud detection model on Vertex AI
End of explanation
import os
import google.auth
USER_FLAG = ""
# Google Cloud Notebook requires dependencies to be installed with '--user'
if "default" in dir(google.auth):
    USER_FLAG = "--user"
Explanation: <table align="left">
  <td>
    <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/fraud_detection/fraud-detection-model.ipynb">
      <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
    </a>
  </td>
  <td>
    <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/fraud_detection/fraud-detection-model.ipynb">
      <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
      View on GitHub
    </a>
  </td>
   <td>
    <a href="https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/official/workbench/fraud_detection/fraud-detection-model.ipynb">
      <img src="https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32" alt="Vertex AI logo">
      Open in Vertex AI Workbench
    </a>
  </td>
</table>
Table of contents
Overview
Dataset
Objective
Costs
Analyze the dataset
Fit a random forest model
Analyzing results
Save the model to a Cloud Storagae path
Create a model in Vertex AI
Create an Endpoint  
What-If Tool 
Clean up
Overview
<a name="section-1"></a>
This tutorial shows you how to build, deploy, and analyze predictions from a simple random forest model using tools like scikit-learn, Vertex AI, and the What-IF Tool (WIT) on a synthetic fraud transaction dataset to solve a financial fraud detection problem.
Dataset
<a name="section-2"></a>
The dataset used in this tutorial is publicly available at Kaggle. See Synthetic Financial Datasets For Fraud Detection.
Objective
<a name="section-3"></a>
This tutorial demonstrates data analysis and model-building using a synthetic financial dataset. The model is trained on identifying fraudulent cases among the transactions. Then, the trained model is deployed on a Vertex AI Endpoint and analyzed using the What-If Tool. The steps taken in this tutorial are as follows: 
Installation of required libraries
Reading the dataset from a Cloud Storage bucket
Performing exploratory analysis on the dataset
Preprocessing the dataset
Training a random forest model using scikit-learn
Saving the model to a Cloud Storage bucket
Creating a Vertex AI model resource and deploying to an endpoint
Running the What-If Tool on test data
Un-deploying the model and cleaning up the model resources
Costs
<a name="section-4"></a>
This tutorial uses billable components of Google Cloud:
Vertex AI
Cloud Storage
Learn about Vertex AI
pricing and Cloud Storage
pricing, and use the Pricing
Calculator
to generate a cost estimate based on your projected usage. 
Set up your local development environment
If you are using Colab or 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:
Install and initialize the Cloud SDK.
Install Python 3.
Install
   virtualenv
   and create a virtual environment that uses Python 3. Activate the virtual environment.
To install Jupyter, run pip3 install jupyter on the
command-line in a terminal shell.
To launch Jupyter, run jupyter notebook on the command-line in a terminal shell.
Open this notebook in the Jupyter Notebook Dashboard.
Install additional packages
End of explanation
! pip install {USER_FLAG} --upgrade google-cloud-aiplatform
Explanation: Install the latest version of the Vertex AI client library.
Run the following command in your notebook environment to install the Vertex SDK for Python:
End of explanation
! pip install {USER_FLAG} witwidget
Explanation: Run the following command in your notebook environment to install witwidget:
End of explanation
! pip install {USER_FLAG} joblib
Explanation: Run the following command in your notebook environment to install joblib:
End of explanation
! pip install {USER_FLAG} scikit-learn
Explanation: Run the following command in your notebook environment to install scikit-learn:
End of explanation
! pip install {USER_FLAG} fsspec
Explanation: Run the following command in your notebook environment to install fsspec:
End of explanation
! pip install {USER_FLAG} gcsfs
Explanation: Run the following command in your notebook environment to install gcsfs:
End of explanation
# Automatically restart kernel after installs
if not os.getenv("IS_TESTING"):
    # Automatically restart kernel after installs
    import IPython
    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)
Explanation: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
End of explanation
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)
Explanation: Before you begin
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud 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 AI API. {TODO: Update the APIs needed for your tutorial. Edit the API names, and update the link to append the API IDs, separating each one with a comma. For example, container.googleapis.com,cloudbuild.googleapis.com}
If you are running this notebook locally, you will need to install the Cloud SDK.
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.
End of explanation
if PROJECT_ID == "" or PROJECT_ID is None:
    PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
! gcloud config set project $PROJECT_ID
Explanation: Otherwise, set your project ID here.
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 it onto the name of resources you create 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 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 ''
Explanation: 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:
In the Cloud Console, go to the Create service account key
   page.
Click Create service account.
In the Service account name field, enter a name, and
   click Create.
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.
Click Create. A JSON file that contains your key downloads to your
local environment.
Enter the path to your service account key as the
GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.
End of explanation
BUCKET_NAME = "[your-bucket-name]"  # @param {type:"string"}
REGION = "[your-region]"  # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
    BUCKET_NAME = PROJECT_ID + "-vertex-ai-" + TIMESTAMP
BUCKET_URI = f"gs://{BUCKET_NAME}"
if REGION == "[your-region]":
    REGION = "us-central1"
Explanation: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you create a model in Vertex AI using the Cloud SDK, you give a Cloud Storage path where the trained model is saved. 
In this tutorial, Vertex AI saves the trained model to a Cloud Storage bucket. Using this model artifact, you can then
create Vertex AI model and endpoint resources in order to serve
online predictions.
Set the name of your Cloud Storage bucket below. It must be unique across all
Cloud Storage buckets.
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.
End of explanation
! gsutil mb -l $REGION $BUCKET_URI
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 $BUCKET_URI
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
import warnings
import joblib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from google.cloud import aiplatform, storage
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import (average_precision_score, classification_report,
                             confusion_matrix, f1_score)
from sklearn.model_selection import train_test_split
from witwidget.notebook.visualization import WitConfigBuilder, WitWidget
warnings.filterwarnings("ignore")
# Load dataset
df = pd.read_csv(
    "gs://cloud-samples-data/vertex-ai/managed_notebooks/fraud_detection/fraud_detection_data.csv"
)
Explanation: Tutorial
Import required libraries
End of explanation
print("shape : ", df.shape)
df.head()
Explanation: Analyze the dataset
<a name="section-5"></a>
Take a quick look at the dataset and the number of rows.
End of explanation
df.isnull().sum()
Explanation: Check for null values.
End of explanation
print(df.type.value_counts())
var = df.groupby("type").amount.sum()
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
var.plot(kind="bar")
ax1.set_title("Total amount per transaction type")
ax1.set_xlabel("Type of Transaction")
ax1.set_ylabel("Amount")
Explanation: Check the type of transactions involved.
End of explanation
# Count number of fraudulent/non-fraudulent transactions
df.isFraud.value_counts()
piedata = df.groupby(["isFlaggedFraud"]).sum()
f, axes = plt.subplots(1, 1, figsize=(6, 6))
axes.set_title("% of fraud transaction detected")
piedata.plot(
    kind="pie", y="isFraud", ax=axes, fontsize=14, shadow=False, autopct="%1.1f%%"
)
axes.set_ylabel("")
plt.legend(loc="upper left", labels=["Not Detected", "Detected"])
plt.show()
Explanation: Working with imbalanced data
Althuogh the outcome variable "isFraud" seems to be very imbalanced in the current dataset, a base model can be trained on it to check the quality of fraudulent transactions in the data and if needed, counter measures like undersampling of majority class or oversampling of the minority class can be considered.
End of explanation
df.drop(["nameOrig", "nameDest", "isFlaggedFraud"], axis=1, inplace=True)
X = pd.concat([df.drop("type", axis=1), pd.get_dummies(df["type"])], axis=1)
X.head()
Explanation: Prepare data for modeling
To prepare the dataset for training, a few columns need to be dropped that contain either unique data ('nameOrig','nameDest') or redundant fields ('isFlaggedFraud'). The categorical field "type" which describes the type of transaction and is important for fraud detection needs to be one-hot encoded.
End of explanation
y = X[["isFraud"]]
X = X.drop(["isFraud"], axis=1)
Explanation: Remove the outcome variable from the training data.
End of explanation
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42, shuffle=False
)
print(X_train.shape, X_test.shape)
Explanation: Split the data and assign 70% for training and 30% for testing.
End of explanation
print("before initiating")
forest = RandomForestClassifier(verbose=1)
print("after initiating")
forest.fit(X_train, y_train)
print("after fitting")
Explanation: Fit a random forest model
<a name="section-6"></a>
Fit a simple random forest classifier on the preprocessed training dataset.
End of explanation
print("before predicting")
y_prob = forest.predict_proba(X_test)
print("after predicting y_prob")
y_pred = forest.predict(X_test)
print("AUPRC :", (average_precision_score(y_test, y_prob[:, 1])))
print("F1 - score :", (f1_score(y_test, y_pred)))
print("Confusion_matrix : ")
print(confusion_matrix(y_test, y_pred))
print("classification_report")
print(classification_report(y_test, y_pred))
print("after printing classification_report")
Explanation: Analyzing Results
<a name="section-7"></a>
The model returns good scores and the confusion matrix confirms that this model can indeed work with imbalanced data.
End of explanation
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_], axis=0)
forest_importances = pd.Series(importances, index=list(X_train))
fig, ax = plt.subplots()
forest_importances.plot.bar(yerr=std, ax=ax)
ax.set_title("Feature Importance for Fraud Transaction Detection Model")
ax.set_ylabel("Importance")
fig.tight_layout()
Explanation: Use RandomForestClassifier's feature_importances_ function to get a better understanding about which features were the most useful to the model.
End of explanation
# save the trained model to a local file "model.joblib"
FILE_NAME = "model.joblib"
joblib.dump(forest, FILE_NAME)
# Upload the saved model file to Cloud Storage
BLOB_PATH = "[your-blob-path]"
BLOB_NAME = os.path.join(BLOB_PATH, FILE_NAME)
bucket = storage.Client(PROJECT_ID).bucket(BUCKET_NAME)
blob = bucket.blob(BLOB_NAME)
blob.upload_from_filename(FILE_NAME)
Explanation: Save the model to a Cloud Storage path
<a name="section-8"></a>
End of explanation
MODEL_DISPLAY_NAME = "[your-model-display-name]"
ARTIFACT_GCS_PATH = f"{BUCKET_URI}/{BLOB_PATH}"
SERVING_CONTAINER_IMAGE_URI = (
    "us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.1-0:latest"
)
# Create a Vertex AI model resource
aiplatform.init(project=PROJECT_ID, location=REGION)
model = aiplatform.Model.upload(
    display_name=MODEL_DISPLAY_NAME,
    artifact_uri=ARTIFACT_GCS_PATH,
    serving_container_image_uri=SERVING_CONTAINER_IMAGE_URI,
)
model.wait()
print(model.display_name)
print(model.resource_name)
Explanation: Create a model in Vertex AI
<a name="section-9"></a>
End of explanation
ENDPOINT_DISPLAY_NAME = "[your-endpoint-display-name]"
endpoint = aiplatform.Endpoint.create(display_name=ENDPOINT_DISPLAY_NAME)
print(endpoint.display_name)
print(endpoint.resource_name)
Explanation: Create an Endpoint
<a name="section-10"></a>
End of explanation
DEPLOYED_MODEL_NAME = "[your-deployed-model-name]"
MACHINE_TYPE = "n1-standard-2"
# deploy the model to the endpoint
model.deploy(
    endpoint=endpoint,
    deployed_model_display_name=DEPLOYED_MODEL_NAME,
    machine_type=MACHINE_TYPE,
)
model.wait()
print(model.display_name)
print(model.resource_name)
Explanation: Deploy the model to the created Endpoint
Configure the deployment name, machine type, and other parameters for the deployment.
End of explanation
# collect 50 samples for each class-label from the test data
pos_samples = y_test[y_test["isFraud"] == 1].sample(50).index
neg_samples = y_test[y_test["isFraud"] == 0].sample(50).index
test_samples_y = pd.concat([y_test.loc[pos_samples], y_test.loc[neg_samples]])
test_samples_X = X_test.loc[test_samples_y.index].copy()
Explanation: What-If Tool
<a name="section-11"></a>
The What-If Tool can be used to analyze the model predictions on a test data. See a brief introduction to the What-If Tool. In this tutorial, the What-If Tool will be configured and run on the model trained locally, and on the model deployed on Vertex AI Endpoint in the previous steps.
WitConfigBuilder provides the  set_ai_platform_model() method to configure the What-If Tool with a model deployed as a version on Ai Platform models. This feature currently supports Ai Platform only but not Vertex AI models. Fortunately, there is also an option to pass a custom function for generating predictions through the set_custom_predict_fn() method where either the locally trained model or a function that returns predictions from a Vertex AI model can be passed.
Prepare test samples
Save some samples from the test data for both the available classes (Fraud/not-Fraud) to analyze the model using the What-If Tool.
End of explanation
# define target and labels
TARGET_FEATURE = "isFraud"
LABEL_VOCAB = ["not-fraud", "fraud"]
# define the function to adjust the predictions
def adjust_prediction(pred):
    return [1 - pred, pred]
# Combine the features and labels into one array for the What-If Tool
test_examples = np.hstack(
    (test_samples_X.to_numpy(), test_samples_y.to_numpy().reshape(-1, 1))
)
# Configure the WIT to run on the locally trained model
config_builder = (
    WitConfigBuilder(
        test_examples.tolist(), test_samples_X.columns.tolist() + ["isFraud"]
    )
    .set_custom_predict_fn(forest.predict_proba)
    .set_target_feature(TARGET_FEATURE)
    .set_label_vocab(LABEL_VOCAB)
)
# display the WIT widget
WitWidget(config_builder, height=600)
Explanation: Running the What-If Tool on the local model
End of explanation
# configure the target and class-labels
TARGET_FEATURE = "isFraud"
LABEL_VOCAB = ["not-fraud", "fraud"]
# function to return predictions from the deployed Model
def endpoint_predict_sample(instances: list):
    prediction = endpoint.predict(instances=instances)
    preds = [[1 - i, i] for i in prediction.predictions]
    return preds
# Combine the features and labels into one array for the What-If Tool
test_examples = np.hstack(
    (test_samples_X.to_numpy(), test_samples_y.to_numpy().reshape(-1, 1))
)
# Configure the WIT with the prediction function
config_builder = (
    WitConfigBuilder(
        test_examples.tolist(), test_samples_X.columns.tolist() + ["isFraud"]
    )
    .set_custom_predict_fn(endpoint_predict_sample)
    .set_target_feature(TARGET_FEATURE)
    .set_label_vocab(LABEL_VOCAB)
)
# run the WIT-widget
WitWidget(config_builder, height=400)
Explanation: Running the What-If Tool on the deployed Vertex AI model
End of explanation
endpoint.undeploy_all()
Explanation: Undeploy the model
When you are done doing predictions, you undeploy the model from the Endpoint resouce. This deprovisions all compute resources and ends billing for the deployed model.
End of explanation
# delete the endpoint
endpoint.delete()
# delete the model
model.delete()
delete_bucket = True
if delete_bucket or os.getenv("IS_TESTING"):
    ! gsutil rm -r $BUCKET_URI
Explanation: Clean up
<a name="section-12"></a>
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:
End of explanation
<END_TASK>