일괄 예측 가져오기

일괄 예측 요청은 비동기식 요청입니다(반면 온라인 예측은 동기식 요청임). 모델 리소스에서 직접 일괄 예측을 요청합니다. 엔드포인트에 모델을 배포할 필요가 없습니다. 일괄 예측과 온라인 예측을 모두 지원하는 데이터 유형의 경우 즉각적인 응답이 필요하지 않고 단일 요청을 사용하여 누적된 데이터를 처리하려면 일괄 예측을 사용합니다.

일괄 예측을 수행하려면 Vertex AI가 예측 결과를 저장하는 입력 소스와 출력 위치를 지정합니다. 입력과 출력은 작업 중인 모델 유형에 따라 다릅니다. 예를 들어 AutoML 이미지 모델 유형의 일괄 예측에는 입력 JSON Lines 파일과 출력을 저장할 Cloud Storage 버킷 이름이 필요합니다.

일괄 요청 입력

일괄 요청의 입력은 예측을 위해 모델에 보낼 항목을 지정합니다. 다음 콘텐츠에서는 각 모델 유형의 입력 형식 요구사항을 제공합니다.

커스텀 학습됨

커스텀 학습 모델에서 일괄 예측을 가져오려면 다음 방법 중 하나로 입력 데이터를 준비합니다.

JSON Lines

JSON Lines 파일을 사용하여 예측할 입력 인스턴스 목록을 지정합니다. Cloud Storage 버킷에 JSON Lines 파일을 저장합니다.

예시 1

다음 예시에서는 입력 JSON Lines 파일의 인스턴스 두 개를 보여줍니다.

[1, 2, 3, 4]
[5, 6, 7, 8]

다음은 HTTP 요청 본문의 예측 컨테이너로 전송되는 항목입니다.

{"instances": [
  [1, 2, 3, 4],
  [5, 6, 7, 8]
]}

예시 2

다음 예시에서는 예측 컨테이너가 객체를 예상하는 입력 JSON Lines 파일의 인스턴스 두 개를 보여줍니다.

{"values": [1, 2, 3, 4], "key": 1}
{"values": [5, 6, 7, 8], "key": 2}

다음은 HTTP 요청 본문의 예측 컨테이너로 전송되는 항목입니다.

{"instances": [
  {"values": [1, 2, 3, 4], "key": 1},
  {"values": [5, 6, 7, 8], "key": 2}
]}

TFRecord

입력 인스턴스를 TFRecord 형식으로 저장합니다. 원하는 경우 Gzip으로 TFRecord 파일을 압축할 수 있습니다. TFRecord 파일을 Cloud Storage 버킷에 저장합니다.

Vertex AI는 TFRecord 파일의 각 인스턴스를 바이너리로 읽은 후 b64라는 단일 키를 사용하여 인스턴스를 JSON 객체로 base64로 인코딩합니다.

다음은 HTTP 요청 본문의 예측 컨테이너로 전송되는 항목입니다.

{"instances": [
 {"b64","b64EncodedASCIIString"},
 {"b64","b64EncodedASCIIString"}
]}

예측 컨테이너가 인스턴스를 디코딩하는 방법을 알고 있는지 확인합니다.

CSV

CSV 파일에서 행마다 입력 인스턴스를 한 개 지정하세요. 첫 번째 행은 헤더 행이어야 합니다. 모든 문자열을 큰따옴표(")로 묶어야 합니다. 줄바꿈 문자를 포함한 셀 값은 허용되지 않습니다. 따옴표가 없는 값은 부동 소수점 숫자로 읽힙니다.

다음 예시는 두 개의 입력 인스턴스가 있는 CSV 파일을 보여줍니다.

"input1","input2","input3"
0.1,1.2,"cat1"
4.0,5.0,"cat2"

다음은 HTTP 요청 본문의 예측 컨테이너로 전송되는 항목입니다.

{"instances": [
 [0.1,1.2,"cat1"],
 [4.0,5.0,"cat2"]
]}

파일 목록

각 행이 파일의 Cloud Storage URI인 텍스트 파일을 만듭니다. Vertex AI는 각 파일의 콘텐츠를 바이너리로 읽은 후 b64라는 단일 키를 사용하여 인스턴스를 JSON 객체로 base64로 인코딩합니다.

Google Cloud Console을 사용하여 일괄 예측을 가져오려면 먼저 Google Cloud Console에 직접 파일 목록을 붙여넣습니다. 그렇지 않으면 파일 목록을 Cloud Storage 버킷에 저장합니다.

다음 예시는 두 개의 입력 인스턴스가 있는 파일 목록을 보여줍니다.

gs://path/to/image/image1.jpg
gs://path/to/image/image2.jpg

다음은 HTTP 요청 본문의 예측 컨테이너로 전송되는 항목입니다.

{"instances": [
 {"b64","b64EncodedASCIIString"},
 {"b64","b64EncodedASCIIString"}
]}

예측 컨테이너가 인스턴스를 디코딩하는 방법을 알고 있는지 확인합니다.

BigQuery

BigQuery 테이블을 projectId.datasetId.tableId로 지정합니다. Vertex AI는 테이블의 각 행을 JSON 인스턴스로 변환합니다.

예를 들어 테이블에 다음이 포함되어 있다고 가정합니다.

열 1 열 2 열 3
1.0 3.0 "Cat1"
2.0 4.0 "Cat2"

다음은 HTTP 요청 본문의 예측 컨테이너로 전송되는 항목입니다.

{"instances": [
 [1.0,3.0,"cat1"],
 [2.0,4.0,"cat2"]
]}

BigQuery 데이터 유형이 JSON으로 변환되는 방식은 다음과 같습니다.

BigQuery 유형 JSON 유형 예시 값
문자열 문자열 "abc"
정수 정수 1
부동 소수점 부동 소수점 1.2
숫자 부동 소수점 4925.000000000
불리언 불리언 true
TimeStamp 문자열 "2019-01-01 23:59:59.999999+00:00"
Date 문자열 "2018-12-31"
시간 문자열 "23:59:59.999999"
DateTime 문자열 "2019-01-01T00:00:00"
레코드 객체 { "A": 1,"B": 2}
반복 유형 Array[Type] [1, 2]
중첩 레코드 객체 {"A": {"a": 0}, "B": 1}

이미지

JSON Lines 파일을 사용하여 예측을 수행할 이미지 목록을 지정한 후 JSON Lines 파일을 Cloud Storage 버킷에 저장합니다. 다음 샘플에서는 입력 JSON Lines 파일의 단일 줄을 보여줍니다.

{"content": "gs://sourcebucket/datasets/images/source_image.jpg", "mimeType": "image/jpeg"}

테이블 형식

테이블 형식 데이터의 경우 Cloud Storage 버킷의 CSV 파일 또는 BigQuery의 테이블을 사용할 수 있습니다. Cloud Storage의 CSV로 또는 BigQuery의 테이블로 예측 데이터를 제공할 수 있습니다. 학습 및 예측 데이터에 동일한 입력 형식을 사용하는 것이 좋습니다. Vertex AI는 모든 CSV 입력 필드를 문자열로 취급하므로 학습 및 예측에서 다른 입력 형식을 사용하면 오류가 발생할 수 있습니다. 예를 들어 BigQuery에서 데이터를 사용하여 모델을 학습시켰으면 BigQuery 테이블을 일괄 예측의 소스로 사용하는 것이 가장 좋습니다.

데이터 소스에는 모델 학습에 사용된 모든 열을 어떤 순서대로든 포함하는 테이블 형식 데이터가 있어야 합니다. 학습 데이터에 없거나, 학습 데이터에는 있지만 학습에 사용할 수 없는 열을 포함할 수 있습니다. 이러한 추가 열은 예측 출력에 포함되지만 예측 생성에는 사용되지 않습니다.

결과에 예측 데이터와 동일한 대상을 사용할 필요가 없습니다. 예를 들어 예측 데이터 소스에 BigQuery를 사용한 경우 Cloud Storage의 CSV 파일로 결과를 보낼 수 있습니다.

BigQuery 테이블 요구사항

  • BigQuery 데이터 소스 테이블은 100GB를 넘지 않아야 합니다.
  • US 또는 EU 위치에 있는 멀티 리전 BigQuery 데이터 세트를 사용해야 합니다.
  • 테이블이 다른 프로젝트에 있으면 해당 프로젝트의 Vertex AI 서비스 계정에 BigQuery Data Editor 역할을 제공해야 합니다.

CSV 파일 요구사항

  • 데이터 소스는 열 이름이 있는 헤더 행으로 시작해야 합니다.
  • 각 데이터 소스 파일은 10GB를 넘지 않아야 합니다. 여러 파일을 포함할 수도 있지만 최대 용량은 100GB로 제한됩니다.
  • Cloud Storage 버킷이 Vertex AI를 사용하는 곳과 다른 프로젝트에 있는 경우, Storage Object Creator 역할을 해당 프로젝트의 Vertex AI 서비스 계정에 제공해야 합니다.
  • 모든 문자열을 큰따옴표(")로 묶어야 합니다.

예측 요구사항

BigQuery 테이블 또는 CSV 파일 요구사항 외에도 예측 모델의 입력은 다음 요구사항을 준수해야 합니다.

  • 시간 열의 모든 값이 있고 유효해야 합니다.
  • 일괄 예측 테이블의 데이터 빈도는 학습 데이터와 동일한 빈도여야 합니다. 시계열에 누락된 행이 있으면 안 됩니다. 적절한 도메인 지식에 따라 누락된 행을 수동으로 삽입합니다.
  • 타임스탬프가 중복된 시계열은 예측에서 삭제됩니다. 이러한 시계열을 포함하려면 중복 타임스탬프를 삭제하세요.
  • 예측할 각 시계열의 이전 데이터를 제공합니다. 가장 정확한 예측을 얻으려면 데이터 양이 학습에 설정된 환경설정 기간과 같아야 합니다. 데이터를 더 적게 제공하는 경우 Vertex AI는 값이 비어 있는 데이터를 패딩합니다. 예를 들어 환경설정 기간이 14일인 경우 최소 14일의 이전 데이터를 제공합니다.
  • 예측은 대상 열의 null 값이 있는 시계열의 첫 번째 행(시간순)에서 시작합니다. null 값은 시계열 내에서 연속적이어야 합니다. 예를 들어 대상 열을 시간순으로 정렬하는 경우 단일 시계열에 `1`, `2`, `null`, `3`, `4`, `null`, `null`과 같이 정렬할 수 없습니다. CSV 파일의 경우 Vertex AI가 빈 문자열을 null로 취급하며 BigQuery의 경우 기본적으로 null 값이 지원됩니다.

텍스트

분류 및 감정 분석

JSON Lines 파일을 사용하여 예측을 수행할 문서 목록을 지정한 후 JSON Lines 파일을 Cloud Storage 버킷에 저장합니다. 다음 샘플에서는 입력 JSON Lines 파일의 단일 줄을 보여줍니다.

{"content": "gs://sourcebucket/datasets/texts/source_text.txt", "mimeType": "text/plain"}

항목 추출

항목 추출의 경우 Cloud Storage 버킷에 있는 문서에 인라인 텍스트 또는 참조를 포함할 수 있습니다. 각 문서의 경우 입력에 key 필드를 추가할 수도 있습니다.

일반적으로 일괄 예측 결과는 contentmimeType 필드가 포함된 instance 필드를 사용하여 입력 및 출력을 매핑합니다. 입력에 key 필드를 사용하는 경우 일괄 예측 출력은 instance 필드를 key 필드로 바꿉니다. 예를 들어 입력에 큰 텍스트 스니펫이 포함되어 있는 경우 일괄 예측 출력을 간소화하는 데 도움이 됩니다.

다음 샘플에서는 key 필드 유무에 관계없이 문서 및 인라인 텍스트 스니펫에 대한 참조가 포함된 JSON Lines 파일을 보여줍니다.

{"content": "gs://sourcebucket/datasets/texts/source_text.txt", "mimeType": "text/plain"}
{"content": "gs://bucket/sample.txt", "mimeType": "text/plain", "key": "sample-file"}
{"content": "Text snippet", "mimeType": "text/plain"}
{"content": "Sample text snippet", "mimeType": "text/plain", "key": "sample-snippet"}

동영상

JSON Lines 파일을 사용하여 예측을 수행할 동영상 목록을 지정한 후 JSON Lines 파일을 Cloud Storage 버킷에 저장합니다. timeSegmentEnd 필드에 Infinity를 지정하여 동영상 종료 지점을 지정할 수 있습니다. 다음 샘플에서는 입력 JSON Lines 파일의 단일 줄을 보여줍니다.

{'content': 'gs://sourcebucket/datasets/videos/source_video.mp4', 'mimeType': 'video/mp4', 'timeSegmentStart': '0.0s', 'timeSegmentEnd': '2.366667s'}

배치 예측 요청

일괄 예측 요청의 경우 Google Cloud Console 또는 Vertex AI API를 사용할 수 있습니다. 제출한 입력 항목 수에 따라 일괄 예측 태스크를 완료하는 데 다소 시간이 걸릴 수 있습니다.

Google Cloud Console

Google Cloud Console을 사용하여 일괄 예측을 요청합니다.

  1. Google Cloud Console의 Vertex AI 섹션에서 일괄 예측 페이지로 이동합니다.

    일괄 예측 페이지로 이동

  2. 만들기를 클릭하여 새 일괄 예측 창을 엽니다.

  3. 일괄 예측 정의에서 다음 단계를 완료합니다.

    커스텀 학습됨

    1. 일괄 예측의 이름을 입력합니다.
    2. 모델 이름에서 이 일괄 예측에 사용할 모델의 이름을 선택합니다.
    3. 버전에서 이 일괄 예측에 사용할 모델 버전을 선택합니다.
    4. 소스 선택:
      • 입력 형식을 JSON Lines, CSV 또는 TFRecord로 지정한 경우 Cloud Storage의 파일(JSON Lines, CSV, TFRecord, TFRecord Gzip)을 선택합니다. 그런 다음 소스 경로 필드에 입력 파일을 지정합니다.
      • 파일 목록을 입력으로 사용하는 경우 Cloud Storage의 파일(기타)을 선택하고 다음 텍스트 상자에 파일 목록을 붙여넣습니다.
      • BigQuery 입력에 BigQuery 경로를 선택합니다. BigQuery를 입력으로 선택하면 BigQuery를 출력으로 선택해야 합니다.
    5. 대상 경로 필드에 Vertex AI에서 일괄 예측 출력을 저장할 Cloud Storage 디렉터리를 지정합니다.
    6. 원하는 경우 일괄 예측 응답의 일부로 특성 기여 분석을 가져오려면 이 모델에 특성 기여 분석 사용 설정을 선택하면 됩니다. 그런 다음 수정을 클릭하여 설명 설정을 구성합니다. 이전에 모델에 대한 설명 설정을 구성한 경우 설명 설정 수정은 선택사항이며 그렇지 않으면 필요합니다.
    7. 일괄 예측 작업의 컴퓨팅 옵션인 컴퓨팅 노드 수, 머신 유형, 원하는 경우 가속기 유형가속기 수를 지정합니다.

    이미지, 텍스트 또는 동영상

    1. 일괄 예측의 이름을 입력합니다.
    2. 모델 이름에서 이 일괄 예측에 사용할 모델의 이름을 선택합니다.
    3. 소스 경로에서 JSON Lines 입력 파일이 있는 Cloud Storage 위치를 지정합니다.
    4. 대상 경로에서 일괄 예측 결과가 저장되는 Cloud Storage 위치를 지정합니다. 출력 형식은 모델의 목표에 따라 결정됩니다. 예를 들어 텍스트 목표의 AutoML 모델은 JSON Lines 파일을 출력합니다.

    테이블 형식

    1. 일괄 예측의 이름을 입력합니다.
    2. 모델 이름에서 이 일괄 예측에 사용할 모델의 이름을 선택합니다.
    3. 소스 선택에서 소스 입력 데이터가 Cloud Storage의 CSV 파일인지, BigQuery의 테이블인지 선택합니다.
      • CSV 파일의 경우 CSV 입력 파일이 있는 Cloud Storage 위치를 지정합니다.
      • BigQuery 테이블의 경우 테이블이 있는 프로젝트 ID, BigQuery 데이터 세트 ID, BigQuery 테이블 또는 뷰 ID를 지정합니다.
    4. 출력에서 CSV 또는 BigQuery를 선택합니다.
      • CSV의 경우 Vertex AI에서 출력을 저장하는 Cloud Storage 버킷을 지정합니다.
      • BigQuery의 경우 프로젝트 ID 또는 기존 데이터 세트를 지정할 수 있습니다.
        • 프로젝트 ID를 지정하려면 Google Cloud 프로젝트 ID 필드에 프로젝트 ID를 입력합니다. Vertex AI는 새로운 출력 데이터 세트를 만듭니다.
        • 기존 데이터 세트를 지정하려면 Google Cloud 프로젝트 ID 필드에 BigQuery 경로를 입력합니다(예: bq://projectid.datasetid).
      • BigQuery를 출력 대상으로 지정하고 예측의 특성 중요도 값을 반환하려는 경우 특성 중요도 생성 체크박스를 선택합니다.

        Cloud Storage에서 또는 예측 모델에 대해 예측 데이터가 반환될 때 특성 중요도가 지원되지 않습니다.

  4. 선택사항: 테이블 형식 커스텀 학습 및 테이블 형식 AutoML 모델에 모델 모니터링 분석을 사용할 수 있습니다. 일괄 예측 작업에 편향 감지 구성을 추가하는 방법은 기본 요건을 참조하세요.

    1. 이 일괄 예측에 모델 모니터링 사용 설정을 클릭하여 켜거나 끕니다.

    2. 학습 데이터 소스를 선택합니다.

    3. 선택한 학습 데이터 소스의 학습 데이터 경로를 입력합니다.

  5. 만들기를 클릭합니다.

API

Vertex AI API를 사용하여 일괄 예측 요청을 전송합니다.

커스텀 학습됨

일괄 예측을 가져오는 데 사용할 도구에 따라 탭을 선택합니다.

REST 및 명령줄

REST API 참조는 BatchPredictionJob을 참조하세요.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. us-central1).

  • PROJECT: 프로젝트 ID입니다.

  • BATCH_JOB_NAME: 일괄 예측 작업의 표시 이름입니다.

  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.

  • INPUT_FORMAT: 입력 데이터의 형식(jsonl, csv, tf-record, tf-record-gzip 또는 file-list)입니다.

  • INPUT_URI: 입력 데이터의 Cloud Storage URI입니다. 와일드 카드를 포함할 수도 있습니다.

  • OUTPUT_DIRECTORY: Vertex AI에서 출력을 저장할 디렉터리의 Cloud Storage URI입니다.

  • MACHINE_TYPE: 이 일괄 예측 작업에 사용할 머신 리소스입니다.

    원하는 경우 가속기를 사용하도록 machineSpec 필드를 구성할 수 있지만 다음 예시에서는 이를 보여주지 않습니다.

  • BATCH_SIZE: 각 예측 요청에서 전송할 인스턴스 수로, 기본값은 64입니다. 배치 크기를 늘리면 처리량이 증가할 수 있지만 요청 시간 초과가 발생할 수도 있습니다.

  • STARTING_REPLICA_COUNT: 이 일괄 예측 작업의 노드 수입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "displayName": "BATCH_JOB_NAME",
  "model": "projects/PROJECT/locations/LOCATION/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "INPUT_FORMAT",
    "gcsSource": {
      "uris": ["INPUT_URI"],
    },
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_DIRECTORY",
    },
  },
  "dedicatedResources" : {
    "machineSpec" : {
      "machineType": MACHINE_TYPE
    },
    "startingReplicaCount": STARTING_REPLICA_COUNT
  },
  "manualBatchTuningParameters": {
    "batch_size": BATCH_SIZE,
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT/locations/us-central1/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "INPUT_URI"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_DIRECTORY"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
}

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

다음 샘플에서 PREDICTIONS_FORMATjsonl로 바꿉니다. 다른 자리표시자를 바꾸는 방법을 알아보려면 이 섹션의 REST & CMD LINE 탭을 참조하세요.

import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.AcceleratorType;
import com.google.cloud.aiplatform.v1.BatchDedicatedResources;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.protobuf.Value;
import java.io.IOException;

public class CreateBatchPredictionJobSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";
    String modelName = "MODEL_NAME";
    String instancesFormat = "INSTANCES_FORMAT";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String predictionsFormat = "PREDICTIONS_FORMAT";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobSample(
        project,
        displayName,
        modelName,
        instancesFormat,
        gcsSourceUri,
        predictionsFormat,
        gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobSample(
      String project,
      String displayName,
      String model,
      String instancesFormat,
      String gcsSourceUri,
      String predictionsFormat,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    JobServiceSettings settings =
        JobServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // 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 (JobServiceClient client = JobServiceClient.create(settings)) {

      // Passing in an empty Value object for model parameters
      Value modelParameters = ValueConverter.EMPTY_VALUE;

      GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
      BatchPredictionJob.InputConfig inputConfig =
          BatchPredictionJob.InputConfig.newBuilder()
              .setInstancesFormat(instancesFormat)
              .setGcsSource(gcsSource)
              .build();
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
      BatchPredictionJob.OutputConfig outputConfig =
          BatchPredictionJob.OutputConfig.newBuilder()
              .setPredictionsFormat(predictionsFormat)
              .setGcsDestination(gcsDestination)
              .build();
      MachineSpec machineSpec =
          MachineSpec.newBuilder()
              .setMachineType("n1-standard-2")
              .setAcceleratorType(AcceleratorType.NVIDIA_TESLA_K80)
              .setAcceleratorCount(1)
              .build();
      BatchDedicatedResources dedicatedResources =
          BatchDedicatedResources.newBuilder()
              .setMachineSpec(machineSpec)
              .setStartingReplicaCount(1)
              .setMaxReplicaCount(1)
              .build();
      String modelName = ModelName.of(project, location, model).toString();
      BatchPredictionJob batchPredictionJob =
          BatchPredictionJob.newBuilder()
              .setDisplayName(displayName)
              .setModel(modelName)
              .setModelParameters(modelParameters)
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .setDedicatedResources(dedicatedResources)
              .build();
      LocationName parent = LocationName.of(project, location);
      BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
      System.out.format("response: %s\n", response);
      System.out.format("\tName: %s\n", response.getName());
    }
  }
}

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_dedicated_resources_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    machine_type: str = "n1-standard-2",
    accelerator_count: int = 1,
    accelerator_type: Union[str, aiplatform_v1.AcceleratorType] = "NVIDIA_TESLA_K80",
    starting_replica_count: int = 1,
    max_replica_count: int = 1,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        machine_type=machine_type,
        accelerator_count=accelerator_count,
        accelerator_type=accelerator_type,
        starting_replica_count=starting_replica_count,
        max_replica_count=max_replica_count,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

특성 중요도

예측에 특성 중요도 값을 반환하려면 generateExplanation 속성을 true로 설정합니다. 예측 모델은 특성 중요도를 지원하지 않으므로 일괄 예측 요청에 포함할 수 없습니다.

특성 기여 분석이라고도 하는 특성 중요도는 Vertex Explainable AI의 일부입니다.

설명을 위해 Model을 구성했거나 BatchPredictionJobexplanationSpec 필드를 지정한 경우에만 generateExplanationtrue로 설정할 수 있습니다.

이미지

다음 일괄 예측 예시는 분류 및 객체 감지 목표에 적용됩니다.

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • THRESHOLD_VALUE(선택사항): Vertex AI는 신뢰도 점수가 이 값 이상인 예측만 반환합니다. 기본값은 0.0입니다.
  • MAX_PREDICTIONS (선택사항): Vertex AI는 신뢰도 점수가 가장 높은 순으로 최대 이 수의 예측을 반환합니다. 기본값은 10입니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/LOCATION/models/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
      "maxPredictions": MAX_PREDICTIONS
    },
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT/locations/us-central1/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}

작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

테이블 형식

일괄 예측을 요청하는 데 필요한 코드는 예측 데이터가 Cloud Storage의 CSV 파일인지 아니면 BigQuery 테이블인지에 따라 다릅니다. 예측 데이터 및 출력 대상에 다른 형식(Cloud Storage 또는 BigQuery)을 사용할 수 있습니다. 예측 데이터가 Vertex AI가 실행되는 프로젝트와 다른 프로젝트에 있는 경우 필수 권한을 설정해야 합니다.

CSV 파일을 사용한 일괄 예측 요청

REST 및 명령줄

batchPredictionJobs.create 메서드를 사용하여 일괄 예측을 요청합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • URI: 학습 데이터가 포함된 Cloud Storage 버킷의 경로(URI)입니다. 두 개 이상 있을 수 있습니다. 각 URI의 형식은 다음과 같습니다.
    gs://bucketName/pathToFileName
    
  • OUTPUT_URI_PREFIX: 예측이 기록되는 Cloud Storage 대상의 경로입니다. Vertex AI에서 이 경로의 타임스탬프가 적용된 하위 디렉터리에 일괄 예측을 기록합니다. 이 값을 다음 형식의 문자열에 설정합니다.
    gs://bucketName/pathToOutputDirectory
    
  • MACHINE_TYPE: 이 일괄 예측 작업에 사용할 머신 리소스입니다. 자세히 알아보기
  • STARTING_REPLICA_COUNT: 이 일괄 예측 작업의 시작 노드 수입니다. 로드 시 필요에 따라 최대 노드 수까지 노드 수를 늘리거나 줄일 수 있지만 절대 이 수 미만이 되지 않습니다.
  • MAX_REPLICA_COUNT: 이 일괄 예측 작업의 최대 노드 수입니다. 로드 시 필요에 따라 노드 수를 늘리거나 줄일 수 있지만 최댓값을 절대 초과하지 않습니다. 선택사항으로, 기본값은 10입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "displayName": "BATCH_JOB_NAME",
  "model": "MODEL_ID",
  "inputConfig": {
    "instancesFormat": "csv",
    "gcsSource": {
      "uris": [
        URI1,...
      ]
    },
  },
  "outputConfig": {
    "predictionsFormat": "csv",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_URI_PREFIX"
    }
  },
  "dedicatedResources": {
    "machineSpec": {
      "machineType": "MACHINE_TYPE",
      "acceleratorCount": "0"
    },
    "startingReplicaCount": STARTING_REPLICA_COUNT,
    "maxReplicaCount": MAX_REPLICA_COUNT
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/12345/locations/us-central1/batchPredictionJobs/67890",
  "displayName": "batch_job_1 202005291958",
  "model": "projects/12345/locations/us-central1/models/5678",
  "state": "JOB_STATE_PENDING",
  "inputConfig": {
    "instancesFormat": "csv",
    "gcsSource": {
      "uris": [
        "gs://bp_bucket/reg_mode_test"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "csv",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_URI_PREFIX"
    }
  },
  "dedicatedResources": {
    "machineSpec": {
      "machineType": "n1-standard-32",
      "acceleratorCount": "0"
    },
    "startingReplicaCount": 2,
    "maxReplicaCount": 6
  },
  "manualBatchTuningParameters": {
    "batchSize": 4
  }
  "outputInfo": {
    "gcsOutputDataset": "OUTPUT_URI_PREFIX/prediction-batch_job_1 202005291958-2020-09-30T02:58:44.341643Z"
  }
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-09-30T02:58:44.341643Z",
  "updateTime": "2020-09-30T02:58:44.341643Z",
}

Cloud Storage에 예측 데이터가 반환될 때 기능 중요도가 지원되지 않습니다.

BigQuery를 사용한 일괄 예측 요청

REST 및 명령줄

batchPredictionJobs.create 메서드를 사용하여 일괄 예측을 요청합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • INPUT_URI: BigQuery 데이터 소스에 대한 참조입니다. 다음 안내를 따라 양식을 작성하세요.
    bq://bqprojectId.bqDatasetId.bqTableId
    
  • OUTPUT_URI: 예측이 기록되는 BigQuery 대상에 대한 참조입니다. 프로젝트 ID를 지정하고 선택적으로 기존 데이터 세트 ID를 지정합니다. 프로젝트 ID만 지정하면 Vertex AI가 새로운 출력 데이터 세트를 만듭니다. 다음 형식을 사용합니다.
    bq://bqprojectId.bqDatasetId
    
  • MACHINE_TYPE: 이 일괄 예측 작업에 사용할 머신 리소스입니다. 자세히 알아보기
  • STARTING_REPLICA_COUNT: 이 일괄 예측 작업의 시작 노드 수입니다. 로드 시 필요에 따라 최대 노드 수까지 노드 수를 늘리거나 줄일 수 있지만 절대 이 수 미만이 되지 않습니다.
  • MAX_REPLICA_COUNT: 이 일괄 예측 작업의 최대 노드 수입니다. 로드 시 필요에 따라 노드 수를 늘리거나 줄일 수 있지만 최댓값을 절대 초과하지 않습니다. 선택사항으로, 기본값은 10입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "displayName": "BATCH_JOB_NAME",
  "model": "MODEL_ID",
  "inputConfig": {
    "instancesFormat": "bigquery",
    "bigquerySource": {
      "inputUri": "INPUT_URI"
    }
  },
  "outputConfig": {
    "predictionsFormat": "bigquery",
    "bigqueryDestination": {
      "outputUri": "OUTPUT_URI"
    }
  },
  "dedicatedResources": {
    "machineSpec": {
      "machineType": "MACHINE_TYPE",
      "acceleratorCount": "0"
    },
    "startingReplicaCount": STARTING_REPLICA_COUNT,
    "maxReplicaCount": MAX_REPLICA_COUNT
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/12345/locations/us-central1/batchPredictionJobs/67890",
  "displayName": "batch_job_1 202005291958",
  "model": "projects/12345/locations/us-central1/models/5678",
  "state": "JOB_STATE_PENDING",
  "inputConfig": {
    "instancesFormat": "bigquery",
    "bigquerySource": {
      "inputUri": "INPUT_URI"
    }
  },
  "outputConfig": {
    "predictionsFormat": "bigquery",
    "bigqueryDestination": {
        "outputUri": bq://12345
    }
  },
  "dedicatedResources": {
    "machineSpec": {
      "machineType": "n1-standard-32",
      "acceleratorCount": "0"
    },
    "startingReplicaCount": 2,
    "maxReplicaCount": 6
  },
  "manualBatchTuningParameters": {
    "batchSize": 4
  },
  "generateExplanation": false,
  "outputInfo": {
    "bigqueryOutputDataset": "bq://12345.reg_model_2020_10_02_06_04
  }
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-09-30T02:58:44.341643Z",
  "updateTime": "2020-09-30T02:58:44.341643Z",
}

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

다음 샘플에서 INSTANCES_FORMATPREDICTIONS_FORMATbigquery로 바꿉니다. 다른 자리표시자를 바꾸는 방법을 알아보려면 이 섹션의 REST & CMD LINE 탭을 참조하세요.

import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.BigQueryDestination;
import com.google.cloud.aiplatform.v1.BigQuerySource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.gson.JsonObject;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;

public class CreateBatchPredictionJobBigquerySample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";
    String modelName = "MODEL_NAME";
    String instancesFormat = "INSTANCES_FORMAT";
    String bigquerySourceInputUri = "BIGQUERY_SOURCE_INPUT_URI";
    String predictionsFormat = "PREDICTIONS_FORMAT";
    String bigqueryDestinationOutputUri = "BIGQUERY_DESTINATION_OUTPUT_URI";
    createBatchPredictionJobBigquerySample(
        project,
        displayName,
        modelName,
        instancesFormat,
        bigquerySourceInputUri,
        predictionsFormat,
        bigqueryDestinationOutputUri);
  }

  static void createBatchPredictionJobBigquerySample(
      String project,
      String displayName,
      String model,
      String instancesFormat,
      String bigquerySourceInputUri,
      String predictionsFormat,
      String bigqueryDestinationOutputUri)
      throws IOException {
    JobServiceSettings settings =
        JobServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // 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 (JobServiceClient client = JobServiceClient.create(settings)) {
      JsonObject jsonModelParameters = new JsonObject();
      Value.Builder modelParametersBuilder = Value.newBuilder();
      JsonFormat.parser().merge(jsonModelParameters.toString(), modelParametersBuilder);
      Value modelParameters = modelParametersBuilder.build();
      BigQuerySource bigquerySource =
          BigQuerySource.newBuilder().setInputUri(bigquerySourceInputUri).build();
      BatchPredictionJob.InputConfig inputConfig =
          BatchPredictionJob.InputConfig.newBuilder()
              .setInstancesFormat(instancesFormat)
              .setBigquerySource(bigquerySource)
              .build();
      BigQueryDestination bigqueryDestination =
          BigQueryDestination.newBuilder().setOutputUri(bigqueryDestinationOutputUri).build();
      BatchPredictionJob.OutputConfig outputConfig =
          BatchPredictionJob.OutputConfig.newBuilder()
              .setPredictionsFormat(predictionsFormat)
              .setBigqueryDestination(bigqueryDestination)
              .build();
      String modelName = ModelName.of(project, location, model).toString();
      BatchPredictionJob batchPredictionJob =
          BatchPredictionJob.newBuilder()
              .setDisplayName(displayName)
              .setModel(modelName)
              .setModelParameters(modelParameters)
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();
      LocationName parent = LocationName.of(project, location);
      BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
      System.out.format("response: %s\n", response);
      System.out.format("\tName: %s\n", response.getName());
    }
  }
}

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

다음 샘플에서 instances_formatpredictions_format 매개변수를 "bigquery"로 설정합니다. 다른 매개변수를 설정하는 방법을 알아보려면 이 섹션의 REST & CMD LINE 탭을 참조하세요.

from google.cloud import aiplatform_v1beta1
from google.protobuf import json_format
from google.protobuf.struct_pb2 import Value

def create_batch_prediction_job_bigquery_sample(
    project: str,
    display_name: str,
    model_name: str,
    instances_format: str,
    bigquery_source_input_uri: str,
    predictions_format: str,
    bigquery_destination_output_uri: 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_v1beta1.JobServiceClient(client_options=client_options)
    model_parameters_dict = {}
    model_parameters = json_format.ParseDict(model_parameters_dict, Value())

    batch_prediction_job = {
        "display_name": display_name,
        # Format: 'projects/{project}/locations/{location}/models/{model_id}'
        "model": model_name,
        "model_parameters": model_parameters,
        "input_config": {
            "instances_format": instances_format,
            "bigquery_source": {"input_uri": bigquery_source_input_uri},
        },
        "output_config": {
            "predictions_format": predictions_format,
            "bigquery_destination": {"output_uri": bigquery_destination_output_uri},
        },
        # optional
        "generate_explanation": True,
    }
    parent = f"projects/{project}/locations/{location}"
    response = client.create_batch_prediction_job(
        parent=parent, batch_prediction_job=batch_prediction_job
    )
    print("response:", response)

특성 중요도

예측에 특성 중요도 값을 반환하려면 generateExplanation 속성을 true로 설정합니다. 예측 모델은 특성 중요도를 지원하지 않으므로 일괄 예측 요청에 포함할 수 없습니다.

특성 기여 분석이라고도 하는 특성 중요도는 Vertex Explainable AI의 일부입니다.

Cloud Storage에서 또는 예측 모델에 대해 예측 데이터가 반환될 때 특성 중요도가 지원되지 않습니다.

텍스트

텍스트 목표를 선택하여 일괄 예측 요청의 예시를 봅니다.

분류

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/LOCATION/MODEL_ID",
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT_NUMBER/locations/LOCATION/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}
작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import java.io.IOException;

public class CreateBatchPredictionJobTextClassificationSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String location = "us-central1";
    String displayName = "DISPLAY_NAME";
    String modelId = "MODEL_ID";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobTextClassificationSample(
        project, location, displayName, modelId, gcsSourceUri, gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobTextClassificationSample(
      String project,
      String location,
      String displayName,
      String modelId,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    // The AI Platform services require regional API endpoints.
    JobServiceSettings settings =
        JobServiceSettings.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 (JobServiceClient client = JobServiceClient.create(settings)) {
      try {
        String modelName = ModelName.of(project, location, modelId).toString();
        GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
        BatchPredictionJob.InputConfig inputConfig =
            BatchPredictionJob.InputConfig.newBuilder()
                .setInstancesFormat("jsonl")
                .setGcsSource(gcsSource)
                .build();
        GcsDestination gcsDestination =
            GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
        BatchPredictionJob.OutputConfig outputConfig =
            BatchPredictionJob.OutputConfig.newBuilder()
                .setPredictionsFormat("jsonl")
                .setGcsDestination(gcsDestination)
                .build();
        BatchPredictionJob batchPredictionJob =
            BatchPredictionJob.newBuilder()
                .setDisplayName(displayName)
                .setModel(modelName)
                .setInputConfig(inputConfig)
                .setOutputConfig(outputConfig)
                .build();
        LocationName parent = LocationName.of(project, location);
        BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
        System.out.format("response: %s\n", response);
      } catch (ApiException ex) {
        System.out.format("Exception: %s\n", ex.getLocalizedMessage());
      }
    }
  }
}

Node.js

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const batchPredictionDisplayName = 'YOUR_BATCH_PREDICTION_DISPLAY_NAME';
// const modelId = 'YOUR_MODEL_ID';
// const gcsSourceUri = 'YOUR_GCS_SOURCE_URI';
// const gcsDestinationOutputUriPrefix = 'YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Job Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform').v1;

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

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createBatchPredictionJobTextClassification() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const modelName = `projects/${project}/locations/${location}/models/${modelId}`;

  const inputConfig = {
    instancesFormat: 'jsonl',
    gcsSource: {uris: [gcsSourceUri]},
  };
  const outputConfig = {
    predictionsFormat: 'jsonl',
    gcsDestination: {outputUriPrefix: gcsDestinationOutputUriPrefix},
  };
  const batchPredictionJob = {
    displayName: batchPredictionDisplayName,
    model: modelName,
    inputConfig,
    outputConfig,
  };
  const request = {
    parent,
    batchPredictionJob,
  };

  // Create batch prediction job request
  const [response] = await jobServiceClient.createBatchPredictionJob(request);

  console.log('Create batch prediction job text classification response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createBatchPredictionJobTextClassification();

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

항목 추출

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/LOCATION/MODEL_ID",
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT_NUMBER/locations/LOCATION/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}
작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import java.io.IOException;

public class CreateBatchPredictionJobTextEntityExtractionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String location = "us-central1";
    String displayName = "DISPLAY_NAME";
    String modelId = "MODEL_ID";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobTextEntityExtractionSample(
        project, location, displayName, modelId, gcsSourceUri, gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobTextEntityExtractionSample(
      String project,
      String location,
      String displayName,
      String modelId,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    // The AI Platform services require regional API endpoints.
    JobServiceSettings settings =
        JobServiceSettings.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 (JobServiceClient client = JobServiceClient.create(settings)) {
      try {
        String modelName = ModelName.of(project, location, modelId).toString();
        GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
        BatchPredictionJob.InputConfig inputConfig =
            BatchPredictionJob.InputConfig.newBuilder()
                .setInstancesFormat("jsonl")
                .setGcsSource(gcsSource)
                .build();
        GcsDestination gcsDestination =
            GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
        BatchPredictionJob.OutputConfig outputConfig =
            BatchPredictionJob.OutputConfig.newBuilder()
                .setPredictionsFormat("jsonl")
                .setGcsDestination(gcsDestination)
                .build();
        BatchPredictionJob batchPredictionJob =
            BatchPredictionJob.newBuilder()
                .setDisplayName(displayName)
                .setModel(modelName)
                .setInputConfig(inputConfig)
                .setOutputConfig(outputConfig)
                .build();
        LocationName parent = LocationName.of(project, location);
        BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
        System.out.format("response: %s\n", response);
        System.out.format("\tname:%s\n", response.getName());
      } catch (ApiException ex) {
        System.out.format("Exception: %s\n", ex.getLocalizedMessage());
      }
    }
  }
}

Node.js

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const batchPredictionDisplayName = 'YOUR_BATCH_PREDICTION_DISPLAY_NAME';
// const modelId = 'YOUR_MODEL_ID';
// const gcsSourceUri = 'YOUR_GCS_SOURCE_URI';
// const gcsDestinationOutputUriPrefix = 'YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Job Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform').v1;

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

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createBatchPredictionJobTextEntityExtraction() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const modelName = `projects/${project}/locations/${location}/models/${modelId}`;

  const inputConfig = {
    instancesFormat: 'jsonl',
    gcsSource: {uris: [gcsSourceUri]},
  };
  const outputConfig = {
    predictionsFormat: 'jsonl',
    gcsDestination: {outputUriPrefix: gcsDestinationOutputUriPrefix},
  };
  const batchPredictionJob = {
    displayName: batchPredictionDisplayName,
    model: modelName,
    inputConfig,
    outputConfig,
  };
  const request = {
    parent,
    batchPredictionJob,
  };

  // Create batch prediction job request
  const [response] = await jobServiceClient.createBatchPredictionJob(request);

  console.log('Create batch prediction job text entity extraction response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createBatchPredictionJobTextEntityExtraction();

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

감정 분석

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/LOCATION/MODEL_ID",
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT_NUMBER/locations/LOCATION/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}
작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import java.io.IOException;

public class CreateBatchPredictionJobTextSentimentAnalysisSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String location = "us-central1";
    String displayName = "DISPLAY_NAME";
    String modelId = "MODEL_ID";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobTextSentimentAnalysisSample(
        project, location, displayName, modelId, gcsSourceUri, gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobTextSentimentAnalysisSample(
      String project,
      String location,
      String displayName,
      String modelId,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    // The AI Platform services require regional API endpoints.
    JobServiceSettings settings =
        JobServiceSettings.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 (JobServiceClient client = JobServiceClient.create(settings)) {
      try {
        String modelName = ModelName.of(project, location, modelId).toString();
        GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
        BatchPredictionJob.InputConfig inputConfig =
            BatchPredictionJob.InputConfig.newBuilder()
                .setInstancesFormat("jsonl")
                .setGcsSource(gcsSource)
                .build();
        GcsDestination gcsDestination =
            GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
        BatchPredictionJob.OutputConfig outputConfig =
            BatchPredictionJob.OutputConfig.newBuilder()
                .setPredictionsFormat("jsonl")
                .setGcsDestination(gcsDestination)
                .build();
        BatchPredictionJob batchPredictionJob =
            BatchPredictionJob.newBuilder()
                .setDisplayName(displayName)
                .setModel(modelName)
                .setInputConfig(inputConfig)
                .setOutputConfig(outputConfig)
                .build();
        LocationName parent = LocationName.of(project, location);
        BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
        System.out.format("response: %s\n", response);
      } catch (ApiException ex) {
        System.out.format("Exception: %s\n", ex.getLocalizedMessage());
      }
    }
  }
}

Node.js

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const batchPredictionDisplayName = 'YOUR_BATCH_PREDICTION_DISPLAY_NAME';
// const modelId = 'YOUR_MODEL_ID';
// const gcsSourceUri = 'YOUR_GCS_SOURCE_URI';
// const gcsDestinationOutputUriPrefix = 'YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Job Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform').v1;

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

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createBatchPredictionJobTextSentimentAnalysis() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const modelName = `projects/${project}/locations/${location}/models/${modelId}`;

  const inputConfig = {
    instancesFormat: 'jsonl',
    gcsSource: {uris: [gcsSourceUri]},
  };
  const outputConfig = {
    predictionsFormat: 'jsonl',
    gcsDestination: {outputUriPrefix: gcsDestinationOutputUriPrefix},
  };
  const batchPredictionJob = {
    displayName: batchPredictionDisplayName,
    model: modelName,
    inputConfig,
    outputConfig,
  };
  const request = {
    parent,
    batchPredictionJob,
  };

  // Create batch prediction job request
  const [response] = await jobServiceClient.createBatchPredictionJob(request);

  console.log('Create batch prediction job text sentiment analysis response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createBatchPredictionJobTextSentimentAnalysis();

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

동영상

동작 인식

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • THRESHOLD_VALUE(선택사항): 모델은 신뢰도가 이 값 이상인 예측만 반환합니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/us-central1/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
    },
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT_NUMBER/locations/us-central1/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}
작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.protobuf.Value;
import java.io.IOException;

public class CreateBatchPredictionJobVideoActionRecognitionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";
    String model = "MODEL";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobVideoActionRecognitionSample(
        project, displayName, model, gcsSourceUri, gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobVideoActionRecognitionSample(
      String project,
      String displayName,
      String model,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    JobServiceSettings settings =
        JobServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // 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 (JobServiceClient client = JobServiceClient.create(settings)) {
      Value modelParameters = ValueConverter.EMPTY_VALUE;
      GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
      BatchPredictionJob.InputConfig inputConfig =
          BatchPredictionJob.InputConfig.newBuilder()
              .setInstancesFormat("jsonl")
              .setGcsSource(gcsSource)
              .build();
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
      BatchPredictionJob.OutputConfig outputConfig =
          BatchPredictionJob.OutputConfig.newBuilder()
              .setPredictionsFormat("jsonl")
              .setGcsDestination(gcsDestination)
              .build();

      String modelName = ModelName.of(project, location, model).toString();

      BatchPredictionJob batchPredictionJob =
          BatchPredictionJob.newBuilder()
              .setDisplayName(displayName)
              .setModel(modelName)
              .setModelParameters(modelParameters)
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();
      LocationName parent = LocationName.of(project, location);
      BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
      System.out.format("response: %s\n", response);
      System.out.format("\tName: %s\n", response.getName());
    }
  }
}

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

분류

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • THRESHOLD_VALUE(선택사항): 모델은 신뢰도가 이 값 이상인 예측만 반환합니다.
  • SEGMENT_CLASSIFICATION (선택사항): 세그먼트 수준 분류를 요청할지 결정하는 부울 값입니다. Vertex AI는 입력 인스턴스에서 지정한 동영상의 전체 시간 세그먼트의 라벨과 신뢰도 점수를 반환합니다. 기본값은 true입니다.
  • SHOT_CLASSIFICATION (선택사항): 장면 수준 분류를 요청할지 결정하는 부울 값입니다. Vertex AI는 입력 인스턴스에서 지정한 동영상의 전체 시간 세그먼트의 각 카메라 샷의 경계를 결정합니다. 그런 다음 Vertex AI는 감지된 각 장면의 라벨과 신뢰도 점수를 장면의 시작 및 종료 시간과 함께 반환합니다. 기본값은 false입니다.
  • ONE_SEC_INTERVAL_CLASSIFICATION(선택사항): 1초 간격으로 동영상 분류를 요청할지 여부를 결정하는 부울 값입니다. Vertex AI는 입력 인스턴스에서 지정한 동영상의 전체 시간 세그먼트의 초당 라벨과 신뢰도 점수를 반환합니다. 기본값은 false입니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/us-central1/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
      "segmentClassification": SEGMENT_CLASSIFICATION,
      "shotClassification": SHOT_CLASSIFICATION,
      "oneSecIntervalClassification": ONE_SEC_INTERVAL_CLASSIFICATION
    },
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT_NUMBER/locations/us-central1/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}
작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.BatchDedicatedResources;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig;
import com.google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig;
import com.google.cloud.aiplatform.v1.BatchPredictionJob.OutputInfo;
import com.google.cloud.aiplatform.v1.BigQueryDestination;
import com.google.cloud.aiplatform.v1.BigQuerySource;
import com.google.cloud.aiplatform.v1.CompletionStats;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.ManualBatchTuningParameters;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ResourcesConsumed;
import com.google.cloud.aiplatform.v1.schema.predict.params.VideoClassificationPredictionParams;
import com.google.protobuf.Any;
import com.google.protobuf.Value;
import com.google.rpc.Status;
import java.io.IOException;
import java.util.List;

public class CreateBatchPredictionJobVideoClassificationSample {

  public static void main(String[] args) throws IOException {
    String batchPredictionDisplayName = "YOUR_VIDEO_CLASSIFICATION_DISPLAY_NAME";
    String modelId = "YOUR_MODEL_ID";
    String gcsSourceUri =
        "gs://YOUR_GCS_SOURCE_BUCKET/path_to_your_video_source/[file.csv/file.jsonl]";
    String gcsDestinationOutputUriPrefix =
        "gs://YOUR_GCS_SOURCE_BUCKET/destination_output_uri_prefix/";
    String project = "YOUR_PROJECT_ID";
    createBatchPredictionJobVideoClassification(
        batchPredictionDisplayName, modelId, gcsSourceUri, gcsDestinationOutputUriPrefix, project);
  }

  static void createBatchPredictionJobVideoClassification(
      String batchPredictionDisplayName,
      String modelId,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix,
      String project)
      throws IOException {
    JobServiceSettings jobServiceSettings =
        JobServiceSettings.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 (JobServiceClient jobServiceClient = JobServiceClient.create(jobServiceSettings)) {
      String location = "us-central1";
      LocationName locationName = LocationName.of(project, location);

      VideoClassificationPredictionParams modelParamsObj =
          VideoClassificationPredictionParams.newBuilder()
              .setConfidenceThreshold(((float) 0.5))
              .setMaxPredictions(10000)
              .setSegmentClassification(true)
              .setShotClassification(true)
              .setOneSecIntervalClassification(true)
              .build();

      Value modelParameters = ValueConverter.toValue(modelParamsObj);

      ModelName modelName = ModelName.of(project, location, modelId);
      GcsSource.Builder gcsSource = GcsSource.newBuilder();
      gcsSource.addUris(gcsSourceUri);
      InputConfig inputConfig =
          InputConfig.newBuilder().setInstancesFormat("jsonl").setGcsSource(gcsSource).build();

      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
      OutputConfig outputConfig =
          OutputConfig.newBuilder()
              .setPredictionsFormat("jsonl")
              .setGcsDestination(gcsDestination)
              .build();

      BatchPredictionJob batchPredictionJob =
          BatchPredictionJob.newBuilder()
              .setDisplayName(batchPredictionDisplayName)
              .setModel(modelName.toString())
              .setModelParameters(modelParameters)
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();
      BatchPredictionJob batchPredictionJobResponse =
          jobServiceClient.createBatchPredictionJob(locationName, batchPredictionJob);

      System.out.println("Create Batch Prediction Job Video Classification Response");
      System.out.format("\tName: %s\n", batchPredictionJobResponse.getName());
      System.out.format("\tDisplay Name: %s\n", batchPredictionJobResponse.getDisplayName());
      System.out.format("\tModel %s\n", batchPredictionJobResponse.getModel());
      System.out.format(
          "\tModel Parameters: %s\n", batchPredictionJobResponse.getModelParameters());

      System.out.format("\tState: %s\n", batchPredictionJobResponse.getState());
      System.out.format("\tCreate Time: %s\n", batchPredictionJobResponse.getCreateTime());
      System.out.format("\tStart Time: %s\n", batchPredictionJobResponse.getStartTime());
      System.out.format("\tEnd Time: %s\n", batchPredictionJobResponse.getEndTime());
      System.out.format("\tUpdate Time: %s\n", batchPredictionJobResponse.getUpdateTime());
      System.out.format("\tLabels: %s\n", batchPredictionJobResponse.getLabelsMap());

      InputConfig inputConfigResponse = batchPredictionJobResponse.getInputConfig();
      System.out.println("\tInput Config");
      System.out.format("\t\tInstances Format: %s\n", inputConfigResponse.getInstancesFormat());

      GcsSource gcsSourceResponse = inputConfigResponse.getGcsSource();
      System.out.println("\t\tGcs Source");
      System.out.format("\t\t\tUris %s\n", gcsSourceResponse.getUrisList());

      BigQuerySource bigQuerySource = inputConfigResponse.getBigquerySource();
      System.out.println("\t\tBigquery Source");
      System.out.format("\t\t\tInput_uri: %s\n", bigQuerySource.getInputUri());

      OutputConfig outputConfigResponse = batchPredictionJobResponse.getOutputConfig();
      System.out.println("\tOutput Config");
      System.out.format(
          "\t\tPredictions Format: %s\n", outputConfigResponse.getPredictionsFormat());

      GcsDestination gcsDestinationResponse = outputConfigResponse.getGcsDestination();
      System.out.println("\t\tGcs Destination");
      System.out.format(
          "\t\t\tOutput Uri Prefix: %s\n", gcsDestinationResponse.getOutputUriPrefix());

      BigQueryDestination bigQueryDestination = outputConfigResponse.getBigqueryDestination();
      System.out.println("\t\tBig Query Destination");
      System.out.format("\t\t\tOutput Uri: %s\n", bigQueryDestination.getOutputUri());

      BatchDedicatedResources batchDedicatedResources =
          batchPredictionJobResponse.getDedicatedResources();
      System.out.println("\tBatch Dedicated Resources");
      System.out.format(
          "\t\tStarting Replica Count: %s\n", batchDedicatedResources.getStartingReplicaCount());
      System.out.format(
          "\t\tMax Replica Count: %s\n", batchDedicatedResources.getMaxReplicaCount());

      MachineSpec machineSpec = batchDedicatedResources.getMachineSpec();
      System.out.println("\t\tMachine Spec");
      System.out.format("\t\t\tMachine Type: %s\n", machineSpec.getMachineType());
      System.out.format("\t\t\tAccelerator Type: %s\n", machineSpec.getAcceleratorType());
      System.out.format("\t\t\tAccelerator Count: %s\n", machineSpec.getAcceleratorCount());

      ManualBatchTuningParameters manualBatchTuningParameters =
          batchPredictionJobResponse.getManualBatchTuningParameters();
      System.out.println("\tManual Batch Tuning Parameters");
      System.out.format("\t\tBatch Size: %s\n", manualBatchTuningParameters.getBatchSize());

      OutputInfo outputInfo = batchPredictionJobResponse.getOutputInfo();
      System.out.println("\tOutput Info");
      System.out.format("\t\tGcs Output Directory: %s\n", outputInfo.getGcsOutputDirectory());
      System.out.format("\t\tBigquery Output Dataset: %s\n", outputInfo.getBigqueryOutputDataset());

      Status status = batchPredictionJobResponse.getError();
      System.out.println("\tError");
      System.out.format("\t\tCode: %s\n", status.getCode());
      System.out.format("\t\tMessage: %s\n", status.getMessage());
      List<Any> details = status.getDetailsList();

      for (Status partialFailure : batchPredictionJobResponse.getPartialFailuresList()) {
        System.out.println("\tPartial Failure");
        System.out.format("\t\tCode: %s\n", partialFailure.getCode());
        System.out.format("\t\tMessage: %s\n", partialFailure.getMessage());
        List<Any> partialFailureDetailsList = partialFailure.getDetailsList();
      }

      ResourcesConsumed resourcesConsumed = batchPredictionJobResponse.getResourcesConsumed();
      System.out.println("\tResources Consumed");
      System.out.format("\t\tReplica Hours: %s\n", resourcesConsumed.getReplicaHours());

      CompletionStats completionStats = batchPredictionJobResponse.getCompletionStats();
      System.out.println("\tCompletion Stats");
      System.out.format("\t\tSuccessful Count: %s\n", completionStats.getSuccessfulCount());
      System.out.format("\t\tFailed Count: %s\n", completionStats.getFailedCount());
      System.out.format("\t\tIncomplete Count: %s\n", completionStats.getIncompleteCount());
    }
  }
}

Node.js

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const batchPredictionDisplayName = 'YOUR_BATCH_PREDICTION_DISPLAY_NAME';
// const modelId = 'YOUR_MODEL_ID';
// const gcsSourceUri = 'YOUR_GCS_SOURCE_URI';
// const gcsDestinationOutputUriPrefix = 'YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {params} = aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Job Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform').v1;

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

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createBatchPredictionJobVideoClassification() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const modelName = `projects/${project}/locations/${location}/models/${modelId}`;

  // For more information on how to configure the model parameters object, see
  // https://cloud.google.com/ai-platform-unified/docs/predictions/batch-predictions
  const modelParamsObj = new params.VideoClassificationPredictionParams({
    confidenceThreshold: 0.5,
    maxPredictions: 1000,
    segmentClassification: true,
    shotClassification: true,
    oneSecIntervalClassification: true,
  });

  const modelParameters = modelParamsObj.toValue();

  const inputConfig = {
    instancesFormat: 'jsonl',
    gcsSource: {uris: [gcsSourceUri]},
  };
  const outputConfig = {
    predictionsFormat: 'jsonl',
    gcsDestination: {outputUriPrefix: gcsDestinationOutputUriPrefix},
  };
  const batchPredictionJob = {
    displayName: batchPredictionDisplayName,
    model: modelName,
    modelParameters,
    inputConfig,
    outputConfig,
  };
  const request = {
    parent,
    batchPredictionJob,
  };

  // Create batch prediction job request
  const [response] = await jobServiceClient.createBatchPredictionJob(request);

  console.log('Create batch prediction job video classification response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createBatchPredictionJobVideoClassification();

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

객체 추적

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 모델이 저장되고 일괄 예측 작업이 실행되는 리전입니다. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID입니다.
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름입니다.
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • THRESHOLD_VALUE(선택사항): Vertex AI는 신뢰도 점수가 이 값 이상인 예측만 반환합니다. 기본값은 0.0입니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/us-central1/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
    },
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth application-default 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/batchPredictionJobs" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME 202005291958",
  "model": "projects/PROJECT_NUMBER/locations/us-central1/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}
작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.BatchDedicatedResources;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig;
import com.google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig;
import com.google.cloud.aiplatform.v1.BatchPredictionJob.OutputInfo;
import com.google.cloud.aiplatform.v1.BigQueryDestination;
import com.google.cloud.aiplatform.v1.BigQuerySource;
import com.google.cloud.aiplatform.v1.CompletionStats;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.ManualBatchTuningParameters;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ResourcesConsumed;
import com.google.cloud.aiplatform.v1.schema.predict.params.VideoObjectTrackingPredictionParams;
import com.google.protobuf.Any;
import com.google.protobuf.Value;
import com.google.rpc.Status;
import java.io.IOException;
import java.util.List;

public class CreateBatchPredictionJobVideoObjectTrackingSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String batchPredictionDisplayName = "YOUR_VIDEO_OBJECT_TRACKING_DISPLAY_NAME";
    String modelId = "YOUR_MODEL_ID";
    String gcsSourceUri =
        "gs://YOUR_GCS_SOURCE_BUCKET/path_to_your_video_source/[file.csv/file.jsonl]";
    String gcsDestinationOutputUriPrefix =
        "gs://YOUR_GCS_SOURCE_BUCKET/destination_output_uri_prefix/";
    String project = "YOUR_PROJECT_ID";
    batchPredictionJobVideoObjectTracking(
        batchPredictionDisplayName, modelId, gcsSourceUri, gcsDestinationOutputUriPrefix, project);
  }

  static void batchPredictionJobVideoObjectTracking(
      String batchPredictionDisplayName,
      String modelId,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix,
      String project)
      throws IOException {
    JobServiceSettings jobServiceSettings =
        JobServiceSettings.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 (JobServiceClient jobServiceClient = JobServiceClient.create(jobServiceSettings)) {
      String location = "us-central1";
      LocationName locationName = LocationName.of(project, location);
      ModelName modelName = ModelName.of(project, location, modelId);

      VideoObjectTrackingPredictionParams modelParamsObj =
          VideoObjectTrackingPredictionParams.newBuilder()
              .setConfidenceThreshold(((float) 0.5))
              .build();

      Value modelParameters = ValueConverter.toValue(modelParamsObj);

      GcsSource.Builder gcsSource = GcsSource.newBuilder();
      gcsSource.addUris(gcsSourceUri);
      InputConfig inputConfig =
          InputConfig.newBuilder().setInstancesFormat("jsonl").setGcsSource(gcsSource).build();

      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
      OutputConfig outputConfig =
          OutputConfig.newBuilder()
              .setPredictionsFormat("jsonl")
              .setGcsDestination(gcsDestination)
              .build();

      BatchPredictionJob batchPredictionJob =
          BatchPredictionJob.newBuilder()
              .setDisplayName(batchPredictionDisplayName)
              .setModel(modelName.toString())
              .setModelParameters(modelParameters)
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();
      BatchPredictionJob batchPredictionJobResponse =
          jobServiceClient.createBatchPredictionJob(locationName, batchPredictionJob);

      System.out.println("Create Batch Prediction Job Video Object Tracking Response");
      System.out.format("\tName: %s\n", batchPredictionJobResponse.getName());
      System.out.format("\tDisplay Name: %s\n", batchPredictionJobResponse.getDisplayName());
      System.out.format("\tModel %s\n", batchPredictionJobResponse.getModel());
      System.out.format(
          "\tModel Parameters: %s\n", batchPredictionJobResponse.getModelParameters());

      System.out.format("\tState: %s\n", batchPredictionJobResponse.getState());
      System.out.format("\tCreate Time: %s\n", batchPredictionJobResponse.getCreateTime());
      System.out.format("\tStart Time: %s\n", batchPredictionJobResponse.getStartTime());
      System.out.format("\tEnd Time: %s\n", batchPredictionJobResponse.getEndTime());
      System.out.format("\tUpdate Time: %s\n", batchPredictionJobResponse.getUpdateTime());
      System.out.format("\tLabels: %s\n", batchPredictionJobResponse.getLabelsMap());

      InputConfig inputConfigResponse = batchPredictionJobResponse.getInputConfig();
      System.out.println("\tInput Config");
      System.out.format("\t\tInstances Format: %s\n", inputConfigResponse.getInstancesFormat());

      GcsSource gcsSourceResponse = inputConfigResponse.getGcsSource();
      System.out.println("\t\tGcs Source");
      System.out.format("\t\t\tUris %s\n", gcsSourceResponse.getUrisList());

      BigQuerySource bigQuerySource = inputConfigResponse.getBigquerySource();
      System.out.println("\t\tBigquery Source");
      System.out.format("\t\t\tInput_uri: %s\n", bigQuerySource.getInputUri());

      OutputConfig outputConfigResponse = batchPredictionJobResponse.getOutputConfig();
      System.out.println("\tOutput Config");
      System.out.format(
          "\t\tPredictions Format: %s\n", outputConfigResponse.getPredictionsFormat());

      GcsDestination gcsDestinationResponse = outputConfigResponse.getGcsDestination();
      System.out.println("\t\tGcs Destination");
      System.out.format(
          "\t\t\tOutput Uri Prefix: %s\n", gcsDestinationResponse.getOutputUriPrefix());

      BigQueryDestination bigQueryDestination = outputConfigResponse.getBigqueryDestination();
      System.out.println("\t\tBig Query Destination");
      System.out.format("\t\t\tOutput Uri: %s\n", bigQueryDestination.getOutputUri());

      BatchDedicatedResources batchDedicatedResources =
          batchPredictionJobResponse.getDedicatedResources();
      System.out.println("\tBatch Dedicated Resources");
      System.out.format(
          "\t\tStarting Replica Count: %s\n", batchDedicatedResources.getStartingReplicaCount());
      System.out.format(
          "\t\tMax Replica Count: %s\n", batchDedicatedResources.getMaxReplicaCount());

      MachineSpec machineSpec = batchDedicatedResources.getMachineSpec();
      System.out.println("\t\tMachine Spec");
      System.out.format("\t\t\tMachine Type: %s\n", machineSpec.getMachineType());
      System.out.format("\t\t\tAccelerator Type: %s\n", machineSpec.getAcceleratorType());
      System.out.format("\t\t\tAccelerator Count: %s\n", machineSpec.getAcceleratorCount());

      ManualBatchTuningParameters manualBatchTuningParameters =
          batchPredictionJobResponse.getManualBatchTuningParameters();
      System.out.println("\tManual Batch Tuning Parameters");
      System.out.format("\t\tBatch Size: %s\n", manualBatchTuningParameters.getBatchSize());

      OutputInfo outputInfo = batchPredictionJobResponse.getOutputInfo();
      System.out.println("\tOutput Info");
      System.out.format("\t\tGcs Output Directory: %s\n", outputInfo.getGcsOutputDirectory());
      System.out.format("\t\tBigquery Output Dataset: %s\n", outputInfo.getBigqueryOutputDataset());

      Status status = batchPredictionJobResponse.getError();
      System.out.println("\tError");
      System.out.format("\t\tCode: %s\n", status.getCode());
      System.out.format("\t\tMessage: %s\n", status.getMessage());
      List<Any> details = status.getDetailsList();

      for (Status partialFailure : batchPredictionJobResponse.getPartialFailuresList()) {
        System.out.println("\tPartial Failure");
        System.out.format("\t\tCode: %s\n", partialFailure.getCode());
        System.out.format("\t\tMessage: %s\n", partialFailure.getMessage());
        List<Any> partialFailureDetailsList = partialFailure.getDetailsList();
      }

      ResourcesConsumed resourcesConsumed = batchPredictionJobResponse.getResourcesConsumed();
      System.out.println("\tResources Consumed");
      System.out.format("\t\tReplica Hours: %s\n", resourcesConsumed.getReplicaHours());

      CompletionStats completionStats = batchPredictionJobResponse.getCompletionStats();
      System.out.println("\tCompletion Stats");
      System.out.format("\t\tSuccessful Count: %s\n", completionStats.getSuccessfulCount());
      System.out.format("\t\tFailed Count: %s\n", completionStats.getFailedCount());
      System.out.format("\t\tIncomplete Count: %s\n", completionStats.getIncompleteCount());
    }
  }
}

Node.js

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const batchPredictionDisplayName = 'YOUR_BATCH_PREDICTION_DISPLAY_NAME';
// const modelId = 'YOUR_MODEL_ID';
// const gcsSourceUri = 'YOUR_GCS_SOURCE_URI';
// const gcsDestinationOutputUriPrefix = 'YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {params} = aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Job Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform').v1;

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

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createBatchPredictionJobVideoObjectTracking() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const modelName = `projects/${project}/locations/${location}/models/${modelId}`;

  // For more information on how to configure the model parameters object, see
  // https://cloud.google.com/ai-platform-unified/docs/predictions/batch-predictions
  const modelParamsObj = new params.VideoObjectTrackingPredictionParams({
    confidenceThreshold: 0.5,
  });

  const modelParameters = modelParamsObj.toValue();

  const inputConfig = {
    instancesFormat: 'jsonl',
    gcsSource: {uris: [gcsSourceUri]},
  };
  const outputConfig = {
    predictionsFormat: 'jsonl',
    gcsDestination: {outputUriPrefix: gcsDestinationOutputUriPrefix},
  };
  const batchPredictionJob = {
    displayName: batchPredictionDisplayName,
    model: modelName,
    modelParameters,
    inputConfig,
    outputConfig,
  };
  const request = {
    parent,
    batchPredictionJob,
  };

  // Create batch prediction job request
  const [response] = await jobServiceClient.createBatchPredictionJob(request);

  console.log('Create batch prediction job video object tracking response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createBatchPredictionJobVideoObjectTracking();

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

일괄 예측 결과 검색

Vertex AI는 지정된 대상에 일괄 예측 출력을 보냅니다.

커스텀 학습됨

일괄 예측 태스크가 완료되면 예측 출력은 요청에서 지정한 Cloud Storage 또는 BigQuery 위치에 저장됩니다.

이미지

일괄 예측 태스크가 완료되면 예측 출력은 요청에서 지정한 Cloud Storage 또는 BigQuery 위치에 저장됩니다.

테이블 형식

결과 검색은 일괄 예측에 지정한 대상(BigQuery 또는 Cloud Storage)에 따라 달라집니다.

BigQuery에서 결과 검색

BigQuery를 출력 대상으로 지정하면 일괄 예측 요청의 결과가 지정한 BigQuery 프로젝트의 데이터 세트에 반환됩니다. BigQuery 데이터 세트를 지정하지 않으면 Vertex AI에서 새 데이터 세트를 만듭니다. 데이터 세트 이름은 모델 이름 앞에 'prediction_'과 예측 작업이 시작된 시점의 타임스탬프를 추가해서 지정해야 합니다. BigQuery 데이터 세트 이름은 모델의 일괄 예측 탭에서 확인할 수 있습니다.

BigQuery 데이터 세트에는 predictions_timestamperrors_timestampe라는 예측 작업이 시작된 시점의 타임스탬프도 추가되는 2개의 테이블이 있습니다. 오류 테이블에는 Vertex AI가 예측을 반환하지 못하는 예측 요청의 모든 행에 대한 하나의 행이 있습니다. 예를 들어 null 비허용 특성이 null인 경우입니다. 예측 테이블에는 반환된 모든 예측에 대한 하나의 행이 포함됩니다.

예측 테이블에서 Vertex AI는 예측 데이터를 반환하고 대상 열 이름 앞에 'predicted_'를 추가하여 예측 결과에 대한 새 열을 만듭니다. 예측 결과 열에는 예측 결과가 포함된 중첩된 BigQuery 구조가 포함됩니다.

예측 결과를 가져오려면 BigQuery 콘솔에서 쿼리를 사용하면 됩니다. 쿼리 형식은 모델 유형에 따라 다릅니다. 다음 샘플 쿼리는 각 목표에 대한 결과를 얻는 방법을 보여줍니다.

분류:

SELECT predicted_<target-column-name>.classes AS classes,
predicted_<target-column-name>.scores AS scores,

'classes'는 잠재적 클래스의 목록이며 'scores'는 해당하는 신뢰도 점수입니다.

예측:

분위수 손실에 최적화된 모델의 경우 다음 쿼리를 사용합니다.

SELECT predicted_target-column-name.quantile_predictions,
predicted_target-column-name.quantile_values,
FROM bq-dataset-name.predictions_timestamp

기타 모든 최적화의 경우 다음 쿼리를 사용합니다.

SELECT predicted_target-column-name.value,
FROM bq-dataset-name.predictions_timestamp

회귀:

SELECT predicted_<target-column-name>.value,
predicted_<target-column-name>.lower_bound,
predicted_<target-column-name>.upper_bound
FROM <bq-dataset-name>.predictions_timestamp

Cloud Storage에서 결과 검색

Cloud Storage를 출력 대상으로 지정하면 일괄 예측 요청의 결과가 지정한 버킷의 새 폴더에 CSV 파일로 반환됩니다. 폴더 이름은 모델 이름 앞에 'prediction_'과 예측 작업이 시작된 시점의 타임스탬프를 추가해 지정해야 합니다. 모델의 일괄 예측 탭에서 Cloud Storage 폴더 이름을 확인할 수 있습니다.

Cloud Storage 폴더에는 오류 파일과 예측 파일의 두 가지 유형의 파일이 있습니다. 결과가 크면 추가 파일이 생성됩니다.

오류 파일의 이름은 errors_1.csv. errors_2.csv 등으로 지정됩니다. 이러한 오류 파일에는 헤더 행 외에 Vertex AI가 예측을 반환하지 못하는 예측 요청의 모든 행에 대한 하나의 행이 포함됩니다.

예측 파일의 이름은 predictions_1.csv. predictions_2.csv 등으로 지정됩니다. 이러한 예측 파일에는 열 이름이 지정된 헤더 행과 반환된 모든 예측에 대한 하나의 행이 포함됩니다.

예측 파일에서 Vertex AI는 예측 데이터를 반환하고. 모델 유형에 따라 예측 결과에 대한 1개 이상의 새 열을 만듭니다.

분류:

타겟 열의 각 예상 값에 대해 이름이 <target-column-name>_<value>_score인 열이 결과에 추가됩니다. 이 열에는 해당 값에 대한 점수 또는 신뢰도 추정치가 포함됩니다.

예측:

예측 값은 predicted_<target-column-name>이라는 열에 반환됩니다. 분위수 예측의 경우 출력 열에 JSON 형식의 분위수 예측 및 분위수 값이 포함됩니다.

회귀:

해당 행의 예측 값은 predicted_<target-column-name>라는 열에 반환됩니다. CSV 출력에 대한 예측 간격은 반환되지 않습니다.

텍스트

일괄 예측 태스크가 완료되면 예측 출력은 요청에서 지정한 Cloud Storage 또는 BigQuery 위치에 저장됩니다.

동영상

일괄 예측 태스크가 완료되면 예측 출력은 요청에서 지정한 Cloud Storage 또는 BigQuery 위치에 저장됩니다.

일괄 예측 결과 예시

다음 예시는 일괄 예측 결과입니다. AutoML 결과는 AutoML 모델의 결과 해석을 참조하세요.

커스텀 학습됨

출력 폴더에는 JSON Line 파일 집합이 있습니다. 파일 이름은 `{gcs_path}/prediction.results-{file_number}-of-{number_of_files_generated}`입니다. 일괄 예측의 분산 특성으로 인해 파일 수는 확정되지 않습니다. 파일의 각 줄은 입력의 인스턴스에 해당하며 다음과 같은 키-값 쌍이 있습니다.
  • prediction: 예측 컨테이너에서 반환된 값이 포함됩니다.
  • instance: FileList의 경우 Cloud Storage URI가 포함됩니다. 다른 모든 입력 형식의 경우 HTTP 요청 본문의 예측 컨테이너로 전송된 값이 포함됩니다.

    예시 1

    HTTP 요청에 다음이 포함된 경우 다음을 실행합니다.
    {
      "instances": [
        [1, 2, 3, 4],
        [5, 6, 7, 8]
    ]}
    
    예측 컨테이너에서 다음을 반환합니다.
    {
      "predictions": [
        [0.1,0.9],
        [0.7,0.3]
      ],
    }
    
    그러면 jsonl 출력 파일은 다음과 같습니다.
    { "instance": [1, 2, 3, 4], "prediction": [0.1,0.9]}
    { "instance": [5, 6, 7, 8], "prediction": [0.7,0.3]}
    

    예시 2

    HTTP 요청에 다음이 포함된 경우 다음을 실행합니다.
    {
      "instances": [
        {"values": [1, 2, 3, 4], "key": 1},
        {"values": [5, 6, 7, 8], "key": 2}
    ]}
    
    예측 컨테이너에서 다음을 반환합니다.
    {
      "predictions": [
        {"result":1},
        {"result":0}
      ],
    }
    
    그러면 jsonl 출력 파일은 다음과 같습니다.
    { "instance": {"values": [1, 2, 3, 4], "key": 1}, "prediction": {"result":1}}
    { "instance": {"values": [5, 6, 7, 8], "key": 2}, "prediction": {"result":0}}
    

이미지

분류

{
  "instance": {"content": "gs://bucket/image.jpg", "mimeType": "image/jpeg"},
  "prediction": {
    "ids": [1, 2],
    "displayNames": ["cat", "dog"],
    "confidences": [0.7, 0.5]
  }
}

객체 감지

중요: 경계 상자는 다음과 같이 지정됩니다.

"bboxes": [ [xMin, xMax, yMin, yMax], ...]

여기서 xMin, xMax는 최소 및 최대 x값이고 yMin, yMax는 각각 최소 및 최대 y값입니다.

{
  "instance": {"content": "gs://bucket/image.jpg", "mimeType": "image/jpeg"},
  "prediction": {
    "ids": [1, 2],
    "displayNames": ["cat", "dog"],
    "bboxes":  [
      [0.1, 0.2, 0.3, 0.4],
      [0.2, 0.3, 0.4, 0.5]
    ],
    "confidences": [0.7, 0.5]
  }
}

텍스트

분류

{
  "instance": {"content": "gs://bucket/text.txt", "mimeType": "text/plain"},
  "predictions": [
    {
      "ids": [
        "1234567890123456789",
        "2234567890123456789",
        "3234567890123456789"
      ],
      "displayNames": [
        "GreatService",
        "Suggestion",
        "InfoRequest"
      ],
      "confidences": [
        0.8986392080783844,
        0.81984345316886902,
        0.7722353458404541
      ]
    }
  ]
}

항목 추출

{
  "key": 1,
  "predictions": {
    "ids": [
      "1234567890123456789",
      "2234567890123456789",
      "3234567890123456789"
    ],
    "displayNames": [
      "SpecificDisease",
      "DiseaseClass",
      "SpecificDisease"
    ],
    "textSegmentStartOffsets":  [13, 40, 57],
    "textSegmentEndOffsets": [29, 51, 75],
    "confidences": [
      0.99959725141525269,
      0.99912621492484128,
      0.99935531616210938
    ]
  }
}

감정 분석

{
  "instance": {"content": "gs://bucket/text.txt", "mimeType": "text/plain"},
  "prediction": {"sentiment": 8}
}

동영상

동작 인식

{
  "instance": {
   "content": "gs://bucket/video.mp4",
    "mimeType": "video/mp4",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "5s"
  }
  "prediction": [{
    "id": "1",
    "displayName": "swing",
    "timeSegmentStart": "1.2s",
    "timeSegmentEnd": "1.2s",
    "confidence": 0.7
  }, {
    "id": "2",
    "displayName": "jump",
    "timeSegmentStart": "3.4s",
    "timeSegmentEnd": "3.4s",
    "confidence": 0.5
  }]
}

분류

{
  "instance": {
   "content": "gs://bucket/video.mp4",
    "mimeType": "video/mp4",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "5s"
  }
  "prediction": [{
    "id": "1",
    "displayName": "cat",
    "type": "segment-classification",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "5s",
    "confidence": 0.7
  }, {
    "id": "1",
    "displayName": "cat",
    "type": "shot-classification",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "4s",
    "confidence": 0.9
  }, {
    "id": "2",
    "displayName": "dog",
    "type": "shot-classification",
    "timeSegmentStart": "4s",
    "timeSegmentEnd": "5s",
    "confidence": 0.6
  }, {
    "id": "1",
    "displayName": "cat",
    "type": "one-sec-interval-classification",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "1s",
    "confidence": 0.95
  }, {
    "id": "1",
    "displayName": "cat",
    "type": "one-sec-interval-classification",
    "timeSegmentStart": "2s",
    "timeSegmentEnd": "2s",
    "confidence": 0.9
  }, {
    "id": "1",
    "displayName": "cat",
    "type": "one-sec-interval-classification",
    "timeSegmentStart": "3s",
    "timeSegmentEnd": "3s",
    "confidence": 0.85
  }, {
    "id": "2",
    "displayName": "dog",
    "type": "one-sec-interval-classification",
    "timeSegmentStart": "4s",
    "timeSegmentEnd": "4s",
    "confidence": 0.6
  }]
}

객체 추적

{
  "instance": {
   "content": "gs://bucket/video.mp4",
    "mimeType": "video/mp4",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "5s"
  }
  "prediction": [{
    "id": "1",
    "displayName": "cat",
    "timeSegmentStart": "1.2s",
    "timeSegmentEnd": "3.4s",
    "frames": [{
      "timeOffset": "1.2s",
      "xMin": 0.1,
      "xMax": 0.2,
      "yMin": 0.3,
      "yMax": 0.4
    }, {
      "timeOffset": "3.4s",
      "xMin": 0.2,
      "xMax": 0.3,
      "yMin": 0.4,
      "yMax": 0.5,
    }],
    "confidence": 0.7
  }, {
    "id": "1",
    "displayName": "cat",
    "timeSegmentStart": "4.8s",
    "timeSegmentEnd": "4.8s",
    "frames": [{
      "timeOffset": "4.8s",
      "xMin": 0.2,
      "xMax": 0.3,
      "yMin": 0.4,
      "yMax": 0.5,
    }],
    "confidence": 0.6
  }, {
    "id": "2",
    "displayName": "dog",
    "timeSegmentStart": "1.2s",
    "timeSegmentEnd": "3.4s",
    "frames": [{
      "timeOffset": "1.2s",
      "xMin": 0.1,
      "xMax": 0.2,
      "yMin": 0.3,
      "yMax": 0.4
    }, {
      "timeOffset": "3.4s",
      "xMin": 0.2,
      "xMax": 0.3,
      "yMin": 0.4,
      "yMax": 0.5,
    }],
    "confidence": 0.5
  }]
}

다음 단계