mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
32 KiB
32 KiB
In [ ]:
# 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.In [ ]:
! pip3 install --upgrade --quiet tensorflow
! pip3 install --upgrade --quiet google-cloud-aiplatform
! gcloud components update --quietIn [ ]:
# Automatically restart kernel after installs so that your environment can access the new packages
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
# Set the project id
! gcloud config set project {PROJECT_ID}In [ ]:
REGION = "us-central1" # @param {type: "string"}In [ ]:
# ! gcloud auth loginIn [ ]:
# from google.colab import auth
# auth.authenticate_user()In [ ]:
BUCKET_URI = f"gs://your-bucket-name-{PROJECT_ID}-unique" # @param {type:"string"}In [ ]:
! gcloud storage buckets create --location={REGION} {BUCKET_URI}In [ ]:
import os
import google.cloud.aiplatform as aiplatformIn [ ]:
aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)In [ ]:
TRAIN_IMAGE = "us-docker.pkg.dev/vertex-ai-restricted/builtin-algorithm/tab_net_v2"
print("Training container:", TRAIN_IMAGE)In [ ]:
if os.getenv("IS_TESTING_TF"):
TF = os.getenv("IS_TESTING_TF")
else:
TF = "2.5".replace(".", "-")
if TF[0] == "2":
DEPLOY_VERSION = "tf2-cpu.{}".format(TF)
else:
DEPLOY_VERSION = "tf-cpu.{}".format(TF)
DEPLOY_IMAGE = "{}-docker.pkg.dev/vertex-ai/prediction/{}:latest".format(
REGION.split("-")[0], DEPLOY_VERSION
)
print("Deployment container:", DEPLOY_IMAGE)In [ ]:
# Please note that if you use csv input, the first column is the label column.
IMPORT_FILE = "petfinder-tabular-classification-tabnet-with-header.csv"
TRAINING_DATA_PATH = f"{BUCKET_URI}/data/petfinder/train.csv"
! gcloud storage cp gs://cloud-samples-data/ai-platform-unified/datasets/tabular/{IMPORT_FILE} {TRAINING_DATA_PATH}In [ ]:
DATASET_NAME = "petfinder" # Change to your dataset name.
job = aiplatform.CustomContainerTrainingJob(
display_name=f"{DATASET_NAME}",
container_uri=TRAIN_IMAGE,
model_serving_container_image_uri=DEPLOY_IMAGE,
)
print(job)In [ ]:
ALGORITHM = "tabnet"
MODEL_TYPE = "classification"
MODEL_NAME = f"{DATASET_NAME}_{ALGORITHM}_{MODEL_TYPE}"
OUTPUT_DIR = f"{BUCKET_URI}/{MODEL_NAME}"
print("Output dir: ", OUTPUT_DIR)
CMDARGS = [
"--preprocess",
"--data_has_header",
f"--training_data_path={TRAINING_DATA_PATH}",
f"--job-dir={OUTPUT_DIR}",
f"--model_type={MODEL_TYPE}",
"--max_steps=2000",
"--batch_size=4096",
"--learning_rate=0.01",
"--prediction_raw_inputs",
"--exclude_key",
]In [ ]:
MODEL_DIR = OUTPUT_DIR
MACHINE_TYPE = "n1-standard-4"
model = job.run(
model_display_name=f"{DATASET_NAME}",
args=CMDARGS,
replica_count=1,
machine_type=MACHINE_TYPE,
base_output_dir=MODEL_DIR,
sync=True,
)
print(model.gca_resource)In [ ]:
job.delete()In [ ]:
# This is for display only; you can name the range anything.
PEERING_RANGE_NAME = "vertex-ai-prediction-peering-range"
NETWORK = "default"
# NOTE: `prefix-length=16` means a CIDR block with mask /16 will be
# reserved for use by Google services, such as Vertex AI.
! gcloud compute addresses create $PEERING_RANGE_NAME \
--global \
--prefix-length=16 \
--description="peering range for Google service" \
--network=$NETWORK \
--purpose=VPC_PEERINGIn [ ]:
! gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--network=$NETWORK \
--ranges=$PEERING_RANGE_NAME \
--project=$PROJECT_IDIn [ ]:
! gcloud compute networks peerings list --network $NETWORKIn [ ]:
project_number = model.resource_name.split("/")[1]
print(project_number)
full_network_name = f"projects/{project_number}/global/networks/{NETWORK}"
full_network_nameIn [ ]:
if not os.getenv("IS_TESTING"):
private_endpoint = aiplatform.PrivateEndpoint.create(
display_name=f"{DATASET_NAME}_private_endpoint",
network=full_network_name,
)In [ ]:
if not os.getenv("IS_TESTING"):
private_endpoint.gca_resourceIn [ ]:
DEPLOYED_NAME = f"{DATASET_NAME}_deployed_model"
if not os.getenv("IS_TESTING"):
response = private_endpoint.deploy(
model=model,
deployed_model_display_name=DEPLOYED_NAME,
machine_type="n1-standard-4",
)In [ ]:
import tensorflow as tf
loaded = tf.saved_model.load(MODEL_DIR + "/model")
loaded.signaturesIn [ ]:
if not os.getenv("IS_TESTING"):
prediction = private_endpoint.predict(
[
{
"Age": 3,
"Breed1": "Tabby",
"Color1": "Black",
"Color2": "White",
"Fee": 100,
"FurLength": "Short",
"Gender": "Male",
"Health": "Healthy",
"MaturitySize": "Small",
"PhotoAmt": 2,
"Sterilized": "No",
"Type": "Cat",
"Vaccinated": "No",
}
]
)
print(prediction)In [ ]:
delete_bucket = False
try:
private_endpoint.delete(force=True)
model.delete()
except Exception as e:
print(e)
if delete_bucket or os.getenv("IS_TESTING"):
! gcloud storage rm --recursive $BUCKET_URI