mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
* upgrade: prep for auto docs index * upgrade: prep for auto docs index * upgrade: prep work of web index * upgrade: autoindex, map dirnames to tags * upgrade: autogen index, folder to tag * upgrade: autogen index, folder to tag * upgrade: fine-tune layout for webdoc * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * upgrade: fine-tuning tags and linkbacks * feat: CL var replacements * fix: tuning index * fix: tuning index * fix: fine tune indexing * fix: fine tune indexing * fix: fine tune indexing * fix: fine tune indexing * fix: fine tune indexing * fix: fine tune indexing * fix: index tuning * tuning: linkbak for repo index * tuning: README index * tuning: README index * tuning: README index * tuning: README index * tuning: README index * tuning: README index * tuning: README index * tuning: README index
55 KiB
55 KiB
In [ ]:
# @title Copyright & License (click to expand)
# 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.In [ ]:
import os
import sys
assert sys.version_info.major == 3, "This notebook requires Python 3."
# The Vertex AI Workbench Notebook product has specific requirements
IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") and not os.getenv("VIRTUAL_ENV")
IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(
"/opt/deeplearning/metadata/env_version"
)
# Vertex AI Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_WORKBENCH_NOTEBOOK:
USER_FLAG = "--user"
# Don't bother installing tensorflow or explainable_ai_sdk on Colab
extra_pkgs = "tensorflow==2.7 explainable_ai_sdk"
if "google.colab" in sys.modules:
extra_pkgs = ""
# Install required packages.
! pip3 install --upgrade -q {USER_FLAG} \
google-cloud-aiplatform \
google-cloud-bigquery \
explainable_ai_sdk \
$extra_pkgsIn [ ]:
# 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)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_IDIn [ ]:
REGION = "[your-region]" # @param {type: "string"}
if REGION == "[your-region]":
REGION = "us-central1"In [ ]:
import random
import string
# Generate a uuid of a specifed length(default=8)
def generate_uuid(length: int = 8) -> str:
return "".join(random.choices(string.ascii_lowercase + string.digits, k=length))
UUID = generate_uuid()In [ ]:
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
import os
import sys
# If on Vertex AI Workbench, then don't execute this code
IS_COLAB = "google.colab" in sys.modules
if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv(
"DL_ANACONDA_HOME"
):
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this notebook locally, replace the string below with the
# path to your service account key and run this cell to authenticate your GCP
# account.
elif not os.getenv("IS_TESTING"):
%env GOOGLE_APPLICATION_CREDENTIALS ''In [ ]:
# Import required packages.
import os
import pprint as pp
import sys
import google.cloud.aiplatform as aiplatform
import matplotlib.pyplot as plt
from google.cloud import bigquery
from google.cloud.aiplatform import model_monitoring
from google.cloud.aiplatform.explain.metadata.tf.v2 import \
saved_model_metadata_builderIn [ ]:
if os.getenv("IS_TESTING"):
! gcloud --quiet components install beta
! gcloud --quiet components update
! gcloud config set ai/region $REGION
os.environ["GOOGLE_CLOUD_PROJECT"] = PROJECT_IDIn [ ]:
aiplatform.init(project=PROJECT_ID, location=REGION)In [ ]:
bqclient = bigquery.Client(project=PROJECT_ID)In [ ]:
# @title Utility data structures
# Sampling distributions for categorical features...
DAYOFWEEK = {1: 1040, 2: 1223, 3: 1352, 4: 1217, 5: 1078, 6: 1011, 7: 1110}
LANGUAGE = {
"en-us": 4807,
"en-gb": 678,
"ja-jp": 419,
"en-au": 310,
"en-ca": 299,
"de-de": 147,
"en-in": 130,
"en": 127,
"fr-fr": 94,
"pt-br": 81,
"es-us": 65,
"zh-tw": 64,
"zh-hans-cn": 55,
"es-mx": 53,
"nl-nl": 37,
"fr-ca": 34,
"en-za": 29,
"vi-vn": 29,
"en-nz": 29,
"es-es": 25,
}
OS = {"IOS": 3980, "ANDROID": 3798, "null": 253}
MONTH = {6: 3125, 7: 1838, 8: 1276, 9: 1718, 10: 74}
COUNTRY = {
"United States": 4395,
"India": 486,
"Japan": 450,
"Canada": 354,
"Australia": 327,
"United Kingdom": 303,
"Germany": 144,
"Mexico": 102,
"France": 97,
"Brazil": 93,
"Taiwan": 72,
"China": 65,
"Saudi Arabia": 49,
"Pakistan": 48,
"Egypt": 46,
"Netherlands": 45,
"Vietnam": 42,
"Philippines": 39,
"South Africa": 38,
}
# Means and standard deviations for numerical features...
MEAN_SD = {
"julianday": (204.6, 34.7),
"cnt_user_engagement": (30.8, 53.2),
"cnt_level_start_quickplay": (7.8, 28.9),
"cnt_level_end_quickplay": (5.0, 16.4),
"cnt_level_complete_quickplay": (2.1, 9.9),
"cnt_level_reset_quickplay": (2.0, 19.6),
"cnt_post_score": (4.9, 13.8),
"cnt_spend_virtual_currency": (0.4, 1.8),
"cnt_ad_reward": (0.1, 0.6),
"cnt_challenge_a_friend": (0.0, 0.3),
"cnt_completed_5_levels": (0.1, 0.4),
"cnt_use_extra_steps": (0.4, 1.7),
}
DEFAULT_INPUT = {
"cnt_ad_reward": 0,
"cnt_challenge_a_friend": 0,
"cnt_completed_5_levels": 1,
"cnt_level_complete_quickplay": 3,
"cnt_level_end_quickplay": 5,
"cnt_level_reset_quickplay": 2,
"cnt_level_start_quickplay": 6,
"cnt_post_score": 34,
"cnt_spend_virtual_currency": 0,
"cnt_use_extra_steps": 0,
"cnt_user_engagement": 120,
"country": "Denmark",
"dayofweek": 3,
"julianday": 254,
"language": "da-dk",
"month": 9,
"operating_system": "IOS",
"user_pseudo_id": "104B0770BAE16E8B53DF330C95881893",
}In [ ]:
MODEL_PATH = "gs://mco-mm/churn"
params = {"sampled_shapley_attribution": {"path_count": 10}}
EXPLAIN_PARAMS = aiplatform.explain.ExplanationParameters(params)
builder = saved_model_metadata_builder.SavedModelMetadataBuilder(
model_path=MODEL_PATH, outputs_to_explain=["churned_probs"]
)
EXPLAIN_META = builder.get_metadata_protobuf()In [ ]:
MODEL_NAME = "churn"
IMAGE = "us-docker.pkg.dev/cloud-aiplatform/prediction/tf2-cpu.2-5:latest"
model = aiplatform.Model.upload(
display_name=MODEL_NAME,
artifact_uri=MODEL_PATH,
serving_container_image_uri=IMAGE,
explanation_parameters=EXPLAIN_PARAMS,
explanation_metadata=EXPLAIN_META,
sync=True,
)
MODEL_ID = model.resource_name.split("/")[-1]In [ ]:
endpoint = model.deploy(machine_type="n1-standard-4")
print(f"endpoint display name: {endpoint.display_name}")
print(f"endpoint resource name: {endpoint.resource_name}")
ENDPOINT = endpoint.resource_name
ENDPOINT_ID = ENDPOINT.split("/")[-1]In [ ]:
try:
resp = endpoint.predict([DEFAULT_INPUT])
for i in resp.predictions:
vals = i["churned_values"]
probs = i["churned_probs"]
for i in range(len(vals)):
print(vals[i], probs[i])
plt.pie(probs, labels=vals)
pp.pprint(resp)
except Exception as ex:
print("prediction request failed", ex)In [ ]:
try:
features = []
scores = []
resp = endpoint.explain([DEFAULT_INPUT])
for i in resp.explanations:
for j in i.attributions:
for k in j.feature_attributions:
features.append(k)
scores.append(j.feature_attributions[k])
features = [x for _, x in sorted(zip(scores, features))]
scores = sorted(scores)
fig, ax = plt.subplots()
fig.set_size_inches(9, 9)
ax.barh(features, scores)
fig.show()
except Exception as ex:
print("explanation request failed", ex)In [ ]:
USER_EMAIL = "[your-email-address]" # @param {type:"string"}
JOB_NAME = "churn"
# Sampling rate (optional, default=.8)
LOG_SAMPLE_RATE = 0.8 # @param {type:"number"}
# Monitoring Interval in hours (optional, default=1).
MONITOR_INTERVAL = 1 # @param {type:"number"}
# URI to training dataset.
DATASET_BQ_URI = "bq://mco-mm.bqmlga4.train" # @param {type:"string"}
# Prediction target column name in training dataset.
TARGET = "churned"
# # Skew and drift thresholds.
DEFAULT_THRESHOLD_VALUE = 0.001
SKEW_THRESHOLDS = {
"country": DEFAULT_THRESHOLD_VALUE,
"cnt_user_engagement": DEFAULT_THRESHOLD_VALUE,
}
DRIFT_THRESHOLDS = {
"country": DEFAULT_THRESHOLD_VALUE,
"cnt_user_engagement": DEFAULT_THRESHOLD_VALUE,
}
ATTRIB_SKEW_THRESHOLDS = {
"country": DEFAULT_THRESHOLD_VALUE,
"cnt_user_engagement": DEFAULT_THRESHOLD_VALUE,
}
ATTRIB_DRIFT_THRESHOLDS = {
"country": DEFAULT_THRESHOLD_VALUE,
"cnt_user_engagement": DEFAULT_THRESHOLD_VALUE,
}In [ ]:
skew_config = model_monitoring.SkewDetectionConfig(
data_source=DATASET_BQ_URI,
skew_thresholds=SKEW_THRESHOLDS,
attribute_skew_thresholds=ATTRIB_SKEW_THRESHOLDS,
target_field=TARGET,
)
drift_config = model_monitoring.DriftDetectionConfig(
drift_thresholds=DRIFT_THRESHOLDS,
attribute_drift_thresholds=ATTRIB_DRIFT_THRESHOLDS,
)
explanation_config = model_monitoring.ExplanationConfig()
objective_config = model_monitoring.ObjectiveConfig(
skew_config, drift_config, explanation_config
)
# Create sampling configuration
random_sampling = model_monitoring.RandomSampleConfig(sample_rate=LOG_SAMPLE_RATE)
# Create schedule configuration
schedule_config = model_monitoring.ScheduleConfig(monitor_interval=MONITOR_INTERVAL)
# Create alerting configuration.
emails = [USER_EMAIL]
alerting_config = model_monitoring.EmailAlertConfig(
user_emails=emails, enable_logging=True
)
# Create the monitoring job.
job = aiplatform.ModelDeploymentMonitoringJob.create(
display_name=JOB_NAME,
logging_sampling_strategy=random_sampling,
schedule_config=schedule_config,
alert_config=alerting_config,
objective_configs=objective_config,
project=PROJECT_ID,
location=REGION,
endpoint=endpoint,
)In [ ]:
# Download the table.
table = bigquery.TableReference.from_string(DATASET_BQ_URI[5:])
rows = bqclient.list_rows(table, max_results=1000)
instances = []
for row in rows:
instance = {}
for key, value in row.items():
if key == TARGET:
continue
if value is None:
value = ""
instance[key] = value
instances.append(instance)
print(len(instances))In [ ]:
response = endpoint.predict(instances=instances)
prediction = response[0]
# print the prediction for the first instance
print(prediction[0])In [ ]:
# Pause a bit for the baseline distribution to be calculated
if os.getenv("IS_TESTING"):
import time
time.sleep(120)In [ ]:
!gsutil ls gs://cloud-ai-platform-fdfb4810-148b-4c86-903c-dbdff879f6e1/*/*In [ ]:
# Undeploy the model and delete the endpoint
endpoint.undeploy_all()
endpoint.delete()
model.delete()
# Delete BQ table and dataset
rmtable = f"bq rm -f model_deployment_monitoring_{ENDPOINT_ID}.serving_predict"
! $rmtable
rmdataset = f"bq rm -f model_deployment_monitoring_{ENDPOINT_ID}"
! $rmdataset
Run in Colab
View on GitHub





