AutoML 모델에서 온라인 예측 수행

일부 데이터 유형의 경우 생성하여 엔드포인트에 배포한 후 AutoML 모델에서 온라인(실시간) 예측을 요청할 수 있습니다. 온라인 예측은 비동기식 요청인 일괄 예측과 달리 동기식 요청입니다.

애플리케이션 입력에 대한 응답으로 요청하거나 적시의 추론이 필요한 다른 상황에서 요청하는 경우에는 온라인 예측을 사용합니다.

온라인 예측을 수행하려면 분석을 위해 하나 이상의 테스트 항목을 모델에 제출하면 모델이 모델의 목표에 따른 결과를 반환합니다. 예측 결과에 대한 자세한 내용은 AutoML 모델의 결과 해석을 참조하세요.

Google Cloud 콘솔을 사용한 온라인 예측

Google Cloud 콘솔을 사용하여 온라인 예측을 요청합니다. 모델을 엔드포인트에 배포해야 합니다.

  1. Google Cloud 콘솔의 Vertex AI 섹션에서 모델 페이지로 이동합니다.

    모델 페이지로 이동

  2. 모델 목록에서 예측을 요청할 모델의 이름을 클릭합니다.

  3. 배포 및 테스트 탭을 선택합니다.

  4. 모델 테스트 섹션에서 테스트 항목을 추가하여 예측을 요청합니다.

    온라인 예측의 메서드와 입력은 모델의 목표에 따라 다릅니다. 예를 들어 텍스트 목표에 대한 AutoML 모델을 사용하려면 텍스트 필드에 콘텐츠를 입력하고 예측을 클릭해야 합니다. 이미지 목표에 대한 AutoML 모델을 사용하려면 이미지를 업로드하여 예측을 요청해야 합니다. 테이블 형식 모델의 경우 기준 예측 데이터가 자동으로 입력되거나, 자체 예측 데이터를 입력하고 예측을 클릭할 수 있습니다.

    테이블 형식 모델의 로컬 특성 중요도에 대한 자세한 내용은 설명 가져오기를 참조하세요.

    예측이 완료되면 Vertex AI가 콘솔에 결과를 반환합니다.

API로 온라인 예측

Vertex AI API를 사용하여 온라인 예측을 요청합니다. 모델을 엔드포인트에 배포해야 합니다.

이미지

이미지 데이터 유형 목표에는 분류와 객체 감지가 포함됩니다.

Edge 모델 예측: 예측에 AutoML 이미지 Edge 모델을 사용하는 경우 예측 요청을 보내기 전에 JPEG가 아닌 예측 파일을 JPEG 파일로 변환해야 합니다. 샘플 Python 사전 처리 함수는 Google Cloud AutoML API 저장소용 Python 클라이언트를 참조하세요.

분류

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [{
        "content": "CONTENT"
      }],
      "parameters": {
        "confidenceThreshold": THRESHOLD_VALUE,
        "maxPredictions": MAX_PREDICTIONS
      }
    }
    

    다음을 바꿉니다.

    • CONTENT: base64 인코딩 이미지 콘텐츠입니다.
    • THRESHOLD_VALUE(선택사항): 모델은 신뢰도가 이 값 이상인 예측만 반환합니다.
    • MAX_PREDICTIONS(선택사항): 모델은 신뢰도 점수가 높은 순으로 최대 이 수의 예측을 반환합니다.
  2. 다음 명령어를 실행합니다.

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: Vertex AI를 사용하는 리전

REST 및 명령줄

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

  • LOCATION: 엔드포인트가 있는 리전. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • CONTENT: base64 인코딩 이미지 콘텐츠입니다.
  • THRESHOLD_VALUE(선택사항): 모델은 신뢰도가 이 값 이상인 예측만 반환합니다.
  • MAX_PREDICTIONS(선택사항): 모델은 신뢰도 점수가 높은 순으로 최대 이 수의 예측을 반환합니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": [{
    "content": "CONTENT"
  }],
  "parameters": {
    "confidenceThreshold": THRESHOLD_VALUE,
    "maxPredictions": MAX_PREDICTIONS
  }
}

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

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/endpoints/ENDPOINT_ID:predict"

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/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

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

{
  "predictions": [
    {
      "confidences": [
        0.92629629373550415
      ],
      "ids": [
        "354376995678715904"
      ],
      "displayNames": [
        "sunflower"
      ]
    }
  ],
  "deployedModelId": "2119225099654529024"
}

Java

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


import com.google.api.client.util.Base64;
import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.instance.ImageClassificationPredictionInstance;
import com.google.cloud.aiplatform.v1.schema.predict.params.ImageClassificationPredictionParams;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.ClassificationPredictionResult;
import com.google.protobuf.Value;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class PredictImageClassificationSample {

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

  static void predictImageClassification(String project, String fileName, String endpointId)
      throws IOException {
    PredictionServiceSettings settings =
        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(settings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      byte[] contents = Base64.encodeBase64(Files.readAllBytes(Paths.get(fileName)));
      String content = new String(contents, StandardCharsets.UTF_8);

      ImageClassificationPredictionInstance predictionInstance =
          ImageClassificationPredictionInstance.newBuilder().setContent(content).build();

      List<Value> instances = new ArrayList<>();
      instances.add(ValueConverter.toValue(predictionInstance));

      ImageClassificationPredictionParams predictionParams =
          ImageClassificationPredictionParams.newBuilder()
              .setConfidenceThreshold((float) 0.5)
              .setMaxPredictions(5)
              .build();

      PredictResponse predictResponse =
          predictionServiceClient.predict(
              endpointName, instances, ValueConverter.toValue(predictionParams));
      System.out.println("Predict Image Classification Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {

        ClassificationPredictionResult.Builder resultBuilder =
            ClassificationPredictionResult.newBuilder();
        // Display names and confidences values correspond to
        // IDs in the ID list.
        ClassificationPredictionResult result =
            (ClassificationPredictionResult) ValueConverter.fromValue(resultBuilder, prediction);
        int counter = 0;
        for (Long id : result.getIdsList()) {
          System.out.printf("Label ID: %d\n", id);
          System.out.printf("Label: %s\n", result.getDisplayNames(counter));
          System.out.printf("Confidence: %.4f\n", result.getConfidences(counter));
          counter++;
        }
      }
    }
  }
}

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 filename = "YOUR_PREDICTION_FILE_NAME";
// const endpointId = "YOUR_ENDPOINT_ID";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {instance, params, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction Service Client library
const {PredictionServiceClient} = aiplatform.v1;

// 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 predictImageClassification() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const parametersObj = new params.ImageClassificationPredictionParams({
    confidenceThreshold: 0.5,
    maxPredictions: 5,
  });
  const parameters = parametersObj.toValue();

  const fs = require('fs');
  const image = fs.readFileSync(filename, 'base64');
  const instanceObj = new instance.ImageClassificationPredictionInstance({
    content: image,
  });
  const instanceValue = instanceObj.toValue();

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

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

  console.log('Predict image classification response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const predictionValue of predictions) {
    const predictionResultObj =
      prediction.ClassificationPredictionResult.fromValue(predictionValue);
    for (const [i, label] of predictionResultObj.displayNames.entries()) {
      console.log(`\tDisplay name: ${label}`);
      console.log(`\tConfidences: ${predictionResultObj.confidences[i]}`);
      console.log(`\tIDs: ${predictionResultObj.ids[i]}\n\n`);
    }
  }
}
predictImageClassification();

Python

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

import base64

from google.cloud import aiplatform
from google.cloud.aiplatform.gapic.schema import predict

def predict_image_classification_sample(
    project: str,
    endpoint_id: str,
    filename: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)
    with open(filename, "rb") as f:
        file_content = f.read()

    # The format of each instance should conform to the deployed model's prediction input schema.
    encoded_content = base64.b64encode(file_content).decode("utf-8")
    instance = predict.instance.ImageClassificationPredictionInstance(
        content=encoded_content,
    ).to_value()
    instances = [instance]
    # See gs://google-cloud-aiplatform/schema/predict/params/image_classification_1.0.0.yaml for the format of the parameters.
    parameters = predict.params.ImageClassificationPredictionParams(
        confidence_threshold=0.5, max_predictions=5,
    ).to_value()
    endpoint = client.endpoint_path(
        project=project, location=location, endpoint=endpoint_id
    )
    response = client.predict(
        endpoint=endpoint, instances=instances, parameters=parameters
    )
    print("response")
    print(" deployed_model_id:", response.deployed_model_id)
    # See gs://google-cloud-aiplatform/schema/predict/prediction/image_classification_1.0.0.yaml for the format of the predictions.
    predictions = response.predictions
    for prediction in predictions:
        print(" prediction:", dict(prediction))

객체 감지

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [{
        "content": "CONTENT"
      }],
      "parameters": {
        "confidenceThreshold": THRESHOLD_VALUE,
        "maxPredictions": MAX_PREDICTIONS
      }
    }
    

    다음을 바꿉니다.

    • CONTENT: base64 인코딩 이미지 콘텐츠입니다.
    • THRESHOLD_VALUE(선택사항): 모델은 신뢰도가 이 값 이상인 예측만 반환합니다.
    • MAX_PREDICTIONS(선택사항): 모델은 신뢰도 점수가 높은 순으로 최대 이 수의 예측을 반환합니다.
  2. 다음 명령어를 실행합니다.

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: Vertex AI를 사용하는 리전

REST 및 명령줄

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

  • LOCATION: 엔드포인트가 있는 리전. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • CONTENT: base64 인코딩 이미지 콘텐츠입니다.
  • THRESHOLD_VALUE(선택사항): 모델은 신뢰도가 이 값 이상인 예측만 반환합니다.
  • MAX_PREDICTIONS(선택사항): 모델은 신뢰도 점수가 높은 순으로 최대 이 수의 예측을 반환합니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": [{
    "content": "CONTENT"
  }],
  "parameters": {
    "confidenceThreshold": THRESHOLD_VALUE,
    "maxPredictions": MAX_PREDICTIONS
  }
}

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

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/endpoints/ENDPOINT_ID:predict"

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/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

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

{
  "predictions": [
    {
      "confidences": [
        0.975873291,
        0.972160876,
        0.879488528,
        0.866532683,
        0.686478078
      ],
      "displayNames": [
        "Salad",
        "Salad",
        "Tomato",
        "Tomato",
        "Salad"
      ],
      "ids": [
        "7517774415476555776",
        "7517774415476555776",
        "2906088397049167872",
        "2906088397049167872",
        "7517774415476555776"
      ],
      "bboxes": [
        [
          0.0869686604,
          0.977020741,
          0.395135701,
          1
        ],
        [
          0,
          0.488701463,
          0.00157663226,
          0.512249
        ],
        [
          0.361617863,
          0.509664357,
          0.772928834,
          0.914706349
        ],
        [
          0.310678929,
          0.45781514,
          0.565507233,
          0.711237729
        ],
        [
          0.584359646,
          1,
          0.00116168708,
          0.130817384
        ]
      ]
    }
  ],
  "deployedModelId": "3860570043075002368"
}

Java

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


import com.google.api.client.util.Base64;
import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.instance.ImageObjectDetectionPredictionInstance;
import com.google.cloud.aiplatform.v1.schema.predict.params.ImageObjectDetectionPredictionParams;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.ImageObjectDetectionPredictionResult;
import com.google.protobuf.Value;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class PredictImageObjectDetectionSample {

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

  static void predictImageObjectDetection(String project, String fileName, String endpointId)
      throws IOException {
    PredictionServiceSettings settings =
        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(settings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      byte[] contents = Base64.encodeBase64(Files.readAllBytes(Paths.get(fileName)));
      String content = new String(contents, StandardCharsets.UTF_8);

      ImageObjectDetectionPredictionParams params =
          ImageObjectDetectionPredictionParams.newBuilder()
              .setConfidenceThreshold((float) (0.5))
              .setMaxPredictions(5)
              .build();

      ImageObjectDetectionPredictionInstance instance =
          ImageObjectDetectionPredictionInstance.newBuilder().setContent(content).build();

      List<Value> instances = new ArrayList<>();
      instances.add(ValueConverter.toValue(instance));

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, ValueConverter.toValue(params));
      System.out.println("Predict Image Object Detection Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {

        ImageObjectDetectionPredictionResult.Builder resultBuilder =
            ImageObjectDetectionPredictionResult.newBuilder();

        ImageObjectDetectionPredictionResult result =
            (ImageObjectDetectionPredictionResult)
                ValueConverter.fromValue(resultBuilder, prediction);

        for (int i = 0; i < result.getIdsCount(); i++) {
          System.out.printf("\tDisplay name: %s\n", result.getDisplayNames(i));
          System.out.printf("\tConfidences: %f\n", result.getConfidences(i));
          System.out.printf("\tIDs: %d\n", result.getIds(i));
          System.out.printf("\tBounding boxes: %s\n", result.getBboxes(i));
        }
      }
    }
  }
}

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 filename = "YOUR_PREDICTION_FILE_NAME";
// const endpointId = "YOUR_ENDPOINT_ID";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {instance, params, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction Service Client library
const {PredictionServiceClient} = aiplatform.v1;

// 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 predictImageObjectDetection() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const parametersObj = new params.ImageObjectDetectionPredictionParams({
    confidenceThreshold: 0.5,
    maxPredictions: 5,
  });
  const parameters = parametersObj.toValue();

  const fs = require('fs');
  const image = fs.readFileSync(filename, 'base64');
  const instanceObj = new instance.ImageObjectDetectionPredictionInstance({
    content: image,
  });

  const instanceVal = instanceObj.toValue();
  const instances = [instanceVal];
  const request = {
    endpoint,
    instances,
    parameters,
  };

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

  console.log('Predict image object detection response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('Predictions :');
  for (const predictionResultVal of predictions) {
    const predictionResultObj =
      prediction.ImageObjectDetectionPredictionResult.fromValue(
        predictionResultVal
      );
    for (const [i, label] of predictionResultObj.displayNames.entries()) {
      console.log(`\tDisplay name: ${label}`);
      console.log(`\tConfidences: ${predictionResultObj.confidences[i]}`);
      console.log(`\tIDs: ${predictionResultObj.ids[i]}`);
      console.log(`\tBounding boxes: ${predictionResultObj.bboxes[i]}\n\n`);
    }
  }
}
predictImageObjectDetection();

Python

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

import base64

from google.cloud import aiplatform
from google.cloud.aiplatform.gapic.schema import predict

def predict_image_object_detection_sample(
    project: str,
    endpoint_id: str,
    filename: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)
    with open(filename, "rb") as f:
        file_content = f.read()

    # The format of each instance should conform to the deployed model's prediction input schema.
    encoded_content = base64.b64encode(file_content).decode("utf-8")
    instance = predict.instance.ImageObjectDetectionPredictionInstance(
        content=encoded_content,
    ).to_value()
    instances = [instance]
    # See gs://google-cloud-aiplatform/schema/predict/params/image_object_detection_1.0.0.yaml for the format of the parameters.
    parameters = predict.params.ImageObjectDetectionPredictionParams(
        confidence_threshold=0.5, max_predictions=5,
    ).to_value()
    endpoint = client.endpoint_path(
        project=project, location=location, endpoint=endpoint_id
    )
    response = client.predict(
        endpoint=endpoint, instances=instances, parameters=parameters
    )
    print("response")
    print(" deployed_model_id:", response.deployed_model_id)
    # See gs://google-cloud-aiplatform/schema/predict/prediction/image_object_detection_1.0.0.yaml for the format of the predictions.
    predictions = response.predictions
    for prediction in predictions:
        print(" prediction:", dict(prediction))

테이블 형식

테이블 형식 목표로는 분류와 회귀가 있습니다.

분류

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [
        {
          PREDICTION_DATA_ROW
        }
      ]
    }
    

    다음을 바꿉니다.

    • PREDICTION_DATA_ROW: JSON 객체를 해당 특성 값으로서의 특성 이름 및 값으로 바꿉니다. 예를 들어 숫자, 문자열 배열, 카테고리의 세 가지 특성이 있는 데이터 세트의 경우 데이터 행은 다음 예시 요청과 유사합니다.

      "length":3.6,
      "material":"cotton",
      "tag_array": ["abc","def"]
      

      학습에 포함된 모든 기능에 값을 제공해야 합니다. 예측에 사용되는 데이터의 형식은 학습에 사용되는 형식과 일치해야 합니다. 자세한 내용은 예측용 데이터 형식을 참조하세요.

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

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: Vertex AI를 사용하는 리전

REST 및 명령줄

endpoints.predict 메서드를 사용하여 온라인 예측을 요청합니다.

다음 예시는 로컬 특성 기여 분석이 없는 테이블 형식 분류 모델에 대한 온라인 예측 요청을 보여줍니다. 로컬 특성 기여 분석을 반환하려면 설명 가져오기를 참조하세요.

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

  • LOCATION: 엔드포인트가 있는 리전. us-central1).
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • PREDICTION_DATA_ROW: JSON 객체를 해당 특성 값으로서의 특성 이름 및 값으로 바꿉니다. 예를 들어 숫자, 문자열 배열, 카테고리의 세 가지 특성이 있는 데이터 세트의 경우 데이터 행은 다음 예시 요청과 유사합니다.

    "length":3.6,
    "material":"cotton",
    "tag_array": ["abc","def"]
    

    학습에 포함된 모든 기능에 값을 제공해야 합니다. 예측에 사용되는 데이터의 형식은 학습에 사용되는 형식과 일치해야 합니다. 자세한 내용은 예측용 데이터 형식을 참조하세요.

  • DEPLOYED_MODEL_ID: predict 메서드에 의해 출력되고 explain 메서드에 의해 입력으로 수락되는 값. 예측을 생성하는 데 사용되는 모델의 ID입니다. 이전에 요청한 예측에 대한 설명을 요청해야 하고 2개 이상의 모델을 배포했다면 이 ID를 사용하여 이전 예측을 제공한 동일한 모델에 대한 설명을 반환할 수 있습니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": [
    {
      PREDICTION_DATA_ROW
    }
  ]
}

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

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/endpoints/ENDPOINT_ID:predict"

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/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

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

{
  "predictions": [
    {
      "scores": [
        0.96771615743637085,
        0.032283786684274673
      ],
      "classes": [
        "0",
        "1"
      ]
   }
  ]
  "deployedModelId": "2429510197"
}

Java

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


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.TabularClassificationPredictionResult;
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 PredictTabularClassificationSample {

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

  static void predictTabularClassification(String instance, String project, String endpointId)
      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();

      Value parameters = Value.newBuilder().setListValue(listValue).build();
      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instanceList, parameters);
      System.out.println("Predict Tabular Classification Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {
        TabularClassificationPredictionResult.Builder resultBuilder =
            TabularClassificationPredictionResult.newBuilder();
        TabularClassificationPredictionResult result =
            (TabularClassificationPredictionResult)
                ValueConverter.fromValue(resultBuilder, prediction);

        for (int i = 0; i < result.getClassesCount(); i++) {
          System.out.printf("\tClass: %s", result.getClasses(i));
          System.out.printf("\tScore: %f", result.getScores(i));
        }
      }
    }
  }
}

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 endpointId = 'YOUR_ENDPOINT_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = 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 predictTablesClassification() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
  const parameters = helpers.toValue({});

  const instance = helpers.toValue({
    petal_length: '1.4',
    petal_width: '1.3',
    sepal_length: '5.1',
    sepal_width: '2.8',
  });

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

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

  console.log('Predict tabular classification response');
  console.log(`\tDeployed model id : ${response.deployedModelId}\n`);
  const predictions = response.predictions;
  console.log('Predictions :');
  for (const predictionResultVal of predictions) {
    const predictionResultObj =
      prediction.TabularClassificationPredictionResult.fromValue(
        predictionResultVal
      );
    for (const [i, class_] of predictionResultObj.classes.entries()) {
      console.log(`\tClass: ${class_}`);
      console.log(`\tScore: ${predictionResultObj.scores[i]}\n\n`);
    }
  }
}
predictTablesClassification();

Python

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

def predict_tabular_classification_sample(
    project: str,
    location: str,
    endpoint_name: str,
    instances: List[Dict],
):
    """
    Args
        project: Your project ID or project number.
        location: Region where Endpoint is located. For example, 'us-central1'.
        endpoint_name: A fully qualified endpoint name or endpoint ID. Example: "projects/123/locations/us-central1/endpoints/456" or
               "456" when project and location are initialized or passed.
        instances: A list of one or more instances (examples) to return a prediction for.
    """
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint_name)

    response = endpoint.predict(instances=instances)

    for prediction_ in response.predictions:
        print(prediction_)

예측

예측 모델에서는 온라인 예측을 지원하지 않습니다. 대신 일괄 예측을 사용합니다.

회귀

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [
        {
          PREDICTION_DATA_ROW
        }
      ]
    }
    

    다음을 바꿉니다.

    • PREDICTION_DATA_ROW: JSON 객체를 해당 특성 값으로서의 특성 이름 및 값으로 바꿉니다. 예를 들어 숫자, 숫자 배열, 카테고리의 세 가지 특성이 있는 데이터 세트의 경우 데이터 행은 다음 예시 요청과 유사합니다.

      "age":3.6,
      "sq_ft":5392,
      "code": "90331"
      

      학습에 포함된 모든 기능에 값을 제공해야 합니다. 예측에 사용되는 데이터의 형식은 학습에 사용되는 형식과 일치해야 합니다. 자세한 내용은 예측용 데이터 형식을 참조하세요.

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

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: Vertex AI를 사용하는 리전

REST 및 명령줄

endpoints.predict 메서드를 사용하여 온라인 예측을 요청합니다.

다음 예시는 로컬 특성 기여 분석이 없는 테이블 형식 회귀 모델에 대한 온라인 예측 요청을 보여줍니다. 로컬 특성 기여 분석을 반환하려면 설명 가져오기를 참조하세요.

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

  • LOCATION: 엔드포인트가 있는 리전. us-central1).
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • PREDICTION_DATA_ROW: JSON 객체를 해당 특성 값으로서의 특성 이름 및 값으로 바꿉니다. 예를 들어 숫자, 숫자 배열, 카테고리의 세 가지 특성이 있는 데이터 세트의 경우 데이터 행은 다음 예시 요청과 유사합니다.

    "age":3.6,
    "sq_ft":5392,
    "code": "90331"
    

    학습에 포함된 모든 기능에 값을 제공해야 합니다. 예측에 사용되는 데이터의 형식은 학습에 사용되는 형식과 일치해야 합니다. 자세한 내용은 예측용 데이터 형식을 참조하세요.

  • DEPLOYED_MODEL_ID: predict 메서드에 의해 출력되고 explain 메서드에 의해 입력으로 수락되는 값. 예측을 생성하는 데 사용되는 모델의 ID입니다. 이전에 요청한 예측에 대한 설명을 요청해야 하고 2개 이상의 모델을 배포했다면 이 ID를 사용하여 이전 예측을 제공한 동일한 모델에 대한 설명을 반환할 수 있습니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": [
    {
      PREDICTION_DATA_ROW
    }
  ]
}

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

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/endpoints/ENDPOINT_ID:predict"

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/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

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

{
  "predictions": [
    [
      {
        "value": 65.14233,
        "lower_bound": 4.6572
        "upper_bound": 164.0279
      }
    ]
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Java

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


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.TabularRegressionPredictionResult;
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 PredictTabularRegressionSample {

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

  static void predictTabularRegression(String instance, String project, String endpointId)
      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();

      Value parameters = Value.newBuilder().setListValue(listValue).build();
      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instanceList, parameters);
      System.out.println("Predict Tabular Regression Response");
      System.out.format("\tDisplay Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {
        TabularRegressionPredictionResult.Builder resultBuilder =
            TabularRegressionPredictionResult.newBuilder();

        TabularRegressionPredictionResult result =
            (TabularRegressionPredictionResult) ValueConverter.fromValue(resultBuilder, prediction);

        System.out.printf("\tUpper bound: %f\n", result.getUpperBound());
        System.out.printf("\tLower bound: %f\n", result.getLowerBound());
        System.out.printf("\tValue: %f\n", result.getValue());
      }
    }
  }
}

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 endpointId = 'YOUR_ENDPOINT_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = 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 predictTablesRegression() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
  const parameters = helpers.toValue({});

  // TODO (erschmid): Make this less painful
  const instance = helpers.toValue({
    BOOLEAN_2unique_NULLABLE: false,
    DATETIME_1unique_NULLABLE: '2019-01-01 00:00:00',
    DATE_1unique_NULLABLE: '2019-01-01',
    FLOAT_5000unique_NULLABLE: 1611,
    FLOAT_5000unique_REPEATED: [2320, 1192],
    INTEGER_5000unique_NULLABLE: '8',
    NUMERIC_5000unique_NULLABLE: 16,
    STRING_5000unique_NULLABLE: 'str-2',
    STRUCT_NULLABLE: {
      BOOLEAN_2unique_NULLABLE: false,
      DATE_1unique_NULLABLE: '2019-01-01',
      DATETIME_1unique_NULLABLE: '2019-01-01 00:00:00',
      FLOAT_5000unique_NULLABLE: 1308,
      FLOAT_5000unique_REPEATED: [2323, 1178],
      FLOAT_5000unique_REQUIRED: 3089,
      INTEGER_5000unique_NULLABLE: '1777',
      NUMERIC_5000unique_NULLABLE: 3323,
      TIME_1unique_NULLABLE: '23:59:59.999999',
      STRING_5000unique_NULLABLE: 'str-49',
      TIMESTAMP_1unique_NULLABLE: '1546387199999999',
    },
    TIMESTAMP_1unique_NULLABLE: '1546387199999999',
    TIME_1unique_NULLABLE: '23:59:59.999999',
  });

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

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

  console.log('Predict tabular regression response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const predictionResultVal of predictions) {
    const predictionResultObj =
      prediction.TabularRegressionPredictionResult.fromValue(
        predictionResultVal
      );
    console.log(`\tUpper bound: ${predictionResultObj.upper_bound}`);
    console.log(`\tLower bound: ${predictionResultObj.lower_bound}`);
    console.log(`\tLower bound: ${predictionResultObj.value}`);
  }
}
predictTablesRegression();

Python

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

def predict_tabular_regression_sample(
    project: str,
    location: str,
    endpoint_name: str,
    instances: List[Dict],
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint_name)

    response = endpoint.predict(instances=instances)

    for prediction_ in response.predictions:
        print(prediction_)

텍스트

텍스트 데이터 유형 목표에는 분류, 항목 추출, 감정 분석이 포함됩니다.

분류

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [{
        "mimeType": "text/plain",
        "content": "CONTENT"
      }]
    }
    

    다음을 바꿉니다.

    • CONTENT: 예측을 수행할 텍스트 스니펫입니다.
  2. 다음 명령어를 실행합니다.

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: Vertex AI를 사용하는 리전

REST 및 명령줄

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

  • LOCATION: 엔드포인트가 있는 리전. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • CONTENT: 예측을 수행할 텍스트 스니펫입니다.
  • DEPLOYED_MODEL_ID: 예측을 위해 사용된 배포된 모델의 ID입니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": [{
    "mimeType": "text/plain",
    "content": "CONTENT"
  }]
}

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

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/endpoints/ENDPOINT_ID:predict"

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/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

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

{
  "predictions": [
    {
      "ids": [
        "1234567890123456789",
        "2234567890123456789",
        "3234567890123456789"
      ],
      "displayNames": [
        "GreatService",
        "Suggestion",
        "InfoRequest"
      ],
      "confidences": [
        0.8986392080783844,
        0.81984345316886902,
        0.7722353458404541
      ]
    }
  ],
  "deployedModelId": "0123456789012345678"
}

Java

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

import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.instance.TextClassificationPredictionInstance;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.ClassificationPredictionResult;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PredictTextClassificationSingleLabelSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String content = "YOUR_TEXT_CONTENT";
    String endpointId = "YOUR_ENDPOINT_ID";

    predictTextClassificationSingleLabel(project, content, endpointId);
  }

  static void predictTextClassificationSingleLabel(
      String project, String content, String endpointId) 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);

      TextClassificationPredictionInstance predictionInstance =
          TextClassificationPredictionInstance.newBuilder().setContent(content).build();

      List<Value> instances = new ArrayList<>();
      instances.add(ValueConverter.toValue(predictionInstance));

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, ValueConverter.EMPTY_VALUE);
      System.out.println("Predict Text Classification Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions:\n\n");
      for (Value prediction : predictResponse.getPredictionsList()) {

        ClassificationPredictionResult.Builder resultBuilder =
            ClassificationPredictionResult.newBuilder();

        // Display names and confidences values correspond to
        // IDs in the ID list.
        ClassificationPredictionResult result =
            (ClassificationPredictionResult) ValueConverter.fromValue(resultBuilder, prediction);
        int counter = 0;
        for (Long id : result.getIdsList()) {
          System.out.printf("Label ID: %d\n", id);
          System.out.printf("Label: %s\n", result.getDisplayNames(counter));
          System.out.printf("Confidence: %.4f\n", result.getConfidences(counter));
          counter++;
        }
      }
    }
  }
}

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 text = 'YOUR_PREDICTION_TEXT';
// const endpointId = 'YOUR_ENDPOINT_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {instance, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Model Service Client library
const {PredictionServiceClient} = aiplatform.v1;

// 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 predictTextClassification() {
  // Configure the resources
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const predictionInstance =
    new instance.TextClassificationPredictionInstance({
      content: text,
    });
  const instanceValue = predictionInstance.toValue();

  const instances = [instanceValue];
  const request = {
    endpoint,
    instances,
  };

  const [response] = await predictionServiceClient.predict(request);
  console.log('Predict text classification response');
  console.log(`\tDeployed model id : ${response.deployedModelId}\n\n`);

  console.log('Prediction results:');

  for (const predictionResultValue of response.predictions) {
    const predictionResult =
      prediction.ClassificationPredictionResult.fromValue(
        predictionResultValue
      );

    for (const [i, label] of predictionResult.displayNames.entries()) {
      console.log(`\tDisplay name: ${label}`);
      console.log(`\tConfidences: ${predictionResult.confidences[i]}`);
      console.log(`\tIDs: ${predictionResult.ids[i]}\n\n`);
    }
  }
}
predictTextClassification();

Python

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

def predict_text_classification_single_label_sample(
    project, location, endpoint, content
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint)

    response = endpoint.predict(instances=[{"content": content}], parameters={})

    for prediction_ in response.predictions:
        print(prediction_)

항목 추출

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [{
        "mimeType": "text/plain",
        "content": "CONTENT"
      }]
    }
    

    다음을 바꿉니다.

    • CONTENT: 예측을 수행할 텍스트 스니펫입니다.
  2. 다음 명령어를 실행합니다.

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: Vertex AI를 사용하는 리전

REST 및 명령줄

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

  • LOCATION: 엔드포인트가 있는 리전. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • CONTENT: 예측을 수행할 텍스트 스니펫입니다.
  • DEPLOYED_MODEL_ID: 예측을 위해 사용된 배포된 모델의 ID입니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": [{
    "mimeType": "text/plain",
    "content": "CONTENT"
  }]
}

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

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/endpoints/ENDPOINT_ID:predict"

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/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

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

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

Java

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


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.instance.TextExtractionPredictionInstance;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.TextExtractionPredictionResult;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PredictTextEntityExtractionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String content = "YOUR_TEXT_CONTENT";
    String endpointId = "YOUR_ENDPOINT_ID";

    predictTextEntityExtraction(project, content, endpointId);
  }

  static void predictTextEntityExtraction(String project, String content, String endpointId)
      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";
      String jsonString = "{\"content\": \"" + content + "\"}";

      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      TextExtractionPredictionInstance instance =
          TextExtractionPredictionInstance.newBuilder().setContent(content).build();

      List<Value> instances = new ArrayList<>();
      instances.add(ValueConverter.toValue(instance));

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, ValueConverter.EMPTY_VALUE);
      System.out.println("Predict Text Entity Extraction Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {
        TextExtractionPredictionResult.Builder resultBuilder =
            TextExtractionPredictionResult.newBuilder();

        TextExtractionPredictionResult result =
            (TextExtractionPredictionResult) ValueConverter.fromValue(resultBuilder, prediction);

        for (int i = 0; i < result.getIdsCount(); i++) {
          long textStartOffset = result.getTextSegmentStartOffsets(i);
          long textEndOffset = result.getTextSegmentEndOffsets(i);
          String entity = content.substring((int) textStartOffset, (int) textEndOffset);

          System.out.format("\tEntity: %s\n", entity);
          System.out.format("\tEntity type: %s\n", result.getDisplayNames(i));
          System.out.format("\tConfidences: %f\n", result.getConfidences(i));
          System.out.format("\tIDs: %d\n", result.getIds(i));
        }
      }
    }
  }
}

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 text = "YOUR_PREDICTION_TEXT";
// const endpointId = "YOUR_ENDPOINT_ID";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {instance, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Model Service Client library
const {PredictionServiceClient} = aiplatform.v1;

// 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 predictTextEntityExtraction() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const instanceObj = new instance.TextExtractionPredictionInstance({
    content: text,
  });
  const instanceVal = instanceObj.toValue();
  const instances = [instanceVal];

  const request = {
    endpoint,
    instances,
  };

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

  console.log('Predict text entity extraction response :');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);

  console.log('\nPredictions :');
  for (const predictionResultValue of response.predictions) {
    const predictionResult =
      prediction.TextExtractionPredictionResult.fromValue(
        predictionResultValue
      );

    for (const [i, label] of predictionResult.displayNames.entries()) {
      const textStartOffset = parseInt(
        predictionResult.textSegmentStartOffsets[i]
      );
      const textEndOffset = parseInt(
        predictionResult.textSegmentEndOffsets[i]
      );
      const entity = text.substring(textStartOffset, textEndOffset);
      console.log(`\tEntity: ${entity}`);
      console.log(`\tEntity type: ${label}`);
      console.log(`\tConfidences: ${predictionResult.confidences[i]}`);
      console.log(`\tIDs: ${predictionResult.ids[i]}\n\n`);
    }
  }
}
predictTextEntityExtraction();

Python

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

def predict_text_entity_extraction_sample(project, location, endpoint_id, content):

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

    endpoint = aiplatform.Endpoint(endpoint_id)

    response = endpoint.predict(instances=[{"content": content}], parameters={})

    for prediction_ in response.predictions:
        print(prediction_)

감정 분석

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [{
        "mimeType": "text/plain",
        "content": "CONTENT"
      }]
    }
    

    다음을 바꿉니다.

    • CONTENT: 예측을 수행할 텍스트 스니펫입니다.
  2. 다음 명령어를 실행합니다.

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: Vertex AI를 사용하는 리전

REST 및 명령줄

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

  • LOCATION: 엔드포인트가 있는 리전. 예를 들면 us-central1입니다.
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • CONTENT: 예측을 수행할 텍스트 스니펫입니다.
  • DEPLOYED_MODEL_ID: 예측을 위해 사용된 배포된 모델의 ID입니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:predict

JSON 요청 본문:

{
  "instances": [{
    "mimeType": "text/plain",
    "content": "CONTENT"
  }]
}

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

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/endpoints/ENDPOINT_ID:predict"

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/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

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

{
  "prediction":
    {
      sentiment": 8
    },
  "deployedModelId": "1234567890123456789"
}

Java

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


import com.google.cloud.aiplatform.v1.EndpointName;
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.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PredictTextSentimentAnalysisSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String content = "YOUR_TEXT_CONTENT";
    String endpointId = "YOUR_ENDPOINT_ID";

    predictTextSentimentAnalysis(project, content, endpointId);
  }

  static void predictTextSentimentAnalysis(String project, String content, String endpointId)
      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";
      String jsonString = "{\"content\": \"" + content + "\"}";

      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      Value parameter = Value.newBuilder().setNumberValue(0).setNumberValue(5).build();
      Value.Builder instance = Value.newBuilder();
      JsonFormat.parser().merge(jsonString, instance);

      List<Value> instances = new ArrayList<>();
      instances.add(instance.build());

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, parameter);
      System.out.println("Predict Text Sentiment Analysis 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용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const text = "YOUR_PREDICTION_TEXT";
// const endpointId = "YOUR_ENDPOINT_ID";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {instance, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Model Service Client library
const {PredictionServiceClient} = aiplatform.v1;

// 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 predictTextSentimentAnalysis() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const instanceObj = new instance.TextSentimentPredictionInstance({
    content: text,
  });
  const instanceVal = instanceObj.toValue();

  const instances = [instanceVal];
  const request = {
    endpoint,
    instances,
  };

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

  console.log('Predict text sentiment analysis response:');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);

  console.log('\nPredictions :');
  for (const predictionResultValue of response.predictions) {
    const predictionResult =
      prediction.TextSentimentPredictionResult.fromValue(
        predictionResultValue
      );
    console.log(`\tSentiment measure: ${predictionResult.sentiment}`);
  }
}
predictTextSentimentAnalysis();

Python

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

def predict_text_sentiment_analysis_sample(project, location, endpoint_id, content):

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

    endpoint = aiplatform.Endpoint(endpoint_id)

    response = endpoint.predict(instances=[{"content": content}], parameters={})

    for prediction_ in response.predictions:
        print(prediction_)

테이블 형식 모델에서 설명 가져오기

AutoML 테이블 형식 모델의 경우, 설명(특성 기여 분석이라고도 함)을 사용하여 온라인 예측을 요청하면 모델이 예측에 어떻게 도착했는지 확인할 수 있습니다. 로컬 특성 중요도 값은 각 특성이 이 예측의 예측 결과에 기여한 정도를 나타냅니다.

로컬 특성 중요도 결과 해석에 대해 자세히 알아보세요.

특성 기여 분석은 Vertex Explainable AI를 통한 Vertex AI 예측에 포함되어 있습니다. Explainable AI에 대해 자세히 알아보세요.

Console

Google Cloud 콘솔을 사용하여 온라인 예측을 요청하면 로컬 특성 중요도 값이 자동으로 반환됩니다.

미리 채워진 예측 값을 사용한 경우 로컬 특성 중요도 값은 모두 0입니다. 미리 채워진 값은 기준 예측 데이터이므로 반환되는 예측이 기준 예측 값입니다.

gcloud

  1. 다음 콘텐츠로 request.json라는 파일을 만듭니다.

    {
      "instances": [
        {
          PREDICTION_DATA_ROW
        }
      ]
    }
    

    다음을 바꿉니다.

    • PREDICTION_DATA_ROW: JSON 객체를 해당 특성 값으로서의 특성 이름 및 값으로 바꿉니다. 예를 들어 숫자, 문자열 배열, 카테고리의 세 가지 특성이 있는 데이터 세트의 경우 데이터 행은 다음 예시 요청과 유사합니다.

      "length":3.6,
      "material":"cotton",
      "tag_array": ["abc","def"]
      

      학습에 포함된 모든 기능에 값을 제공해야 합니다. 예측에 사용되는 데이터의 형식은 학습에 사용되는 형식과 일치해야 합니다. 자세한 내용은 예측용 데이터 형식을 참조하세요.

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

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

    다음을 바꿉니다.

    • ENDPOINT_ID: 엔드포인트의 ID입니다.
    • LOCATION: 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: 엔드포인트가 있는 리전. us-central1).
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • PREDICTION_DATA_ROW: JSON 객체를 해당 특성 값으로서의 특성 이름 및 값으로 바꿉니다. 예를 들어 숫자, 문자열 배열, 카테고리의 세 가지 특성이 있는 데이터 세트의 경우 데이터 행은 다음 예시 요청과 유사합니다.

    "length":3.6,
    "material":"cotton",
    "tag_array": ["abc","def"]
    

    학습에 포함된 모든 기능에 값을 제공해야 합니다. 예측에 사용되는 데이터의 형식은 학습에 사용되는 형식과 일치해야 합니다. 자세한 내용은 예측용 데이터 형식을 참조하세요.

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

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:explain

JSON 요청 본문:

{
  "instances": [
    {
      PREDICTION_DATA_ROW
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

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

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/endpoints/ENDPOINT_ID:explain"

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/endpoints/ENDPOINT_ID:explain" | Select-Object -Expand Content
 

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI 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)

결과 해석에 대한 샘플 응답 및 정보는 AutoML 모델의 예측 결과 해석을 참조하세요.

이전에 반환된 예측에 대한 설명 가져오기

설명은 리소스 사용량을 증가시키므로, 필요한 경우 상황에 대한 설명 요청을 예약하는 것이 좋습니다. 간혹 예측이 이상점이거나 합리적이기 않은 경우 이미 수신된 예측 결과에 대한 설명을 요청하는 것이 유용할 수 있습니다.

모든 예측이 동일한 모델에서 오는 경우 이번에는 요청된 설명과 함께 요청 데이터를 다시 전송하면 됩니다. 그러나 예측을 반환하는 모델이 여러 개 있는 경우에는 올바른 모델로 설명 요청을 보내야 합니다. 원래 예측 요청의 응답에 포함되기도 한, 요청의 배포된 모델 ID를 포함하여 특정 모델에 대한 설명을 확인할 수 있습니다. 배포된 모델 ID는 모델 ID와 다릅니다.

다음 단계