mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
28 KiB
28 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 --upgrade --quiet google-cloud-aiplatform \
tensorflow==2.15.1In [ ]:
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"}
# Set the project id
! gcloud config set project {PROJECT_ID}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 [ ]:
from google.cloud import aiplatformIn [ ]:
aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)In [ ]:
IMPORT_FILE = "gs://cloud-samples-data/ai-platform/flowers/flowers.csv"In [ ]:
if "IMPORT_FILES" in globals():
FILE = IMPORT_FILES[0]
else:
FILE = IMPORT_FILE
count = ! gcloud storage cat $FILE | wc -l
print("Number of Examples", int(count[0]))
print("First 10 rows")
! gcloud storage cat $FILE | headIn [ ]:
dataset = aiplatform.ImageDataset.create(
display_name="Flowers",
gcs_source=[IMPORT_FILE],
import_schema_uri=aiplatform.schema.dataset.ioformat.image.single_label_classification,
)
print(dataset.resource_name)In [ ]:
dag = aiplatform.AutoMLImageTrainingJob(
display_name="flowers",
prediction_type="classification",
multi_label=False,
model_type="CLOUD",
base_model=None,
)
print(dag)In [ ]:
model = dag.run(
dataset=dataset,
model_display_name="flowers",
training_fraction_split=0.8,
validation_fraction_split=0.1,
test_fraction_split=0.1,
budget_milli_node_hours=8000,
disable_early_stopping=False,
)In [ ]:
model_evaluations = model.list_model_evaluations()
for model_evaluation in model_evaluations:
print(model_evaluation.to_dict())In [ ]:
test_items = !gcloud storage cat $IMPORT_FILE | head -n2
if len(str(test_items[0]).split(",")) == 3:
_, test_item_1, test_label_1 = str(test_items[0]).split(",")
_, test_item_2, test_label_2 = str(test_items[1]).split(",")
else:
test_item_1, test_label_1 = str(test_items[0]).split(",")
test_item_2, test_label_2 = str(test_items[1]).split(",")
print(test_item_1, test_label_1)
print(test_item_2, test_label_2)In [ ]:
file_1 = test_item_1.split("/")[-1]
file_2 = test_item_2.split("/")[-1]
! gcloud storage cp $test_item_1 $BUCKET_URI/$file_1
! gcloud storage cp $test_item_2 $BUCKET_URI/$file_2
test_item_1 = BUCKET_URI + "/" + file_1
test_item_2 = BUCKET_URI + "/" + file_2In [ ]:
import json
import tensorflow as tf
gcs_input_uri = BUCKET_URI + "/test.jsonl"
with tf.io.gfile.GFile(gcs_input_uri, "w") as f:
data = {"content": test_item_1, "mime_type": "image/jpeg"}
f.write(json.dumps(data) + "\n")
data = {"content": test_item_2, "mime_type": "image/jpeg"}
f.write(json.dumps(data) + "\n")
print(gcs_input_uri)
! gcloud storage cat $gcs_input_uriIn [ ]:
batch_predict_job = model.batch_predict(
job_display_name="flowers",
gcs_source=gcs_input_uri,
gcs_destination_prefix=BUCKET_URI,
sync=False,
)
print(batch_predict_job)In [ ]:
batch_predict_job.wait()In [ ]:
import json
import tensorflow as tf
bp_iter_outputs = batch_predict_job.iter_outputs()
prediction_results = list()
for blob in bp_iter_outputs:
if blob.name.split("/")[-1].startswith("prediction"):
prediction_results.append(blob.name)
tags = list()
for prediction_result in prediction_results:
gfile_name = f"gs://{bp_iter_outputs.bucket.name}/{prediction_result}"
with tf.io.gfile.GFile(name=gfile_name, mode="r") as gfile:
for line in gfile.readlines():
line = json.loads(line)
print(line)
breakIn [ ]:
# Delete the dataset using the Vertex dataset object
dataset.delete()
# Delete the model using the Vertex model object
model.delete()
# Delete the AutoML trainig job
dag.delete()
# Delete the batch prediction job
batch_predict_job.delete()
# Delete the cloud storage bucket
delete_bucket = False # set True for deletion
if delete_bucket:
! gcloud storage rm --recursive $BUCKET_URI