커스텀 학습 모델에서 온라인 예측 가져오기

이 페이지에서는 Google Cloud 콘솔 또는 Vertex AI API를 사용하여 커스텀 학습 모델에서 온라인 (실시간) 예측을 수행하는 방법을 보여줍니다.

온라인 예측 입력 형식 지정

이 섹션에서는 예측 입력 인스턴스의 형식을 JSON으로 지정하는 방법을 보여주는데, 이는 predict 또는 explain 메서드를 사용하는 경우에 필요합니다. rawPredict 메서드인 경우에는 필요하지 않습니다. 선택해야 할 메서드에 대한 자세한 내용은 엔드포인트로 요청 보내기를 참조하세요.

Python용 Vertex AI SDK를 사용하여 예측 요청을 전송하는 경우 instances 필드 없이 인스턴스 목록을 지정합니다. 예를 들어 { "instances": [ ["the","quick","brown"], ... ] } 대신 [ ["the","quick","brown"], ... ]을 지정합니다.

모델에서 커스텀 컨테이너를 사용하는 경우, 입력은 JSON 형식이어야 하며 컨테이너에 사용할 수 있는 추가 parameters 필드가 있습니다. 커스텀 컨테이너를 사용한 예측 입력 형식 지정에 대해 자세히 알아보세요.

인스턴스 형식을 JSON 문자열로 지정

온라인 예측의 기본 형식은 데이터 인스턴스 목록입니다. 학습 애플리케이션에서 입력을 구성한 방법에 따라서 일반 값 목록이 될 수도 또는 JSON 객체의 멤버가 될 수도 있습니다. TensorFlow 모델은 더 복잡한 입력을 수락할 수 있지만 대부분의 scikit-learn 및 XGBoost 모델은 번호 목록을 입력으로 예상합니다.

이 예시에서는 TensorFlow 모델에 대한 입력 텐서와 인스턴스 키를 보여줍니다.

 {"values": [1, 2, 3, 4], "key": 1}

JSON 문자열 구성은 다음 규칙을 따르는 한 복잡해도 괜찮습니다.

  • 인스턴스 데이터의 최상위 수준은 키-값 쌍의 사전인 JSON 객체여야 합니다.

  • 인스턴스 객체의 개별 값은 문자열, 숫자, 목록일 수 있습니다. JSON 객체를 삽입할 수 없습니다.

  • 목록에는 같은 유형의 항목만 포함되어야 합니다(다른 목록 포함). 문자열과 숫자 값을 함께 사용할 수 없습니다.

온라인 예측의 입력 인스턴스를 projects.locations.endpoints.predict 호출의 메시지 본문으로 전달합니다. 요청 본문의 형식 요구사항에 대해 자세히 알아보세요.

각 인스턴스를 JSON 배열의 항목으로 만들고 배열을 JSON 객체의 instances 필드로 제공합니다. 예를 들면 다음과 같습니다.

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

예측 입력을 위한 바이너리 데이터 인코딩

바이너리 데이터는 JSON이 지원하는 UTF-8 인코딩된 문자열로 형식을 지정할 수 없습니다. 입력에 바이너리 데이터가 있는 경우 이 데이터를 표시하려면 base64 인코딩을 사용해야 합니다. 다음 특수 형식으로 지정해야 합니다.

  • 인코딩된 문자열 형식을 b64라는 단일 키를 사용하여 JSON 객체로 지정해야 합니다. Python 3에서는 base64 인코딩이 바이트 시퀀스를 출력합니다. JSON으로 직렬화할 수 있도록 문자열로 변환해야 합니다.

    {'image_bytes': {'b64': base64.b64encode(jpeg_data).decode()}}
    
  • TensorFlow 모델 코드에서 바이너리 입력 및 출력 텐서의 별칭이 '_bytes'로 끝나도록 지정해야 합니다.

요청 및 응답 예시

이 섹션에서는 예측 요청 본문 및 응답 본문의 형식을 TensorFlow, scikit-learn, XGBoost에 대한 예시와 함께 설명합니다.

요청 본문 세부정보

TensorFlow

요청 본문에는 다음과 같은 구조의 데이터가 포함됩니다(JSON 표현).

{
  "instances": [
    <value>|<simple/nested list>|<object>,
    ...
  ]
}

instances[] 객체는 필수 항목이며 예측 결과를 가져올 인스턴스의 목록을 포함해야 합니다.

인스턴스 목록의 각 요소에 대한 구조는 모델의 입력 정의에 따라 결정됩니다. 인스턴스는 이름이 지정된 입력을 객체로서 포함하거나 라벨이 없는 값만 포함할 수 있습니다.

일부 데이터는 이름이 지정된 입력을 포함하지 않습니다. 일부 인스턴스는 단순한 JSON 값(부울, 숫자, 문자열)입니다. 그러나 인스턴스가 단순한 값 목록 또는 복잡한 중첩 목록인 경우가 있습니다.

다음은 요청 본문의 몇 가지 예입니다.

각 행이 문자열 값으로 인코딩된 CSV 데이터는 다음과 같습니다.

{"instances": ["1.0,true,\\"x\\"", "-2.0,false,\\"y\\""]}

일반 텍스트는 다음과 같습니다.

{"instances": ["the quick brown fox", "the lazy dog"]}

단어 목록(문자열 벡터)으로 인코딩된 문장은 다음과 같습니다.

{
  "instances": [
    ["the","quick","brown"],
    ["the","lazy","dog"],
    ...
  ]
}

부동 소수점 스칼라 값은 다음과 같습니다.

{"instances": [0.0, 1.1, 2.2]}

정수 벡터는 다음과 같습니다.

{
  "instances": [
    [0, 1, 2],
    [3, 4, 5],
    ...
  ]
}

텐서(이 경우, 2차원 텐서)는 다음과 같습니다.

{
  "instances": [
    [
      [0, 1, 2],
      [3, 4, 5]
    ],
    ...
  ]
}

이미지는 다양한 방식으로 표현될 수 있습니다. 이 인코딩 스키마의 경우 앞에서 두 차원은 이미지의 행과 열을 나타내고 세 번째 차원은 각 픽셀의 R, G, B 값 목록(벡터)을 포함합니다.

{
  "instances": [
    [
      [
        [138, 30, 66],
        [130, 20, 56],
        ...
      ],
      [
        [126, 38, 61],
        [122, 24, 57],
        ...
      ],
      ...
    ],
    ...
  ]
}

데이터 인코딩

JSON 문자열은 UTF-8로 인코딩되어야 합니다. 바이너리 데이터를 보내려면 데이터를 base64로 인코딩하고 바이너리 데이터로 표시해야 합니다. JSON 문자열을 바이너리로 표시하려면 문자열을 b64라는 단일 속성의 JSON 객체로 대체합니다.

{"b64": "..."} 

다음 예시는 base64 인코딩을 필요로 하는 두 개의 직렬화된 tf.Examples 인스턴스를 보여줍니다(참고용 모의 데이터).

{"instances": [{"b64": "X5ad6u"}, {"b64": "IA9j4nx"}]}

다음 예시는 base64 인코딩을 필요로 하는 두 개의 JPEG 이미지 바이트 문자열을 보여줍니다(참고용 허위 데이터).

{"instances": [{"b64": "ASa8asdf"}, {"b64": "JLK7ljk3"}]}

여러 입력 텐서

일부 모델에는 여러 개의 입력 텐서를 허용하는 기본 텐서플로우 그래프가 있습니다. 이 경우 JSON 이름/값 쌍의 이름을 사용하여 입력 텐서를 식별합니다.

입력 텐서 별칭 '태그'(문자열) 및 '이미지'(base64로 인코딩된 문자열)가 있는 그래프의 경우는 다음과 같습니다.

{
  "instances": [
    {
      "tag": "beach",
      "image": {"b64": "ASa8asdf"}
    },
    {
      "tag": "car",
      "image": {"b64": "JLK7ljk3"}
    }
  ]
}

입력 텐서 별칭 '태그'(문자열) 및 '이미지'(8비트 정수의 3차원 배열)가 있는 그래프의 경우는 다음과 같습니다.

{
  "instances": [
    {
      "tag": "beach",
      "image": [
        [
          [138, 30, 66],
          [130, 20, 56],
          ...
        ],
        [
          [126, 38, 61],
          [122, 24, 57],
          ...
        ],
        ...
      ]
    },
    {
      "tag": "car",
      "image": [
        [
          [255, 0, 102],
          [255, 0, 97],
          ...
        ],
        [
          [254, 1, 101],
          [254, 2, 93],
          ...
        ],
        ...
      ]
    },
    ...
  ]
}

scikit-learn

요청 본문에는 다음과 같은 구조의 데이터가 포함됩니다(JSON 표현).

{
  "instances": [
    <simple list>,
    ...
  ]
}

instances[] 객체는 필수 항목이며 예측 결과를 가져올 인스턴스의 목록을 포함해야 합니다. 다음 예시에서 각 입력 인스턴스는 부동 소수점의 목록입니다.

{
  "instances": [
    [0.0, 1.1, 2.2],
    [3.3, 4.4, 5.5],
    ...
  ]
}

입력 인스턴스의 차원은 모델에 필요한 차원과 일치해야 합니다. 예를 들어 모델에 세 가지 특성이 필요한 경우 각 입력 인스턴스의 길이는 3이어야 합니다.

XGBoost

요청 본문에는 다음과 같은 구조의 데이터가 포함됩니다(JSON 표현).

{
  "instances": [
    <simple list>,
    ...
  ]
}

instances[] 객체는 필수 항목이며 예측 결과를 가져올 인스턴스의 목록을 포함해야 합니다. 다음 예시에서 각 입력 인스턴스는 부동 소수점의 목록입니다.

{
  "instances": [
    [0.0, 1.1, 2.2],
    [3.3, 4.4, 5.5],
    ...
  ]
}

입력 인스턴스의 차원은 모델에 필요한 차원과 일치해야 합니다. 예를 들어 모델에 세 가지 특성이 필요한 경우 각 입력 인스턴스의 길이는 3이어야 합니다.

XGBoost의 경우 Vertex AI는 입력 인스턴스의 희소 표현을 지원하지 않습니다.

온라인 예측 서비스는 0과 NaN을 다르게 해석합니다. 특성 값이 0이면 해당 입력에 0.0을 사용합니다. 특성 값이 누락된 경우 해당 입력에서 "NaN"을 사용합니다.

다음 예시는 첫 번째 특성 값이 0.0, 두 번째 특성 값이 1.1, 세 번째 특성 값이 누락된 단일 입력 인스턴스가 포함된 예측 요청을 나타냅니다.

{"instances": [[0.0, 1.1, "NaN"]]}

PyTorch

모델에서 PyTorch의 사전 빌드된 컨테이너를 사용하는 경우 TorchServe의 기본 핸들러는 각 인스턴스가 data 필드로 래핑될 것으로 예상합니다. 예를 들면 다음과 같습니다.

{
  "instances": [
    { "data": , <value> },
    { "data": , <value> }
  ]
}

응답 본문 세부정보

호출이 성공한 경우 응답 본문은 요청 본문의 인스턴스당 하나의 예측 항목을 포함하며 동일한 순서로 표시됩니다.

{
  "predictions": [
    {
      object
    }
  ],
  "deployedModelId": string
}

모든 인스턴스에 대한 예측이 실패하면 응답 본문은 예측을 포함하지 않습니다. 대신 단일 오류 항목을 포함합니다.

{
  "error": string
}

predictions[] 객체에는 요청의 인스턴스마다 예측 목록이 하나씩 포함됩니다.

오류가 발생하면 error 문자열은 문제를 설명하는 메시지를 포함합니다. 인스턴스를 처리하는 동안 오류가 발생한 경우 예측 목록 대신 오류가 반환됩니다.

예측은 인스턴스당 하나씩이지만 예측의 형식은 인스턴스의 형식과 직접적인 관련이 없습니다. 예측은 모델에 정의된 출력 컬렉션에 지정된 형식을 취합니다. 예측 컬렉션은 JSON 목록으로 반환됩니다. 목록의 각 구성원은 단순한 값, 목록, 다양한 복잡성을 가지는 JSON 객체일 수 있습니다. 모델에 둘 이상의 출력 텐서가 있는 경우 각 예측은 출력마다 이름/값 쌍을 포함하는 JSON 객체가 됩니다. 이름은 그래프의 출력 별칭을 식별합니다.

응답 본문 예시

TensorFlow

다음 예시에서는 몇 가지 가능한 응답을 보여줍니다.

  • 3개의 입력 인스턴스에 대한 간단한 예측 집합으로 각 예측은 정수 값입니다.

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 보다 복잡한 예측 집합으로 각 집합은 출력 텐서에 해당하는 두 개의 이름(각각 labelscores)이 지정된 값을 포함합니다. label 값은 예측 카테고리('car' 또는 'beach')이며 scores는 가능한 카테고리 범위에서 해당 인스턴스에 대한 확률 목록을 포함합니다.

    {
      "predictions": [
        {
          "label": "beach",
          "scores": [0.1, 0.9]
        },
        {
          "label": "car",
          "scores": [0.75, 0.25]
        }
      ],
      "deployedModelId": 123456789012345678
    }
    
  • 입력 인스턴스를 처리하는 중 오류가 발생했을 때의 응답입니다.

    {"error": "Divide by zero"}
    

scikit-learn

다음 예시에서는 몇 가지 가능한 응답을 보여줍니다.

  • 3개의 입력 인스턴스에 대한 간단한 예측 집합으로 각 예측은 정수 값입니다.

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 입력 인스턴스를 처리하는 중 오류가 발생했을 때의 응답입니다.

    {"error": "Divide by zero"}
    

XGBoost

다음 예시에서는 몇 가지 가능한 응답을 보여줍니다.

  • 3개의 입력 인스턴스에 대한 간단한 예측 집합으로 각 예측은 정수 값입니다.

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 입력 인스턴스를 처리하는 중 오류가 발생했을 때의 응답입니다.

    {"error": "Divide by zero"}
    

엔드포인트에 요청 보내기

요청을 보내는 방법은 세 가지가 있습니다.

  • 예측 요청: 온라인 예측을 가져오는 predict 요청을 보냅니다.

  • 원시 예측 요청: rawPredict 요청을 보냅니다. 이 페이지의 입력 형식 지정 섹션에 설명된 가이드라인을 따르는 대신 임의 HTTP 페이로드를 사용할 수 있습니다. 다음과 같은 경우 원시 예측을 확인할 수 있습니다.

    • 가이드라인과 다른 요청을 수신하고 응답을 전송하는 커스텀 컨테이너를 사용하는 경우
    • 지연 시간이 짧아야 하는 경우. rawPredict는 직렬화 단계를 건너뛰고 요청을 예측 컨테이너로 직접 전달합니다.
    • NVIDIA Triton으로 예측을 제공하는 경우
  • 설명 요청: explain 요청을 보냅니다. Vertex Explainable AI용으로 Model을 구성한 경우 온라인 설명을 가져올 수 있습니다. 온라인 설명 요청의 형식은 온라인 예측 요청과 동일하며 유사한 응답을 반환합니다. 유일한 차이는 온라인 설명 응답에는 예측뿐 아니라 특성 기여 분석이 포함된다는 점입니다.

온라인 예측 요청 전송

gcloud

다음 예시에서는 gcloud ai endpoints predict 명령어를 사용합니다.

  1. 다음 JSON 객체를 작성하여 로컬 환경에 보관합니다. 파일 이름은 중요하지 않지만 이 예시에서는 파일 이름을 request.json으로 지정합니다.

    {
     "instances": INSTANCES
    }
    

    다음을 바꿉니다.

    • INSTANCES: 예측을 가져올 인스턴스의 JSON 배열입니다. 각 인스턴스의 형식은 학습된 ML 모델이 예상하는 입력 내용에 따라 달라집니다. 자세한 내용은 온라인 예측 입력 형식 지정을 참조하세요.

  2. 다음 명령어를 실행합니다.

    gcloud ai endpoints predict ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json
    

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID
    • LOCATION_ID: Vertex AI를 사용하는 리전

REST

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

  • LOCATION_ID: Vertex AI를 사용하는 리전입니다.
  • PROJECT_ID: 프로젝트 ID입니다.
  • ENDPOINT_ID: 엔드포인트의 ID
  • INSTANCES: 예측을 가져올 인스턴스의 JSON 배열입니다. 각 인스턴스의 형식은 학습된 ML 모델이 예상하는 입력 내용에 따라 달라집니다. 자세한 내용은 온라인 예측 입력 형식 지정을 참조하세요.

HTTP 메서드 및 URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": INSTANCES
}

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

curl

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

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

PowerShell

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

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content
성공하면 다음과 비슷한 JSON 응답이 표시됩니다. 응답에서 다음 값이 바뀝니다.
  • PREDICTIONS: 요청 본문에 포함된 각 인스턴스당 하나의 JSON 요청 배열입니다.
  • DEPLOYED_MODEL_ID: 예측을 제공한 DeployedModel의 ID입니다.
{
  "predictions": PREDICTIONS,
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Java

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictRequest;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.protobuf.ListValue;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.List;

public class PredictCustomTrainedModelSample {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String instance = "[{ “feature_column_a”: “value”, “feature_column_b”: “value”}]";
    String project = "YOUR_PROJECT_ID";
    String endpointId = "YOUR_ENDPOINT_ID";
    predictCustomTrainedModel(project, endpointId, instance);
  }

  static void predictCustomTrainedModel(String project, String endpointId, String instance)
      throws IOException {
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.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 (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      ListValue.Builder listValue = ListValue.newBuilder();
      JsonFormat.parser().merge(instance, listValue);
      List<Value> instanceList = listValue.getValuesList();

      PredictRequest predictRequest =
          PredictRequest.newBuilder()
              .setEndpoint(endpointName.toString())
              .addAllInstances(instanceList)
              .build();
      PredictResponse predictResponse = predictionServiceClient.predict(predictRequest);

      System.out.println("Predict Custom Trained model Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());
      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {
        System.out.format("\tPrediction: %s\n", prediction);
      }
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

// const filename = "YOUR_PREDICTION_FILE_NAME";
// const endpointId = "YOUR_ENDPOINT_ID";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const util = require('util');
const {readFile} = require('fs');
const readFileAsync = util.promisify(readFile);

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

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

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function predictCustomTrainedModel() {
  // Configure the parent resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
  const parameters = {
    structValue: {
      fields: {},
    },
  };
  const instanceDict = await readFileAsync(filename, 'utf8');
  const instanceValue = JSON.parse(instanceDict);
  const instance = {
    structValue: {
      fields: {
        Age: {stringValue: instanceValue['Age']},
        Balance: {stringValue: instanceValue['Balance']},
        Campaign: {stringValue: instanceValue['Campaign']},
        Contact: {stringValue: instanceValue['Contact']},
        Day: {stringValue: instanceValue['Day']},
        Default: {stringValue: instanceValue['Default']},
        Deposit: {stringValue: instanceValue['Deposit']},
        Duration: {stringValue: instanceValue['Duration']},
        Housing: {stringValue: instanceValue['Housing']},
        Job: {stringValue: instanceValue['Job']},
        Loan: {stringValue: instanceValue['Loan']},
        MaritalStatus: {stringValue: instanceValue['MaritalStatus']},
        Month: {stringValue: instanceValue['Month']},
        PDays: {stringValue: instanceValue['PDays']},
        POutcome: {stringValue: instanceValue['POutcome']},
        Previous: {stringValue: instanceValue['Previous']},
      },
    },
  };

  const instances = [instance];
  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const [response] = await predictionServiceClient.predict(request);

  console.log('Predict custom trained model response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const prediction of predictions) {
    console.log(`\t\tPrediction : ${JSON.stringify(prediction)}`);
  }
}
predictCustomTrainedModel();

Python

Python을 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

def endpoint_predict_sample(
    project: str, location: str, instances: list, endpoint: str
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint)

    prediction = endpoint.predict(instances=instances)
    print(prediction)
    return prediction

온라인 원시 예측 요청 보내기

gcloud

다음 예시에서는 gcloud ai endpoints raw-predict 명령어를 사용합니다.

  • 명령줄에 지정된 REQUEST의 JSON 객체를 사용하여 예측을 요청하려면 다음 명령어를 사용합니다.

     gcloud ai endpoints raw-predict ENDPOINT_ID 
    --region=LOCATION
    --request REQUEST
  • image.jpeg 파일에 저장된 이미지와 적절한 Content-Type 헤더를 사용하여 예측을 요청하려면 다음 명령어를 사용합니다.

     gcloud ai endpoints raw-predict ENDPOINT_ID 
    --region=LOCATION
    --http-headers=Content-Type=image/jpeg
    --request @image.jpeg

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID
    • LOCATION_ID: Vertex AI를 사용하는 리전입니다.
    • REQUEST: 예측을 수행할 요청의 콘텐츠입니다. 요청 형식은 커스텀 컨테이너가 예상하는 대상에 따라 달라지며 JSON 객체일 필요는 없습니다.

Python

Python을 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for RawPredict
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.

# To install the latest published package dependency, execute the following:
#   python3 -m pip install google-cloud-aiplatform

from google.cloud import aiplatform_v1

def sample_raw_predict():
    # Create a client
    client = aiplatform_v1.PredictionServiceClient()

    # Initialize request argument(s)
    request = aiplatform_v1.RawPredictRequest(
        endpoint="endpoint_value",
    )

    # Make the request
    response = client.raw_predict(request=request)

    # Handle the response
    print(response)

응답에는 다음 HTTP 헤더가 포함됩니다.

  • X-Vertex-AI-Endpoint-Id: 이 예측을 제공한 Endpoint의 ID입니다.

  • X-Vertex-AI-Deployed-Model-Id: 이 예측을 제공한 엔드포인트의 DeployedModel ID입니다.

온라인 설명 요청 보내기

gcloud

다음 예시에서는 gcloud ai endpoints explain 명령어를 사용합니다.

  1. 다음 JSON 객체를 작성하여 로컬 환경에 보관합니다. 파일 이름은 중요하지 않지만 이 예시에서는 파일 이름을 request.json으로 지정합니다.

    {
     "instances": INSTANCES
    }
    

    다음을 바꿉니다.

    • INSTANCES: 예측을 가져올 인스턴스의 JSON 배열입니다. 각 인스턴스의 형식은 학습된 ML 모델이 예상하는 입력 내용에 따라 달라집니다. 자세한 내용은 온라인 예측 입력 형식 지정을 참조하세요.

  2. 다음 명령어를 실행합니다.

    gcloud ai endpoints explain ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json
    

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID
    • LOCATION_ID: Vertex AI를 사용하는 리전

    원하는 경우 Endpoint의 특정 DeployedModel에 설명 요청을 보내려면 --deployed-model-id 플래그를 지정할 수 있습니다.

    gcloud ai endpoints explain ENDPOINT_ID \
      --region=LOCATION \
      --deployed-model-id=DEPLOYED_MODEL_ID \
      --json-request=request.json
    

    앞에서 설명한 자리표시자 외에도 다음을 바꿉니다.

    • DEPLOYED_MODEL_ID 선택사항: 설명을 가져올 배포된 모델의 ID입니다. ID는 predict 메서드의 응답에 포함됩니다. 특정 모델에 대한 설명을 요청해야 하며 동일 엔드포인트에 배포된 모델이 2개 이상 있는 경우, 이 ID를 사용하여 특정 모델에 대한 설명이 반환되도록 할 수 있습니다.

REST

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

  • LOCATION_ID: Vertex AI를 사용하는 리전입니다.
  • PROJECT_ID: 프로젝트 ID입니다.
  • ENDPOINT_ID: 엔드포인트의 ID
  • INSTANCES: 예측을 가져올 인스턴스의 JSON 배열입니다. 각 인스턴스의 형식은 학습된 ML 모델이 예상하는 입력 내용에 따라 달라집니다. 자세한 내용은 온라인 예측 입력 형식 지정을 참조하세요.

HTTP 메서드 및 URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:explain

JSON 요청 본문:

{
  "instances": INSTANCES
}

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

curl

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

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

PowerShell

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

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:explain" | Select-Object -Expand Content
성공하면 다음과 비슷한 JSON 응답이 표시됩니다. 응답에서 다음 값이 바뀝니다.
  • PREDICTIONS: 요청 본문에 포함된 각 인스턴스당 하나의 JSON 요청 배열입니다.
  • EXPLANATIONS: 예측마다 하나의 설명의 JSON 배열입니다.
  • DEPLOYED_MODEL_ID: 예측을 제공한 DeployedModel의 ID입니다.
{
  "predictions": PREDICTIONS,
  "explanations": EXPLANATIONS,
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Python

Python을 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

def explain_tabular_sample(
    project: str, location: str, endpoint_id: str, instance_dict: Dict
):

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

    endpoint = aiplatform.Endpoint(endpoint_id)

    response = endpoint.explain(instances=[instance_dict], parameters={})

    for explanation in response.explanations:
        print(" explanation")
        # Feature attributions.
        attributions = explanation.attributions
        for attribution in attributions:
            print("  attribution")
            print("   baseline_output_value:", attribution.baseline_output_value)
            print("   instance_output_value:", attribution.instance_output_value)
            print("   output_display_name:", attribution.output_display_name)
            print("   approximation_error:", attribution.approximation_error)
            print("   output_name:", attribution.output_name)
            output_index = attribution.output_index
            for output_index in output_index:
                print("   output_index:", output_index)

    for prediction in response.predictions:
        print(prediction)

다음 단계