使用 Vertex AI API 訓練 AutoML Edge 模型

您可以直接在 Google Cloud 控制台中建立 AutoML 模型,也可以使用 API 或其中一個 Vertex AI 用戶端程式庫,以程式輔助方式建立訓練管道。

這個模型是使用您透過控制台或 Vertex AI API 提供的已準備資料集建立而成。Vertex AI API 使用資料集項目訓練模型、測試模型,並評估模型效能。查看評估結果,視需要調整訓練資料集,並使用改善的資料集建立新的訓練管道。

模型訓練可能需要數小時才能完成。Vertex AI API 可讓您取得訓練工作的狀態。

建立 AutoML Edge 訓練管道

當您的資料集包含代表性的訓練項目時,表示您已準備好建立 AutoML Edge 訓練管道。

選取資料類型。

圖片

請選取下方目標的分頁標籤:

分類

您可以在訓練時選擇所需的 AutoML Edge 模型類型,具體取決於您的特定用途:

  • 低延遲 (MOBILE_TF_LOW_LATENCY_1)
  • 一般用途 (MOBILE_TF_VERSATILE_1)
  • 預測品質較高 (MOBILE_TF_HIGH_ACCURACY_1)

請選取下方對應您語言或環境的分頁:

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:資料集所在的區域,以及建立模型的位置。例如:us-central1
  • PROJECT:您的專案 ID
  • TRAININGPIPELINE_DISPLAYNAME:必填。trainingPipeline 的顯示名稱。
  • DATASET_ID:資料集的 ID 編號,用於訓練。
  • fractionSplit:選用。機器學習使用資料時,可以採用多種分割選項之一。對於 fractionSplit,值的總和必須為 1。例如:
    • {"trainingFraction": "0.7","validationFraction": "0.15","testFraction": "0.15"}
  • MODEL_DISPLAYNAME*:TrainingPipeline 上傳 (建立) 的模型顯示名稱。
  • MODEL_DESCRIPTION*:模型的說明。
  • modelToUpload.labels*:任何一組鍵/值組合,用於整理模型。例如:
    • "env": "prod"
    • "tier": "backend"
  • EDGE_MODELTYPE:要訓練的 Edge 模型類型。選項如下:
    • MOBILE_TF_LOW_LATENCY_1
    • MOBILE_TF_VERSATILE_1
    • MOBILE_TF_HIGH_ACCURACY_1
  • NODE_HOUR_BUDGET:實際訓練費用會等於或低於這個值。針對 Edge 模型,預算必須介於 1,000 到 100,000 毫秒節點時數 (含) 之間。
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines

JSON 要求主體:

{
  "displayName": "TRAININGPIPELINE_DISPLAYNAME",
  "inputDataConfig": {
    "datasetId": "DATASET_ID",
    "fractionSplit": {
      "trainingFraction": "DECIMAL",
      "validationFraction": "DECIMAL",
      "testFraction": "DECIMAL"
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_DISPLAYNAME",
    "description": "MODEL_DESCRIPTION",
    "labels": {
      "KEY": "VALUE"
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_image_classification_1.0.0.yaml",
  "trainingTaskInputs": {
    "multiLabel": "false",
    "modelType": ["EDGE_MODELTYPE"],
    "budgetMilliNodeHours": NODE_HOUR_BUDGET
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines" | Select-Object -Expand Content

回應內容包含規格和 TRAININGPIPELINE_ID 相關資訊。

您可以使用 TRAININGPIPELINE_ID 取得訓練管道工作的狀態。

分類

您可以在訓練時選擇所需的 AutoML Edge 模型類型,具體取決於您的特定用途:

  • 低延遲 (MOBILE_TF_LOW_LATENCY_1)
  • 一般用途 (MOBILE_TF_VERSATILE_1)
  • 預測品質較高 (MOBILE_TF_HIGH_ACCURACY_1)

請選取下方對應您語言或環境的分頁:

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:資料集所在的區域,以及建立模型的位置。例如:us-central1
  • PROJECT:您的專案 ID
  • TRAININGPIPELINE_DISPLAYNAME:必填。trainingPipeline 的顯示名稱。
  • DATASET_ID:資料集的 ID 編號,用於訓練。
  • fractionSplit:選用。機器學習使用資料時,可以採用多種分割選項之一。對於 fractionSplit,值的總和必須為 1。例如:
    • {"trainingFraction": "0.7","validationFraction": "0.15","testFraction": "0.15"}
  • MODEL_DISPLAYNAME*:TrainingPipeline 上傳 (建立) 的模型顯示名稱。
  • MODEL_DESCRIPTION*:模型的說明。
  • modelToUpload.labels*:任何一組鍵/值組合,用於整理模型。例如:
    • "env": "prod"
    • "tier": "backend"
  • EDGE_MODELTYPE:要訓練的 Edge 模型類型。選項如下:
    • MOBILE_TF_LOW_LATENCY_1
    • MOBILE_TF_VERSATILE_1
    • MOBILE_TF_HIGH_ACCURACY_1
  • NODE_HOUR_BUDGET:實際訓練費用會等於或低於這個值。針對 Edge 模型,預算必須介於 1,000 到 100,000 毫秒節點時數 (含) 之間。
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines

JSON 要求主體:

{
  "displayName": "TRAININGPIPELINE_DISPLAYNAME",
  "inputDataConfig": {
    "datasetId": "DATASET_ID",
    "fractionSplit": {
      "trainingFraction": "DECIMAL",
      "validationFraction": "DECIMAL",
      "testFraction": "DECIMAL"
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_DISPLAYNAME",
    "description": "MODEL_DESCRIPTION",
    "labels": {
      "KEY": "VALUE"
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_image_classification_1.0.0.yaml",
  "trainingTaskInputs": {
    "multiLabel": "true",
    "modelType": ["EDGE_MODELTYPE"],
    "budgetMilliNodeHours": NODE_HOUR_BUDGET
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines" | Select-Object -Expand Content

回應內容包含規格和 TRAININGPIPELINE_ID 相關資訊。

您可以使用 TRAININGPIPELINE_ID 取得訓練管道工作的狀態。

物件偵測

您可以在訓練時選擇所需的 AutoML Edge 模型類型,具體取決於您的特定用途:

  • 低延遲 (MOBILE_TF_LOW_LATENCY_1)
  • 一般用途 (MOBILE_TF_VERSATILE_1)
  • 預測品質較高 (MOBILE_TF_HIGH_ACCURACY_1)

請選取下方對應您語言或環境的分頁:

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:資料集所在的區域,以及建立模型的位置。例如:us-central1
  • PROJECT:您的專案 ID
  • TRAININGPIPELINE_DISPLAYNAME:必填。trainingPipeline 的顯示名稱。
  • DATASET_ID:資料集的 ID 編號,用於訓練。
  • fractionSplit:選用。機器學習使用資料時,可以採用多種分割選項之一。對於 fractionSplit,值的總和必須為 1。例如:
    • {"trainingFraction": "0.7","validationFraction": "0.15","testFraction": "0.15"}
  • MODEL_DISPLAYNAME*:TrainingPipeline 上傳 (建立) 的模型顯示名稱。
  • MODEL_DESCRIPTION*:模型的說明。
  • modelToUpload.labels*:任何一組鍵/值組合,用於整理模型。例如:
    • "env": "prod"
    • "tier": "backend"
  • EDGE_MODELTYPE:要訓練的 Edge 模型類型。選項如下:
    • MOBILE_TF_LOW_LATENCY_1
    • MOBILE_TF_VERSATILE_1
    • MOBILE_TF_HIGH_ACCURACY_1
  • NODE_HOUR_BUDGET:實際訓練費用會等於或低於這個值。雲端模型的預算必須介於 20,000 至 900,000 毫秒節點小時 (含) 之間。 預設值為 216,000,代表實際時間的一天的長度,假設使用 9 個節點。
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines

JSON 要求主體:

{
  "displayName": "TRAININGPIPELINE_DISPLAYNAME",
  "inputDataConfig": {
    "datasetId": "DATASET_ID",
    "fractionSplit": {
      "trainingFraction": "DECIMAL",
      "validationFraction": "DECIMAL",
      "testFraction": "DECIMAL"
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_DISPLAYNAME",
    "description": "MODEL_DESCRIPTION",
    "labels": {
      "KEY": "VALUE"
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_image_object_detection_1.0.0.yaml",
  "trainingTaskInputs": {
    "modelType": ["EDGE_MODELTYPE"],
    "budgetMilliNodeHours": NODE_HOUR_BUDGET
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines" | Select-Object -Expand Content

回應內容包含規格和 TRAININGPIPELINE_ID 相關資訊。

您可以使用 TRAININGPIPELINE_ID 取得訓練管道工作的狀態。

影片

請選取下方目標的分頁標籤:

動作識別

在訓練時,請選擇下列 AutoML Edge 類型:

  • MOBILE_VERSATILE_1:一般用途

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT:您的專案 ID
  • LOCATION:資料集所在的區域,以及建立模型的位置。例如:us-central1
  • TRAINING_PIPELINE_DISPLAY_NAME:必填。TrainingPipeline 的顯示名稱。
  • DATASET_ID:訓練資料集 ID。
  • TRAINING_FRACTIONTEST_FRACTIONfractionSplit 物件為選用項目,可用於控制資料分割。如要進一步瞭解如何控制資料分割,請參閱「AutoML 模型資料分割簡介」。例如:
    • {"trainingFraction": "0.8","validationFraction": "0","testFraction": "0.2"}
  • MODEL_DISPLAY_NAME:已訓練模型的顯示名稱。
  • MODEL_DESCRIPTION:模型的說明。
  • MODEL_LABELS:任何一組鍵/值組合,用於整理模型。舉例來說:
    • "env": "prod"
    • "tier": "backend"
  • EDGE_MODEL_TYPE
    • MOBILE_VERSATILE_1:一般用途
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines

JSON 要求主體:

{
  "displayName": "TRAINING_PIPELINE_DISPLAY_NAME",
  "inputDataConfig": {
    "datasetId": "DATASET_ID",
    "fractionSplit": {
      "trainingFraction": "TRAINING_FRACTION",
      "validationFraction": "0",
      "testFraction": "TEST_FRACTION"
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_DISPLAY_NAME",
    "description": "MODEL_DESCRIPTION",
    "labels": {
      "KEY": "VALUE"
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_action_recognition_1.0.0.yaml",
  "trainingTaskInputs": {
    "modelType": ["EDGE_MODEL_TYPE"],
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines" | Select-Object -Expand Content

回應內容包含規格和 TRAININGPIPELINE_ID 相關資訊。

分類

在訓練時,請選擇下列 AutoML Edge 類型:

  • MOBILE_VERSATILE_1:一般用途

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT:您的專案 ID
  • LOCATION:資料集所在的區域,以及建立模型的位置。例如:us-central1
  • TRAINING_PIPELINE_DISPLAY_NAME:必填。TrainingPipeline 的顯示名稱。
  • DATASET_ID:訓練資料集 ID。
  • TRAINING_FRACTIONTEST_FRACTIONfractionSplit 物件為選用項目,可用於控制資料分割。如要進一步瞭解如何控制資料分割,請參閱「AutoML 模型資料分割簡介」。例如:
    • {"trainingFraction": "0.8","validationFraction": "0","testFraction": "0.2"}
  • MODEL_DISPLAY_NAME:已訓練模型的顯示名稱。
  • MODEL_DESCRIPTION:模型的說明。
  • MODEL_LABELS:任何一組鍵/值組合,用於整理模型。舉例來說:
    • "env": "prod"
    • "tier": "backend"
  • EDGE_MODEL_TYPE
    • MOBILE_VERSATILE_1:一般用途
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines

JSON 要求主體:

{
  "displayName": "TRAINING_PIPELINE_DISPLAY_NAME",
  "inputDataConfig": {
    "datasetId": "DATASET_ID",
    "fractionSplit": {
      "trainingFraction": "TRAINING_FRACTION",
      "validationFraction": "0",
      "testFraction": "TEST_FRACTION"
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_DISPLAY_NAME",
    "description": "MODEL_DESCRIPTION",
    "labels": {
      "KEY": "VALUE"
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_classification_1.0.0.yaml",
  "trainingTaskInputs": {
    "modelType": ["EDGE_MODEL_TYPE"],
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines" | Select-Object -Expand Content

回應內容包含規格和 TRAININGPIPELINE_ID 相關資訊。

物件追蹤

在訓練時,請選擇 AutoML 邊緣類型:

  • MOBILE_VERSATILE_1:一般用途
  • MOBILE_CORAL_VERSATILE_1:Google Coral 的預測品質更高
  • MOBILE_CORAL_LOW_LATENCY_1:Google Coral 延遲時間縮短
  • MOBILE_JETSON_VERSATILE_1:針對 NVIDIA Jetson 提供更優質的預測品質
  • MOBILE_JETSON_LOW_LATENCY_1:降低 NVIDIA Jetson 的延遲時間

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT:您的專案 ID
  • LOCATION:資料集所在的區域,以及建立模型的位置。例如:us-central1
  • TRAINING_PIPELINE_DISPLAY_NAME:必填。TrainingPipeline 的顯示名稱。
  • DATASET_ID:訓練資料集 ID。
  • TRAINING_FRACTIONTEST_FRACTIONfractionSplit 物件為選用項目,可用於控制資料分割。如要進一步瞭解如何控制資料分割,請參閱「AutoML 模型資料分割簡介」。例如:
    • {"trainingFraction": "0.8","validationFraction": "0","testFraction": "0.2"}
  • MODEL_DISPLAY_NAME:已訓練模型的顯示名稱。
  • MODEL_DESCRIPTION:模型的說明。
  • MODEL_LABELS:任何一組鍵/值組合,用於整理模型。舉例來說:
    • "env": "prod"
    • "tier": "backend"
  • EDGE_MODEL_TYPE:下列任一值:
    • MOBILE_VERSATILE_1:一般用途
    • MOBILE_CORAL_VERSATILE_1:Google Coral 的預測品質更高
    • MOBILE_CORAL_LOW_LATENCY_1:Google Coral 延遲時間縮短
    • MOBILE_JETSON_VERSATILE_1:針對 NVIDIA Jetson 提供更優質的預測品質
    • MOBILE_JETSON_LOW_LATENCY_1:降低 NVIDIA Jetson 的延遲時間
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines

JSON 要求主體:

{
  "displayName": "TRAINING_PIPELINE_DISPLAY_NAME",
  "inputDataConfig": {
    "datasetId": "DATASET_ID",
    "fractionSplit": {
      "trainingFraction": "TRAINING_FRACTION",
      "validationFraction": "0",
      "testFraction": "TEST_FRACTION"
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_DISPLAY_NAME",
    "description": "MODEL_DESCRIPTION",
    "labels": {
      "KEY": "VALUE"
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_object_tracking_1.0.0.yaml",
  "trainingTaskInputs": {
    "modelType": ["EDGE_MODEL_TYPE"],
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/beta1/projects/PROJECT/locations/LOCATION/trainingPipelines" | Select-Object -Expand Content

回應內容包含規格和 TRAININGPIPELINE_ID 相關資訊。

取得 trainingPipeline 狀態

使用下列程式碼,以程式輔助方式取得訓練管道建立作業的狀態。

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:TrainingPipeline 所在的區域。
  • PROJECT:您的專案 ID
  • TRAININGPIPELINE_ID:特定 TrainingPipeline 的 ID。
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines/TRAININGPIPELINE_ID

如要傳送要求,請選擇以下其中一個選項:

curl

執行下列指令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines/TRAININGPIPELINE_ID"

PowerShell

執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines/TRAININGPIPELINE_ID" | Select-Object -Expand Content

"state" 欄位會顯示作業目前的狀態。完成的訓練管道會顯示

針對已完成的建立訓練管道作業,您應該會看到類似以下的輸出內容:

Java

在試用這個範例之前,請先按照 Vertex AI 快速入門:使用用戶端程式庫中的操作說明設定 Java。詳情請參閱 Vertex AI Java API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.cloud.aiplatform.v1.DeployedModelRef;
import com.google.cloud.aiplatform.v1.EnvVar;
import com.google.cloud.aiplatform.v1.FilterSplit;
import com.google.cloud.aiplatform.v1.FractionSplit;
import com.google.cloud.aiplatform.v1.InputDataConfig;
import com.google.cloud.aiplatform.v1.Model;
import com.google.cloud.aiplatform.v1.ModelContainerSpec;
import com.google.cloud.aiplatform.v1.PipelineServiceClient;
import com.google.cloud.aiplatform.v1.PipelineServiceSettings;
import com.google.cloud.aiplatform.v1.Port;
import com.google.cloud.aiplatform.v1.PredefinedSplit;
import com.google.cloud.aiplatform.v1.PredictSchemata;
import com.google.cloud.aiplatform.v1.TimestampSplit;
import com.google.cloud.aiplatform.v1.TrainingPipeline;
import com.google.cloud.aiplatform.v1.TrainingPipelineName;
import com.google.rpc.Status;
import java.io.IOException;

public class GetTrainingPipelineSample {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String trainingPipelineId = "YOUR_TRAINING_PIPELINE_ID";
    getTrainingPipeline(project, trainingPipelineId);
  }

  static void getTrainingPipeline(String project, String trainingPipelineId) throws IOException {
    PipelineServiceSettings pipelineServiceSettings =
        PipelineServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PipelineServiceClient pipelineServiceClient =
        PipelineServiceClient.create(pipelineServiceSettings)) {
      String location = "us-central1";
      TrainingPipelineName trainingPipelineName =
          TrainingPipelineName.of(project, location, trainingPipelineId);

      TrainingPipeline trainingPipelineResponse =
          pipelineServiceClient.getTrainingPipeline(trainingPipelineName);

      System.out.println("Get Training Pipeline Response");
      System.out.format("\tName: %s\n", trainingPipelineResponse.getName());
      System.out.format("\tDisplay Name: %s\n", trainingPipelineResponse.getDisplayName());
      System.out.format(
          "\tTraining Task Definition: %s\n", trainingPipelineResponse.getTrainingTaskDefinition());
      System.out.format(
          "\tTraining Task Inputs: %s\n", trainingPipelineResponse.getTrainingTaskInputs());
      System.out.format(
          "\tTraining Task Metadata: %s\n", trainingPipelineResponse.getTrainingTaskMetadata());
      System.out.format("\tState: %s\n", trainingPipelineResponse.getState());
      System.out.format("\tCreate Time: %s\n", trainingPipelineResponse.getCreateTime());
      System.out.format("\tStart Time: %s\n", trainingPipelineResponse.getStartTime());
      System.out.format("\tEnd Time: %s\n", trainingPipelineResponse.getEndTime());
      System.out.format("\tUpdate Time: %s\n", trainingPipelineResponse.getUpdateTime());
      System.out.format("\tLabels: %s\n", trainingPipelineResponse.getLabelsMap());
      InputDataConfig inputDataConfig = trainingPipelineResponse.getInputDataConfig();

      System.out.println("\tInput Data Config");
      System.out.format("\t\tDataset Id: %s\n", inputDataConfig.getDatasetId());
      System.out.format("\t\tAnnotations Filter: %s\n", inputDataConfig.getAnnotationsFilter());
      FractionSplit fractionSplit = inputDataConfig.getFractionSplit();

      System.out.println("\t\tFraction Split");
      System.out.format("\t\t\tTraining Fraction: %s\n", fractionSplit.getTrainingFraction());
      System.out.format("\t\t\tValidation Fraction: %s\n", fractionSplit.getValidationFraction());
      System.out.format("\t\t\tTest Fraction: %s\n", fractionSplit.getTestFraction());
      FilterSplit filterSplit = inputDataConfig.getFilterSplit();

      System.out.println("\t\tFilter Split");
      System.out.format("\t\t\tTraining Filter: %s\n", filterSplit.getTrainingFilter());
      System.out.format("\t\t\tValidation Filter: %s\n", filterSplit.getValidationFilter());
      System.out.format("\t\t\tTest Filter: %s\n", filterSplit.getTestFilter());
      PredefinedSplit predefinedSplit = inputDataConfig.getPredefinedSplit();

      System.out.println("\t\tPredefined Split");
      System.out.format("\t\t\tKey: %s\n", predefinedSplit.getKey());
      TimestampSplit timestampSplit = inputDataConfig.getTimestampSplit();

      System.out.println("\t\tTimestamp Split");
      System.out.format("\t\t\tTraining Fraction: %s\n", timestampSplit.getTrainingFraction());
      System.out.format("\t\t\tTest Fraction: %s\n", timestampSplit.getTestFraction());
      System.out.format("\t\t\tValidation Fraction: %s\n", timestampSplit.getValidationFraction());
      System.out.format("\t\t\tKey: %s\n", timestampSplit.getKey());
      Model modelResponse = trainingPipelineResponse.getModelToUpload();

      System.out.println("\t\tModel to upload");
      System.out.format("\t\tName: %s\n", modelResponse.getName());
      System.out.format("\t\tDisplay Name: %s\n", modelResponse.getDisplayName());
      System.out.format("\t\tDescription: %s\n", modelResponse.getDescription());
      System.out.format("\t\tMetadata Schema Uri: %s\n", modelResponse.getMetadataSchemaUri());
      System.out.format("\t\tMeta Data: %s\n", modelResponse.getMetadata());
      System.out.format("\t\tTraining Pipeline: %s\n", modelResponse.getTrainingPipeline());
      System.out.format("\t\tArtifact Uri: %s\n", modelResponse.getArtifactUri());
      System.out.format(
          "\t\tSupported Deployment Resources Types: %s\n",
          modelResponse.getSupportedDeploymentResourcesTypesList().toString());
      System.out.format(
          "\t\tSupported Input Storage Formats: %s\n",
          modelResponse.getSupportedInputStorageFormatsList().toString());
      System.out.format(
          "\t\tSupported Output Storage Formats: %s\n",
          modelResponse.getSupportedOutputStorageFormatsList().toString());
      System.out.format("\t\tCreate Time: %s\n", modelResponse.getCreateTime());
      System.out.format("\t\tUpdate Time: %s\n", modelResponse.getUpdateTime());
      System.out.format("\t\tLabels: %s\n", modelResponse.getLabelsMap());
      PredictSchemata predictSchemata = modelResponse.getPredictSchemata();

      System.out.println("\tPredict Schemata");
      System.out.format("\t\tInstance Schema Uri: %s\n", predictSchemata.getInstanceSchemaUri());
      System.out.format(
          "\t\tParameters Schema Uri: %s\n", predictSchemata.getParametersSchemaUri());
      System.out.format(
          "\t\tPrediction Schema Uri: %s\n", predictSchemata.getPredictionSchemaUri());

      for (Model.ExportFormat supportedExportFormat :
          modelResponse.getSupportedExportFormatsList()) {
        System.out.println("\tSupported Export Format");
        System.out.format("\t\tId: %s\n", supportedExportFormat.getId());
      }
      ModelContainerSpec containerSpec = modelResponse.getContainerSpec();

      System.out.println("\tContainer Spec");
      System.out.format("\t\tImage Uri: %s\n", containerSpec.getImageUri());
      System.out.format("\t\tCommand: %s\n", containerSpec.getCommandList());
      System.out.format("\t\tArgs: %s\n", containerSpec.getArgsList());
      System.out.format("\t\tPredict Route: %s\n", containerSpec.getPredictRoute());
      System.out.format("\t\tHealth Route: %s\n", containerSpec.getHealthRoute());

      for (EnvVar envVar : containerSpec.getEnvList()) {
        System.out.println("\t\tEnv");
        System.out.format("\t\t\tName: %s\n", envVar.getName());
        System.out.format("\t\t\tValue: %s\n", envVar.getValue());
      }

      for (Port port : containerSpec.getPortsList()) {
        System.out.println("\t\tPort");
        System.out.format("\t\t\tContainer Port: %s\n", port.getContainerPort());
      }

      for (DeployedModelRef deployedModelRef : modelResponse.getDeployedModelsList()) {
        System.out.println("\tDeployed Model");
        System.out.format("\t\tEndpoint: %s\n", deployedModelRef.getEndpoint());
        System.out.format("\t\tDeployed Model Id: %s\n", deployedModelRef.getDeployedModelId());
      }

      Status status = trainingPipelineResponse.getError();
      System.out.println("\tError");
      System.out.format("\t\tCode: %s\n", status.getCode());
      System.out.format("\t\tMessage: %s\n", status.getMessage());
    }
  }
}

Python 適用的 Vertex AI SDK

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Vertex AI SDK for Python API 參考說明文件

from google.cloud import aiplatform


def get_training_pipeline_sample(
    project: str,
    training_pipeline_id: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.PipelineServiceClient(client_options=client_options)
    name = client.training_pipeline_path(
        project=project, location=location, training_pipeline=training_pipeline_id
    )
    response = client.get_training_pipeline(name=name)
    print("response:", response)

取得模型資訊

訓練管道建立完成後,您可以使用模型的顯示名稱取得更詳細的模型資訊。

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:模型所在的區域。例如:us-central1
  • PROJECT:您的專案 ID
  • MODEL_DISPLAYNAME:建立訓練管道工作時指定的模型顯示名稱。
  • PROJECT_NUMBER:系統自動產生的專案編號

HTTP 方法和網址:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models?filter=display_name=MODEL_DISPLAYNAME

如要傳送要求,請選擇以下其中一個選項:

curl

執行下列指令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models?filter=display_name=MODEL_DISPLAYNAME"

PowerShell

執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models?filter=display_name=MODEL_DISPLAYNAME" | Select-Object -Expand Content

針對已訓練的 AutoML Edge 模型,您應該會看到類似以下的輸出內容。以下是圖片 AutoML Edge 模型的輸出範例:

Java

在試用這個範例之前,請先按照 Vertex AI 快速入門:使用用戶端程式庫中的操作說明設定 Java。詳情請參閱 Vertex AI Java API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.cloud.aiplatform.v1.DeployedModelRef;
import com.google.cloud.aiplatform.v1.EnvVar;
import com.google.cloud.aiplatform.v1.Model;
import com.google.cloud.aiplatform.v1.Model.ExportFormat;
import com.google.cloud.aiplatform.v1.ModelContainerSpec;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import com.google.cloud.aiplatform.v1.Port;
import com.google.cloud.aiplatform.v1.PredictSchemata;
import java.io.IOException;

public class GetModelSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    getModelSample(project, modelId);
  }

  static void getModelSample(String project, String modelId) throws IOException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      ModelName modelName = ModelName.of(project, location, modelId);

      Model modelResponse = modelServiceClient.getModel(modelName);
      System.out.println("Get Model response");
      System.out.format("\tName: %s\n", modelResponse.getName());
      System.out.format("\tDisplay Name: %s\n", modelResponse.getDisplayName());
      System.out.format("\tDescription: %s\n", modelResponse.getDescription());

      System.out.format("\tMetadata Schema Uri: %s\n", modelResponse.getMetadataSchemaUri());
      System.out.format("\tMetadata: %s\n", modelResponse.getMetadata());
      System.out.format("\tTraining Pipeline: %s\n", modelResponse.getTrainingPipeline());
      System.out.format("\tArtifact Uri: %s\n", modelResponse.getArtifactUri());

      System.out.format(
          "\tSupported Deployment Resources Types: %s\n",
          modelResponse.getSupportedDeploymentResourcesTypesList());
      System.out.format(
          "\tSupported Input Storage Formats: %s\n",
          modelResponse.getSupportedInputStorageFormatsList());
      System.out.format(
          "\tSupported Output Storage Formats: %s\n",
          modelResponse.getSupportedOutputStorageFormatsList());

      System.out.format("\tCreate Time: %s\n", modelResponse.getCreateTime());
      System.out.format("\tUpdate Time: %s\n", modelResponse.getUpdateTime());
      System.out.format("\tLabels: %s\n", modelResponse.getLabelsMap());

      PredictSchemata predictSchemata = modelResponse.getPredictSchemata();
      System.out.println("\tPredict Schemata");
      System.out.format("\t\tInstance Schema Uri: %s\n", predictSchemata.getInstanceSchemaUri());
      System.out.format(
          "\t\tParameters Schema Uri: %s\n", predictSchemata.getParametersSchemaUri());
      System.out.format(
          "\t\tPrediction Schema Uri: %s\n", predictSchemata.getPredictionSchemaUri());

      for (ExportFormat exportFormat : modelResponse.getSupportedExportFormatsList()) {
        System.out.println("\tSupported Export Format");
        System.out.format("\t\tId: %s\n", exportFormat.getId());
      }

      ModelContainerSpec containerSpec = modelResponse.getContainerSpec();
      System.out.println("\tContainer Spec");
      System.out.format("\t\tImage Uri: %s\n", containerSpec.getImageUri());
      System.out.format("\t\tCommand: %s\n", containerSpec.getCommandList());
      System.out.format("\t\tArgs: %s\n", containerSpec.getArgsList());
      System.out.format("\t\tPredict Route: %s\n", containerSpec.getPredictRoute());
      System.out.format("\t\tHealth Route: %s\n", containerSpec.getHealthRoute());

      for (EnvVar envVar : containerSpec.getEnvList()) {
        System.out.println("\t\tEnv");
        System.out.format("\t\t\tName: %s\n", envVar.getName());
        System.out.format("\t\t\tValue: %s\n", envVar.getValue());
      }

      for (Port port : containerSpec.getPortsList()) {
        System.out.println("\t\tPort");
        System.out.format("\t\t\tContainer Port: %s\n", port.getContainerPort());
      }

      for (DeployedModelRef deployedModelRef : modelResponse.getDeployedModelsList()) {
        System.out.println("\tDeployed Model");
        System.out.format("\t\tEndpoint: %s\n", deployedModelRef.getEndpoint());
        System.out.format("\t\tDeployed Model Id: %s\n", deployedModelRef.getDeployedModelId());
      }
    }
  }
}

Node.js

在試用這個範例之前,請先按照 Vertex AI 快速入門:使用用戶端程式庫中的操作說明設定 Node.js。詳情請參閱 Vertex AI Node.js API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const modelId = 'YOUR_MODEL_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function getModel() {
  // Configure the parent resource
  const name = `projects/${project}/locations/${location}/models/${modelId}`;
  const request = {
    name,
  };
  // Get and print out a list of all the endpoints for this resource
  const [response] = await modelServiceClient.getModel(request);

  console.log('Get model response');
  console.log(`\tName : ${response.name}`);
  console.log(`\tDisplayName : ${response.displayName}`);
  console.log(`\tDescription : ${response.description}`);
  console.log(`\tMetadata schema uri : ${response.metadataSchemaUri}`);
  console.log(`\tMetadata : ${JSON.stringify(response.metadata)}`);
  console.log(`\tTraining pipeline : ${response.trainingPipeline}`);
  console.log(`\tArtifact uri : ${response.artifactUri}`);
  console.log(
    `\tSupported deployment resource types : \
      ${response.supportedDeploymentResourceTypes}`
  );
  console.log(
    `\tSupported input storage formats : \
      ${response.supportedInputStorageFormats}`
  );
  console.log(
    `\tSupported output storage formats : \
      ${response.supportedOutputStoragFormats}`
  );
  console.log(`\tCreate time : ${JSON.stringify(response.createTime)}`);
  console.log(`\tUpdate time : ${JSON.stringify(response.updateTime)}`);
  console.log(`\tLabels : ${JSON.stringify(response.labels)}`);

  const predictSchemata = response.predictSchemata;
  console.log('\tPredict schemata');
  console.log(`\tInstance schema uri : ${predictSchemata.instanceSchemaUri}`);
  console.log(
    `\tParameters schema uri : ${predictSchemata.prametersSchemaUri}`
  );
  console.log(
    `\tPrediction schema uri : ${predictSchemata.predictionSchemaUri}`
  );

  const [supportedExportFormats] = response.supportedExportFormats;
  console.log('\tSupported export formats');
  console.log(`\t${supportedExportFormats}`);

  const containerSpec = response.containerSpec;
  console.log('\tContainer Spec');
  if (!containerSpec) {
    console.log(`\t\t${JSON.stringify(containerSpec)}`);
    console.log('\t\tImage uri : {}');
    console.log('\t\tCommand : {}');
    console.log('\t\tArgs : {}');
    console.log('\t\tPredict route : {}');
    console.log('\t\tHealth route : {}');
    console.log('\t\tEnv');
    console.log('\t\t\t{}');
    console.log('\t\tPort');
    console.log('\t\t{}');
  } else {
    console.log(`\t\t${JSON.stringify(containerSpec)}`);
    console.log(`\t\tImage uri : ${containerSpec.imageUri}`);
    console.log(`\t\tCommand : ${containerSpec.command}`);
    console.log(`\t\tArgs : ${containerSpec.args}`);
    console.log(`\t\tPredict route : ${containerSpec.predictRoute}`);
    console.log(`\t\tHealth route : ${containerSpec.healthRoute}`);
    const env = containerSpec.env;
    console.log('\t\tEnv');
    console.log(`\t\t\t${JSON.stringify(env)}`);
    const ports = containerSpec.ports;
    console.log('\t\tPort');
    console.log(`\t\t\t${JSON.stringify(ports)}`);
  }

  const [deployedModels] = response.deployedModels;
  console.log('\tDeployed models');
  console.log('\t\t', deployedModels);
}
getModel();

Python 適用的 Vertex AI SDK

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Vertex AI SDK for Python API 參考說明文件

def get_model_sample(project: str, location: str, model_name: str):

    aiplatform.init(project=project, location=location)

    model = aiplatform.Model(model_name=model_name)

    print(model.display_name)
    print(model.resource_name)
    return model

後續步驟