mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
36 KiB
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.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 --upgradeIn [ ]:
# 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 [ ]:
!python3 -c "import kfp; print('KFP SDK version: {}'.format(kfp.__version__))"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 = "python-docs-samples-tests" # @param {type:"string"}In [ ]:
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")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 ''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-" + TIMESTAMPIn [ ]:
! gsutil mb -l $REGION $BUCKET_NAMEIn [ ]:
! gsutil ls -al $BUCKET_NAMEIn [ ]:
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_ROOTIn [ ]:
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 AIPlatformClientIn [ ]:
aiplatform.init(project=PROJECT_ID)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)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.
)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))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: F841In [ ]:
from kfp.v2 import compiler # noqa: F811
compiler.Compiler().compile(
pipeline_func=pipeline, package_path="metrics_pipeline_job.json"
)In [ ]:
from kfp.v2.google.client import AIPlatformClient # noqa: F811
api_client = AIPlatformClient(
project_id=PROJECT_ID,
region=REGION,
)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},
)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},
)In [ ]:
pipeline_df = aiplatform.get_pipeline_df(pipeline="metrics-pipeline-v2")
pipeline_dfIn [ ]:
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))In [ ]:
pipeline_df = aiplatform.get_pipeline_df(pipeline="metrics-pipeline-v2")
pipeline_dfIn [ ]:
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()In [ ]:
# Warning: this command will delete ALL Cloud Storage objects under the PIPELINE_ROOT path.
# ! gsutil -m rm -r $PIPELINE_ROOT
Run in Colab
View on GitHub