You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Vertex AI提取模型文件到Workbench,并用Python访问已训练模型?

如何用Python访问Vertex AI中已训练的模型

完全可以通过Python访问Vertex AI里已训练完成的模型,下面是具体实现步骤:

1. 安装依赖库

先确保安装了Vertex AI的Python SDK:

pip install google-cloud-aiplatform --upgrade

2. 初始化Vertex AI客户端

在代码中配置你的项目ID和对应区域,初始化客户端:

from google.cloud import aiplatform
from datetime import datetime

# 替换为你的项目ID和区域
PROJECT_ID = "your-project-id"
REGION = "your-region"

# 初始化客户端
aiplatform.init(project=PROJECT_ID, location=REGION)

3. 获取最新的已训练模型

如果训练任务失败,你可以筛选出账号下最新创建的模型(按创建时间排序):

# 列出所有模型,按创建时间倒序排列
models = aiplatform.Model.list(order_by="create_time desc")

# 取最新的第一个模型
latest_model = models[0]
print(f"已获取最新模型:{latest_model.display_name},模型ID:{latest_model.resource_name}")

如果知道目标模型的名称或ID,也可以直接获取:

# 通过模型ID获取
model = aiplatform.Model(model_name="projects/your-project-id/locations/your-region/models/your-model-id")

# 或者通过模型名称筛选
target_model_name = "your-model-display-name"
filtered_models = [m for m in models if m.display_name == target_model_name]
if filtered_models:
    target_model = filtered_models[0]

4. 执行批量预测

拿到模型对象后,直接调用批量预测方法:

# 替换为你的输入、输出GCS路径
INPUT_GCS_PATH = "gs://your-bucket/input-data/*"
OUTPUT_GCS_PATH = "gs://your-bucket/prediction-output/"

# 启动批量预测任务
batch_prediction_job = latest_model.batch_predict(
    job_display_name=f"batch-prediction-{datetime.now().strftime('%Y%m%d%H%M')}",
    gcs_source=INPUT_GCS_PATH,
    gcs_destination_prefix=OUTPUT_GCS_PATH,
    instances_format="jsonl",  # 根据你的数据格式调整,比如"csv"
    predictions_format="jsonl"
)

# 等待任务完成
batch_prediction_job.wait()

# 查看预测结果
print(f"批量预测完成,结果路径:{batch_prediction_job.output_info.gcs_output_directory}")

注意事项

  • 确保你的Workbench环境有访问Vertex AI模型的权限(比如赋予AI Platform Admin或相关角色)
  • 输入数据格式要和模型训练时的格式一致,避免预测失败
  • 如果模型是自定义容器训练的,要确保批量预测的环境配置和训练环境兼容

内容的提问来源于stack exchange,提问作者Sneharth Bhajani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:57:24