mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
* feat: MLMD + Pipelines notebook * Updates from notebook execution test * Update with changes from linter * Update MLMD notebook from feedback, upgrade to latest sdk versions * Add metadata notebook to codeowners file * Resolve merge conflicts with codeowners * Update KFP and Vertex SDK versions * Run the linter Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com>
39 KiB
39 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.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 [ ]:
!pip3 install {USER_FLAG} google-cloud-aiplatform==1.7.0
!pip3 install {USER_FLAG} kfp==1.8.9In [ ]:
# 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 [ ]:
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)In [ ]:
if PROJECT_ID == "" or PROJECT_ID is None:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}In [ ]:
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.
# If on Google Cloud Notebooks, then don't execute this code
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
if not IS_GOOGLE_CLOUD_NOTEBOOK:
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
!gcloud config set project $PROJECT_ID
# 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 [ ]:
!gcloud services enable compute.googleapis.com \
containerregistry.googleapis.com \
aiplatform.googleapis.comIn [ ]:
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")In [ ]:
BUCKET_NAME = "gs://{}-bucket".format(PROJECT_ID)
!gsutil mb -l us-central1 $BUCKET_NAME # You only need to run this onceIn [ ]:
import matplotlib.pyplot as plt
import pandas as pd
# We'll use this beta library for metadata querying
from google.cloud import aiplatform, aiplatform_v1beta1
from google.cloud.aiplatform import pipeline_jobs
from kfp.v2 import compiler, dsl
from kfp.v2.dsl import (Artifact, Dataset, Input, Metrics, Model, Output,
OutputPath, component)In [ ]:
PATH = get_ipython().run_line_magic("env", "PATH")
%env PATH={PATH}:/home/jupyter/.local/bin
REGION = "us-central1"
PIPELINE_ROOT = f"{BUCKET_NAME}/pipeline_root/"
PIPELINE_ROOTIn [ ]:
aiplatform.init(project=PROJECT_ID, location=REGION)In [ ]:
@component(
packages_to_install=["google-cloud-bigquery", "pandas", "pyarrow"],
base_image="python:3.9",
output_component_file="create_dataset.yaml",
)
def get_dataframe(bq_table: str, output_data_path: OutputPath("Dataset")):
from google.cloud import bigquery
bqclient = bigquery.Client()
table = bigquery.TableReference.from_string(bq_table)
rows = bqclient.list_rows(table)
dataframe = rows.to_dataframe(
create_bqstorage_client=True,
)
dataframe = dataframe.sample(frac=1, random_state=2)
dataframe.to_csv(output_data_path)In [ ]:
@component(
packages_to_install=["sklearn", "pandas", "joblib"],
base_image="python:3.9",
output_component_file="beans_model_component.yaml",
)
def sklearn_train(
dataset: Input[Dataset], metrics: Output[Metrics], model: Output[Model]
):
import pandas as pd
from joblib import dump
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
df = pd.read_csv(dataset.path)
labels = df.pop("Class").tolist()
data = df.values.tolist()
x_train, x_test, y_train, y_test = train_test_split(data, labels)
skmodel = DecisionTreeClassifier()
skmodel.fit(x_train, y_train)
score = skmodel.score(x_test, y_test)
print("accuracy is:", score)
metrics.log_metric("accuracy", (score * 100.0))
metrics.log_metric("framework", "Scikit Learn")
metrics.log_metric("dataset_size", len(df))
dump(skmodel, model.path + ".joblib")In [ ]:
@component(
packages_to_install=["google-cloud-aiplatform"],
base_image="python:3.9",
output_component_file="beans_deploy_component.yaml",
)
def deploy_model(
model: Input[Model],
project: str,
region: str,
vertex_endpoint: Output[Artifact],
vertex_model: Output[Model],
):
from google.cloud import aiplatform
aiplatform.init(project=project, location=region)
deployed_model = aiplatform.Model.upload(
display_name="beans-model-pipeline",
artifact_uri=model.uri.replace("model", ""),
serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.0-24:latest",
)
endpoint = deployed_model.deploy(machine_type="n1-standard-4")
# Save data to the output params
vertex_endpoint.uri = endpoint.resource_name
vertex_model.uri = deployed_model.resource_nameIn [ ]:
@dsl.pipeline(
# Default pipeline root. You can override it when submitting the pipeline.
pipeline_root=PIPELINE_ROOT,
# A name for the pipeline.
name="mlmd-pipeline",
)
def pipeline(
bq_table: str = "",
output_data_path: str = "data.csv",
project: str = PROJECT_ID,
region: str = REGION,
):
dataset_task = get_dataframe(bq_table)
model_task = sklearn_train(dataset_task.output)
deploy_model(model=model_task.outputs["model"], project=project, region=region)In [ ]:
compiler.Compiler().compile(pipeline_func=pipeline, package_path="mlmd_pipeline.json")In [ ]:
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")In [ ]:
run1 = pipeline_jobs.PipelineJob(
display_name="mlmd-pipeline",
template_path="mlmd_pipeline.json",
job_id="mlmd-pipeline-small-{}".format(TIMESTAMP),
parameter_values={"bq_table": "sara-vertex-demos.beans_demo.small_dataset"},
enable_caching=True,
)In [ ]:
run2 = pipeline_jobs.PipelineJob(
display_name="mlmd-pipeline",
template_path="mlmd_pipeline.json",
job_id="mlmd-pipeline-large-{}".format(TIMESTAMP),
parameter_values={"bq_table": "sara-vertex-demos.beans_demo.large_dataset"},
enable_caching=True,
)In [ ]:
run1.run()In [ ]:
run2.run()In [ ]:
df = aiplatform.get_pipeline_df(pipeline="mlmd-pipeline")
print(df)In [ ]:
plt.plot(df["metric.dataset_size"], df["metric.accuracy"], label="Accuracy")
plt.title("Accuracy and dataset size")
plt.legend(loc=4)
plt.show()In [ ]:
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)
metadata_client = aiplatform_v1beta1.MetadataServiceClient(
client_options={"api_endpoint": API_ENDPOINT}
)In [ ]:
MODEL_FILTER = 'schema_title = "system.Model"'
artifact_request = aiplatform_v1beta1.ListArtifactsRequest(
parent="projects/{}/locations/{}/metadataStores/default".format(PROJECT_ID, REGION),
filter=MODEL_FILTER,
)
model_artifacts = metadata_client.list_artifacts(artifact_request)In [ ]:
LIVE_FILTER = 'create_time > "2021-08-10T00:00:00-00:00" AND state = LIVE'
artifact_req = {
"parent": "projects/{}/locations/{}/metadataStores/default".format(
PROJECT_ID, REGION
),
"filter": LIVE_FILTER,
}
live_artifacts = metadata_client.list_artifacts(artifact_req)In [ ]:
data = {"uri": [], "createTime": [], "type": []}
for i in live_artifacts:
data["uri"].append(i.uri)
data["createTime"].append(i.create_time)
data["type"].append(i.schema_title)
df = pd.DataFrame.from_dict(data)
print(df)
Run in Colab
View on GitHub