mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
33 KiB
33 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
! pip3 install --upgrade --quiet google-cloud-aiplatform \
google-cloud-storage \
kfp \
google-cloud-pipeline-components
if os.getenv("IS_TESTING"):
! pip3 install --upgrade matplotlib $USER_FLAG -qIn [ ]:
import sys
if "google.colab" in sys.modules:
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)In [ ]:
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}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 [ ]:
BUCKET_URI = f"gs://your-bucket-name-{PROJECT_ID}-unique" # @param {type:"string"}In [ ]:
! gcloud storage buckets create --location {LOCATION} --project {PROJECT_ID} {BUCKET_URI}In [ ]:
SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"}In [ ]:
import sys
IS_COLAB = "google.colab" in sys.modules
if (
SERVICE_ACCOUNT == ""
or SERVICE_ACCOUNT is None
or SERVICE_ACCOUNT == "[your-service-account]"
):
# Get your service account from gcloud
if not IS_COLAB:
shell_output = !gcloud auth list 2>/dev/null
SERVICE_ACCOUNT = shell_output[2].replace("*", "").strip()
if IS_COLAB:
shell_output = ! gcloud projects describe $PROJECT_ID
project_number = shell_output[-1].split(":")[1].strip().replace("'", "")
SERVICE_ACCOUNT = f"{project_number}-compute@developer.gserviceaccount.com"
print("Service Account:", SERVICE_ACCOUNT)In [ ]:
! gcloud storage buckets add-iam-policy-binding $BUCKET_URI --member=serviceAccount:{SERVICE_ACCOUNT} --role=roles/storage.objectCreator
! gcloud storage buckets add-iam-policy-binding $BUCKET_URI --member=serviceAccount:{SERVICE_ACCOUNT} --role=roles/storage.objectViewerIn [ ]:
import google.cloud.aiplatform as aip
from kfp import compiler, dsl
from kfp.dsl import ClassificationMetrics, Metrics, Output, componentIn [ ]:
PIPELINE_NAME = "metrics-pipeline-v2"
PIPELINE_ROOT = "{}/pipeline_root/iris".format(BUCKET_URI)In [ ]:
aip.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)In [ ]:
@component(
packages_to_install=["scikit-learn==1.2", "numpy==1.26.4"], base_image="python:3.9"
)
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)
compiler.Compiler().compile(wine_classification, "wine_classification_component.yaml")In [ ]:
@component(
packages_to_install=["scikit-learn==1.2", "numpy==1.26.4"], 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=["scikit-learn==1.2", "numpy==1.26.4"],
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 [ ]:
compiler.Compiler().compile(
pipeline_func=pipeline,
package_path="tabular_classification_pipeline.yaml",
)In [ ]:
DISPLAY_NAME = "iris_" + UUID
job1 = aip.PipelineJob(
display_name=DISPLAY_NAME,
template_path="tabular_classification_pipeline.yaml",
job_id=f"tabular-classification-v2{UUID}-1",
pipeline_root=PIPELINE_ROOT,
parameter_values={"seed": 7, "splits": 10},
)
job1.run()In [ ]:
job2 = aip.PipelineJob(
display_name="iris_" + UUID,
template_path="tabular_classification_pipeline.yaml",
job_id=f"tabular-classification-pipeline-v2{UUID}-2",
pipeline_root=PIPELINE_ROOT,
parameter_values={"seed": 5, "splits": 7},
)
job2.run()In [ ]:
pipeline_df = aip.get_pipeline_df(pipeline=PIPELINE_NAME)
print(pipeline_df.head(2))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"],
)
ax.set_yscale("symlog")
ax.legend(bbox_to_anchor=(1.0, 0.5))In [ ]:
try:
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()
except Exception as e:
print(e)In [ ]:
delete_bucket = False
job1.delete()
job2.delete()
if delete_bucket:
! gcloud storage rm --recursive $BUCKET_URI
! rm -rf tabular_classification_pipeline.yaml