mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
75 KiB
75 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 [ ]:
! pip3 install -U google-cloud-aiplatform --userIn [ ]:
! pip3 install google-cloud-storageIn [ ]:
import os
if not os.getenv("AUTORUN"):
# 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 = "us-central1" # @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 Google Cloud account. This provides access
# to your Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# If on Vertex, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this tutorial in a notebook locally, replace the string
# below with the path to your service account key and run this cell to
# authenticate your Google Cloud account.
else:
%env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json
# Log in to your account on Google Cloud
! gcloud auth loginIn [ ]:
BUCKET_NAME = "[your-bucket-name]" # @param {type:"string"}In [ ]:
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMPIn [ ]:
! gcloud storage buckets create --location=$REGION gs://$BUCKET_NAMEIn [ ]:
! gcloud storage ls --all-versions --long gs://$BUCKET_NAMEIn [ ]:
import os
import sys
import time
from google.cloud.aiplatform import gapic as aip
from google.protobuf import json_format
from google.protobuf.json_format import MessageToJson, ParseDict
from google.protobuf.struct_pb2 import Struct, ValueIn [ ]:
# API Endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)
# Vertex AI location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGIONIn [ ]:
# Video Dataset type
VIDEO_SCHEMA = "google-cloud-aiplatform/schema/dataset/metadata/video_1.0.0.yaml"
# Video Labeling type
IMPORT_SCHEMA_VIDEO_OBJECT_TRACKING = "gs://google-cloud-aiplatform/schema/dataset/ioformat/video_object_tracking_io_format_1.0.0.yaml"
# Video Training task
TRAINING_VIDEO_OBJECT_TRACKING_SCHEMA = "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_object_tracking_1.0.0.yaml"In [ ]:
# client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}
def create_dataset_client():
client = aip.DatasetServiceClient(client_options=client_options)
return client
def create_model_client():
client = aip.ModelServiceClient(client_options=client_options)
return client
def create_pipeline_client():
client = aip.PipelineServiceClient(client_options=client_options)
return client
def create_endpoint_client():
client = aip.EndpointServiceClient(client_options=client_options)
return client
def create_prediction_client():
client = aip.PredictionServiceClient(client_options=client_options)
return client
def create_job_client():
client = aip.JobServiceClient(client_options=client_options)
return client
clients = {}
clients["dataset"] = create_dataset_client()
clients["model"] = create_model_client()
clients["pipeline"] = create_pipeline_client()
clients["endpoint"] = create_endpoint_client()
clients["prediction"] = create_prediction_client()
clients["job"] = create_job_client()
for client in clients.items():
print(client)In [ ]:
IMPORT_FILE = "gs://automl-video-demo-data/traffic_videos/traffic_videos_labels.csv"In [ ]:
! gcloud storage cat $IMPORT_FILE | head -n 10In [ ]:
DATA_SCHEMA = VIDEO_SCHEMA
dataset = {
"display_name": "traffic_" + TIMESTAMP,
"metadata_schema_uri": "gs://" + DATA_SCHEMA,
}
print(
MessageToJson(
aip.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__["_pb"]
)
)In [ ]:
request = clients["dataset"].create_dataset(parent=PARENT, dataset=dataset)In [ ]:
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))In [ ]:
# The full unique ID for the dataset
dataset_id = result.name
# The short numeric ID for the dataset
dataset_short_id = dataset_id.split("/")[-1]
print(dataset_id)In [ ]:
LABEL_SCHEMA = IMPORT_SCHEMA_VIDEO_OBJECT_TRACKING
import_config = {
"gcs_source": {"uris": [IMPORT_FILE]},
"import_schema_uri": LABEL_SCHEMA,
}
print(
MessageToJson(
aip.ImportDataRequest(
name=dataset_short_id, import_configs=[import_config]
).__dict__["_pb"]
)
)In [ ]:
request = clients["dataset"].import_data(
name=dataset_id, import_configs=[import_config]
)In [ ]:
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))In [ ]:
TRAINING_SCHEMA = TRAINING_VIDEO_OBJECT_TRACKING_SCHEMA
task = Value(struct_value=Struct(fields={"model_type": Value(string_value="CLOUD")}))
training_pipeline = {
"display_name": "traffic_" + TIMESTAMP,
"training_task_definition": TRAINING_SCHEMA,
"training_task_inputs": task,
"input_data_config": {
"dataset_id": dataset_short_id,
"fraction_split": {"training_fraction": 0.8, "test_fraction": 0.2},
},
"model_to_upload": {"display_name": "traffic_" + TIMESTAMP},
}
print(
MessageToJson(
aip.CreateTrainingPipelineRequest(
parent=PARENT, training_pipeline=training_pipeline
).__dict__["_pb"]
)
)In [ ]:
request = clients["pipeline"].create_training_pipeline(
parent=PARENT, training_pipeline=training_pipeline
)In [ ]:
print(MessageToJson(request.__dict__["_pb"]))In [ ]:
# The full unique ID for the training pipeline
training_pipeline_id = request.name
# The short numeric ID for the training pipeline
training_pipeline_short_id = training_pipeline_id.split("/")[-1]
print(training_pipeline_id)In [ ]:
request = clients["pipeline"].get_training_pipeline(name=training_pipeline_id)In [ ]:
print(MessageToJson(request.__dict__["_pb"]))In [ ]:
while True:
response = clients["pipeline"].get_training_pipeline(name=training_pipeline_id)
if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:
print("Training job has not completed:", response.state)
model_to_deploy_name = None
if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:
break
else:
model_id = response.model_to_upload.name
print("Training Time:", response.end_time - response.start_time)
break
time.sleep(60)
print(model_id)In [ ]:
request = clients["model"].list_model_evaluations(parent=model_id)In [ ]:
import json
model_evaluations = [json.loads(MessageToJson(me.__dict__["_pb"])) for me in request]
# The evaluation slice
evaluation_slice = request.model_evaluations[0].name
print(json.dumps(model_evaluations, indent=2))In [ ]:
request = clients["model"].get_model_evaluation(name=evaluation_slice)In [ ]:
print(MessageToJson(request.__dict__["_pb"]))In [ ]:
test_items = ! gcloud storage cat $IMPORT_FILE | head -n25
cols_1 = test_items[0].split(",")
cols_2 = test_items[-1].split(",")
if len(cols_1) > 12:
test_item_1 = str(cols_1[1])
test_item_2 = str(cols_2[1])
test_label_1 = str(cols_1[5:])
test_label_2 = str(cols_2[5:])
else:
test_item_1 = str(cols_1[0])
test_item_2 = str(cols_2[0])
test_label_1 = str(cols_1[4:])
test_label_2 = str(cols_2[4:])
print(test_item_1, test_label_1)
print(test_item_2, test_label_2)In [ ]:
import json
import tensorflow as tf
gcs_input_uri = "gs://" + BUCKET_NAME + "/test.jsonl"
with tf.io.gfile.GFile(gcs_input_uri, "w") as f:
data = {
"content": test_item_1,
"mimeType": "video/avi",
"timeSegmentStart": "0.0s",
"timeSegmentEnd": "inf",
}
f.write(json.dumps(data) + "\n")
data = {
"content": test_item_2,
"mimeType": "video/avi",
"timeSegmentStart": "0.0s",
"timeSegmentEnd": "inf",
}
f.write(json.dumps(data) + "\n")
print(gcs_input_uri)
!gcloud storage cat $gcs_input_uriIn [ ]:
batch_prediction_job = {
"display_name": "traffic_" + TIMESTAMP,
# Format: 'projects/{project}/locations/{location}/models/{model_id}'
"model": model_id,
"model_parameters": json_format.ParseDict(
{"confidenceThreshold": 0.5, "maxPredictions": 2}, Value()
),
"input_config": {
"instances_format": "jsonl",
"gcs_source": {"uris": [gcs_input_uri]},
},
"output_config": {
"predictions_format": "jsonl",
"gcs_destination": {
"output_uri_prefix": "gs://" + f"{BUCKET_NAME}/batch_output/"
},
},
"dedicated_resources": {
"machine_spec": {"machine_type": "n1-standard-4", "accelerator_count": 0},
"starting_replica_count": 1,
"max_replica_count": 1,
},
}
print(
MessageToJson(
aip.CreateBatchPredictionJobRequest(
parent=PARENT, batch_prediction_job=batch_prediction_job
).__dict__["_pb"]
)
)Warning:
Output truncated. This notebook contains too many cells to display efficiently.