mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
43 KiB
43 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 [ ]:
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} --upgrade google-cloud-aiplatformIn [ ]:
# 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 [ ]:
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 = "[your-project-id]" # @param {type:"string"}
print("Project ID: ", PROJECT_ID)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 [ ]:
from google.cloud import aiplatform
from google.cloud.aiplatform import Feature, Featurestore
REGION = "[your-region]" # @param {type:"string"}
FEATURESTORE_ID = "movie_prediction"
INPUT_CSV_FILE = "gs://cloud-samples-data-us-central1/vertex-ai/feature-store/datasets/movie_prediction.csv"
ONLINE_STORE_FIXED_NODE_COUNT = 1
aiplatform.init(project=PROJECT_ID, location=REGION)In [ ]:
fs = Featurestore.create(
featurestore_id=FEATURESTORE_ID,
online_store_fixed_node_count=ONLINE_STORE_FIXED_NODE_COUNT,
project=PROJECT_ID,
location=REGION,
sync=True,
)In [ ]:
fs = Featurestore(
featurestore_name=FEATURESTORE_ID,
project=PROJECT_ID,
location=REGION,
)
print(fs.gca_resource)In [ ]:
# Create users entity type
users_entity_type = fs.create_entity_type(
entity_type_id="users",
description="Users entity",
)In [ ]:
# Create movies entity type
movies_entity_type = fs.create_entity_type(
entity_type_id="movies",
description="Movies entity",
)In [ ]:
users_entity_type = fs.get_entity_type(entity_type_id="users")
movies_entity_type = fs.get_entity_type(entity_type_id="movies")
print(users_entity_type)
print(movies_entity_type)In [ ]:
fs.list_entity_types()In [ ]:
# to create features one at a time use
users_feature_age = users_entity_type.create_feature(
feature_id="age",
value_type="INT64",
description="User age",
)
users_feature_gender = users_entity_type.create_feature(
feature_id="gender",
value_type="STRING",
description="User gender",
)
users_feature_liked_genres = users_entity_type.create_feature(
feature_id="liked_genres",
value_type="STRING_ARRAY",
description="An array of genres this user liked",
)In [ ]:
users_entity_type.list_features()In [ ]:
movies_feature_configs = {
"title": {
"value_type": "STRING",
"description": "The title of the movie",
},
"genres": {
"value_type": "STRING",
"description": "The genre of the movie",
},
"average_rating": {
"value_type": "DOUBLE",
"description": "The average rating for the movie, range is [1.0-5.0]",
},
}In [ ]:
movie_features = movies_entity_type.batch_create_features(
feature_configs=movies_feature_configs,
)In [ ]:
my_features = Feature.search(query="featurestore_id={}".format(FEATURESTORE_ID))
my_featuresIn [ ]:
double_features = Feature.search(
query="value_type=DOUBLE AND featurestore_id={}".format(FEATURESTORE_ID)
)
double_features[0].gca_resourceIn [ ]:
title_features = Feature.search(
query="feature_id:title AND value_type=STRING AND featurestore_id={}".format(
FEATURESTORE_ID
)
)
title_features[0].gca_resourceIn [ ]:
USERS_FEATURES_IDS = [feature.name for feature in users_entity_type.list_features()]
USERS_FEATURE_TIME = "update_time"
USERS_ENTITY_ID_FIELD = "user_id"
USERS_GCS_SOURCE_URI = (
"gs://cloud-samples-data-us-central1/vertex-ai/feature-store/datasets/users.avro"
)
GCS_SOURCE_TYPE = "avro"
WORKER_COUNT = 1
print(USERS_FEATURES_IDS)In [ ]:
users_entity_type.ingest_from_gcs(
feature_ids=USERS_FEATURES_IDS,
feature_time=USERS_FEATURE_TIME,
entity_id_field=USERS_ENTITY_ID_FIELD,
gcs_source_uris=USERS_GCS_SOURCE_URI,
gcs_source_type=GCS_SOURCE_TYPE,
worker_count=WORKER_COUNT,
sync=False,
)In [ ]:
MOVIES_FEATURES_IDS = [feature.name for feature in movies_entity_type.list_features()]
MOVIES_FEATURE_TIME = "update_time"
MOVIES_ENTITY_ID_FIELD = "movie_id"
MOVIES_GCS_SOURCE_URI = (
"gs://cloud-samples-data-us-central1/vertex-ai/feature-store/datasets/movies.avro"
)
GCS_SOURCE_TYPE = "avro"
WORKER_COUNT = 1
print(MOVIES_FEATURES_IDS)In [ ]:
movies_entity_type.ingest_from_gcs(
feature_ids=MOVIES_FEATURES_IDS,
feature_time=MOVIES_FEATURE_TIME,
entity_id_field=MOVIES_ENTITY_ID_FIELD,
gcs_source_uris=MOVIES_GCS_SOURCE_URI,
gcs_source_type=GCS_SOURCE_TYPE,
worker_count=WORKER_COUNT,
sync=False,
)In [ ]:
users_entity_type.read(entity_ids="bob")In [ ]:
movies_entity_type.read(entity_ids="movie_01", feature_ids="title")In [ ]:
users_entity_type.read(entity_ids=["bob", "alice"])In [ ]:
movies_entity_type.read(
entity_ids=["movie_02", "movie_03", "movie_04"], feature_ids=["title, genres"]
)In [ ]:
from datetime import datetime
from google.cloud import bigqueryIn [ ]:
# Output dataset
DESTINATION_DATA_SET = "movie_predictions" # @param {type:"string"}
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
DESTINATION_DATA_SET = "{prefix}_{timestamp}".format(
prefix=DESTINATION_DATA_SET, timestamp=TIMESTAMP
)
# Output table. Make sure that the table does NOT already exist; the BatchReadFeatureValues API cannot overwrite an existing table
DESTINATION_TABLE_NAME = "training_data" # @param {type:"string"}
DESTINATION_PATTERN = "bq://{project}.{dataset}.{table}"
DESTINATION_TABLE_URI = DESTINATION_PATTERN.format(
project=PROJECT_ID, dataset=DESTINATION_DATA_SET, table=DESTINATION_TABLE_NAME
)In [ ]:
# Create dataset
client = bigquery.Client(project=PROJECT_ID)
dataset_id = "{}.{}".format(client.project, DESTINATION_DATA_SET)
dataset = bigquery.Dataset(dataset_id)
dataset.location = REGION
dataset = client.create_dataset(dataset)
print("Created dataset {}.{}".format(client.project, dataset.dataset_id))In [ ]:
SERVING_FEATURE_IDS = {
# to choose all the features use 'entity_type_id: ['*']'
"users": ["age", "gender", "liked_genres"],
"movies": ["title", "average_rating", "genres"],
}In [ ]:
fs.batch_serve_to_bq(
bq_destination_output_uri=DESTINATION_TABLE_URI,
serving_feature_ids=SERVING_FEATURE_IDS,
read_instances_uri=INPUT_CSV_FILE,
)In [ ]:
# Delete Featurestore
fs.delete(force=True)In [ ]:
# Delete BigQuery dataset
client = bigquery.Client(project=PROJECT_ID)
client.delete_dataset(
DESTINATION_DATA_SET, delete_contents=True, not_found_ok=True
) # Make an API request.
print("Deleted dataset '{}'.".format(DESTINATION_DATA_SET))