Vertex AI API客户端库
项目描述
Vertex AI:Google Vertex AI是一个集成的机器学习工具和服务套件,用于使用AutoML或自定义代码构建和使用ML模型。它为初学者和专家提供了一个完整的机器学习开发生命周期的最佳工作台。
快速入门
为了使用此库,您首先需要完成以下步骤
安装
使用pip在此虚拟环境中安装此库。 虚拟环境是一种用于创建隔离Python环境的工具。它解决的基本问题是依赖关系和版本问题,以及间接的权限问题。
使用虚拟环境,您可以在无需系统安装权限的情况下安装此库,并且不会与已安装的系统依赖冲突。
Mac/Linux
pip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-aiplatform
Windows
pip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-cloud-aiplatform
支持的Python版本
Python >= 3.8
弃用的Python版本
Python <= 3.7。
此库与Python 3.6兼容的最后一个版本是google-cloud-aiplatform==1.12.1。
概述
本节提供了Vertex AI Python SDK的简要概述。您还可以参考vertex-ai-samples中的笔记本以获取示例。
所有公开的SDK功能都可以在google/cloud/aiplatform
目录中找到。底层,Vertex SDK建立在GAPIC之上,即Google API CodeGen。GAPIC库代码位于google/cloud/aiplatform_v1
和google/cloud/aiplatform_v1beta1
,它是由Google的服务proto文件自动生成的。
对于大多数开发者的编程需求,他们可以按照以下步骤确定要导入哪些库
首先查看
google/cloud/aiplatform
– 与GAPIC相比,Vertex SDK的API几乎总是更易于使用且更简洁如果您找不到所需的特性,请查看
aiplatform_v1
以查看是否在GAPIC中可用如果它仍处于测试阶段,它将在
aiplatform_v1beta1
中可用
如果以上任何一种情况都无法帮助您找到完成任务的正确工具,请随时在GitHub上打开一个问题并向我们发送功能请求。
导入
可以通过导入以下命名空间来使用基于Vertex AI SDK资源的功能
from google.cloud import aiplatform
初始化
初始化SDK以存储您与SDK一起使用的常用配置。
aiplatform.init(
# your Google Cloud Project ID or number
# environment default used is not set
project='my-project',
# the Vertex AI region you will use
# defaults to us-central1
location='us-central1',
# Google Cloud Storage bucket in same region as location
# used to stage artifacts
staging_bucket='gs://my_staging_bucket',
# custom google.auth.credentials.Credentials
# environment default credentials used if not set
credentials=my_credentials,
# customer managed encryption key resource name
# will be applied to all Vertex AI resources if set
encryption_spec_key_name=my_encryption_key_name,
# the name of the experiment to use to track
# logged metrics and parameters
experiment='my-experiment',
# description of the experiment above
experiment_description='my experiment description'
)
数据集
Vertex AI提供托管表格、文本、图像和视频数据集。在SDK中,数据集可以用于下游训练模型。
创建表格数据集
my_dataset = aiplatform.TabularDataset.create(
display_name="my-dataset", gcs_source=['gs://path/to/my/dataset.csv'])
您还可以分步骤创建和导入数据集
from google.cloud import aiplatform
my_dataset = aiplatform.TextDataset.create(
display_name="my-dataset")
my_dataset.import_data(
gcs_source=['gs://path/to/my/dataset.csv'],
import_schema_uri=aiplatform.schema.dataset.ioformat.text.multi_label_classification
)
获取先前创建的Dataset
dataset = aiplatform.ImageDataset('projects/my-project/location/us-central1/datasets/{DATASET_ID}')
Vertex AI支持多种数据集模式。这些模式的引用可在aiplatform.schema.dataset
命名空间下找到。有关支持的数据集模式的更多信息,请参阅准备数据文档。
训练
Vertex AI Python SDK允许您训练自定义和AutoML模型。
您可以使用自定义Python脚本、自定义Python包或容器来训练自定义模型。
准备您的自定义代码
Vertex AI自定义训练使您能够在Vertex AI数据集上训练并生成Vertex AI模型。为此,您的脚本必须遵守以下合同
它必须从由训练服务填充的环境变量中读取数据集
os.environ['AIP_DATA_FORMAT'] # provides format of data
os.environ['AIP_TRAINING_DATA_URI'] # uri to training split
os.environ['AIP_VALIDATION_DATA_URI'] # uri to validation split
os.environ['AIP_TEST_DATA_URI'] # uri to test split
请访问在自定义训练应用程序中使用托管数据集以获取详细概述。
它必须将模型工件写入由训练服务填充的环境变量
os.environ['AIP_MODEL_DIR']
运行训练
job = aiplatform.CustomTrainingJob(
display_name="my-training-job",
script_path="training_script.py",
container_uri="us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-2:latest",
requirements=["gcsfs==0.7.1"],
model_serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-2:latest",
)
model = job.run(my_dataset,
replica_count=1,
machine_type="n1-standard-4",
accelerator_type='NVIDIA_TESLA_K80',
accelerator_count=1)
在上面的代码块中,my_dataset是在上面的数据集部分中创建的托管数据集。变量model是一个可部署或导出的托管Vertex AI模型。
AutoML
Vertex AI Python SDK支持AutoML表格、图像、文本、视频和预测。
要训练AutoML表格模型
dataset = aiplatform.TabularDataset('projects/my-project/location/us-central1/datasets/{DATASET_ID}')
job = aiplatform.AutoMLTabularTrainingJob(
display_name="train-automl",
optimization_prediction_type="regression",
optimization_objective="minimize-rmse",
)
model = job.run(
dataset=dataset,
target_column="target_column_name",
training_fraction_split=0.6,
validation_fraction_split=0.2,
test_fraction_split=0.2,
budget_milli_node_hours=1000,
model_display_name="my-automl-model",
disable_early_stopping=False,
)
模型
获取模型
model = aiplatform.Model('/projects/my-project/locations/us-central1/models/{MODEL_ID}')
上传模型
model = aiplatform.Model.upload(
display_name='my-model',
artifact_uri="gs://python/to/my/model/dir",
serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-2:latest",
)
部署模型
endpoint = model.deploy(machine_type="n1-standard-4",
min_replica_count=1,
max_replica_count=5
machine_type='n1-standard-4',
accelerator_type='NVIDIA_TESLA_K80',
accelerator_count=1)
请访问将模型导入Vertex AI以获取详细概述
模型评估
Python Vertex AI SDK 目前支持获取所有AutoML模型的模型评估指标。
要列出某个模型的全部模型评估
model = aiplatform.Model('projects/my-project/locations/us-central1/models/{MODEL_ID}')
evaluations = model.list_model_evaluations()
要获取特定模型的模型评估资源
model = aiplatform.Model('projects/my-project/locations/us-central1/models/{MODEL_ID}')
# returns the first evaluation with no arguments, you can also pass the evaluation ID
evaluation = model.get_model_evaluation()
eval_metrics = evaluation.metrics
您还可以通过传递模型评估的资源名称直接创建模型评估的引用
evaluation = aiplatform.ModelEvaluation(
evaluation_name='projects/my-project/locations/us-central1/models/{MODEL_ID}/evaluations/{EVALUATION_ID}')
或者,您可以通过传递模型和评估ID来创建评估的引用
evaluation = aiplatform.ModelEvaluation(
evaluation_name={EVALUATION_ID},
model_id={MODEL_ID})
批量预测
要创建批量预测作业
model = aiplatform.Model('/projects/my-project/locations/us-central1/models/{MODEL_ID}')
batch_prediction_job = model.batch_predict(
job_display_name='my-batch-prediction-job',
instances_format='csv',
machine_type='n1-standard-4',
gcs_source=['gs://path/to/my/file.csv'],
gcs_destination_prefix='gs://path/to/my/batch_prediction/results/',
service_account='my-sa@my-project.iam.gserviceaccount.com'
)
您还可以通过包含 sync=False 参数异步创建批量预测作业
batch_prediction_job = model.batch_predict(..., sync=False)
# wait for resource to be created
batch_prediction_job.wait_for_resource_creation()
# get the state
batch_prediction_job.state
# block until job is complete
batch_prediction_job.wait()
端点
要创建端点
endpoint = aiplatform.Endpoint.create(display_name='my-endpoint')
将模型部署到已创建的端点
model = aiplatform.Model('/projects/my-project/locations/us-central1/models/{MODEL_ID}')
endpoint.deploy(model,
min_replica_count=1,
max_replica_count=5,
machine_type='n1-standard-4',
accelerator_type='NVIDIA_TESLA_K80',
accelerator_count=1)
从端点获取预测
endpoint.predict(instances=[[6.7, 3.1, 4.7, 1.5], [4.6, 3.1, 1.5, 0.2]])
从端点卸载模型
endpoint.undeploy_all()
删除端点
endpoint.delete()
管道
要创建 Vertex AI 管道运行并监控直到完成
# Instantiate PipelineJob object
pl = PipelineJob(
display_name="My first pipeline",
# Whether or not to enable caching
# True = always cache pipeline step result
# False = never cache pipeline step result
# None = defer to cache option for each pipeline component in the pipeline definition
enable_caching=False,
# Local or GCS path to a compiled pipeline definition
template_path="pipeline.json",
# Dictionary containing input parameters for your pipeline
parameter_values=parameter_values,
# GCS path to act as the pipeline root
pipeline_root=pipeline_root,
)
# Execute pipeline in Vertex AI and monitor until completion
pl.run(
# Email address of service account to use for the pipeline run
# You must have iam.serviceAccounts.actAs permission on the service account to use it
service_account=service_account,
# Whether this function call should be synchronous (wait for pipeline run to finish before terminating)
# or asynchronous (return immediately)
sync=True
)
要创建不监控直到完成的 Vertex AI 管道,请使用 submit 而不是 run
# Instantiate PipelineJob object
pl = PipelineJob(
display_name="My first pipeline",
# Whether or not to enable caching
# True = always cache pipeline step result
# False = never cache pipeline step result
# None = defer to cache option for each pipeline component in the pipeline definition
enable_caching=False,
# Local or GCS path to a compiled pipeline definition
template_path="pipeline.json",
# Dictionary containing input parameters for your pipeline
parameter_values=parameter_values,
# GCS path to act as the pipeline root
pipeline_root=pipeline_root,
)
# Submit the Pipeline to Vertex AI
pl.submit(
# Email address of service account to use for the pipeline run
# You must have iam.serviceAccounts.actAs permission on the service account to use it
service_account=service_account,
)
可解释人工智能:获取元数据
从 TensorFlow 1 模型以字典格式获取元数据
from google.cloud.aiplatform.explain.metadata.tf.v1 import saved_model_metadata_builder
builder = saved_model_metadata_builder.SavedModelMetadataBuilder(
'gs://python/to/my/model/dir', tags=[tf.saved_model.tag_constants.SERVING]
)
generated_md = builder.get_metadata()
从 TensorFlow 2 模型以字典格式获取元数据
from google.cloud.aiplatform.explain.metadata.tf.v2 import saved_model_metadata_builder
builder = saved_model_metadata_builder.SavedModelMetadataBuilder('gs://python/to/my/model/dir')
generated_md = builder.get_metadata()
在端点部署和模型上传中使用解释元数据
explanation_metadata = builder.get_metadata_protobuf()
# To deploy a model to an endpoint with explanation
model.deploy(..., explanation_metadata=explanation_metadata)
# To deploy a model to a created endpoint with explanation
endpoint.deploy(..., explanation_metadata=explanation_metadata)
# To upload a model with explanation
aiplatform.Model.upload(..., explanation_metadata=explanation_metadata)
云分析器
云分析器允许您按需分析远程 Vertex AI 训练作业,并在 Vertex AI Tensorboard 中可视化结果。
要开始使用 TensorFlow 的分析器,请更新您的训练脚本以包含以下内容
from google.cloud.aiplatform.training_utils import cloud_profiler
...
cloud_profiler.init()
接下来,使用 Vertex AI TensorBoard 实例运行作业。有关如何操作的完整详情,请访问 https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-overview
最后,在您的 Google Cloud Console 中访问 TensorBoard,导航到“配置文件”选项卡,并点击 捕获配置文件 按钮。这将允许用户捕获正在运行作业的配置文件统计信息。
下一步
阅读 Vertex AI API 的 客户端库文档,以查看客户端上的其他可用方法。
阅读 Vertex AI API 产品文档,了解产品详情并查看教程。
查看此 README,了解我们覆盖的完整 Cloud API 列表。
项目详情
哈希值 for google_cloud_aiplatform-1.69.0-py2.py3-none-any.whl
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 6e21c29bf4506ed3bfb00cfe47ab1ad1788854b18f0ded2458016837c917e520 |
|
MD5 | 2dc5dad3fc61144e048b5282b9428f9c |
|
BLAKE2b-256 | ea15260229c9cd3b1bd386cd69a0dc39eeaf6cda08948d2707a4204966c71269 |