온라인 예측

이 페이지에서는 AutoML Tables에서 온라인(단일, 짧은 대기 시간) 예측을 얻는 방법을 설명합니다.

소개

모델을 생성(학습)한 후에는 모델을 배포하고 온라인(실시간) 예측을 요청할 수 있습니다. 온라인 예측은 데이터 행 하나를 허용하고, 해당 데이터에 대해 모델을 기준으로 예측한 결과를 제공합니다. 온라인 예측은 예측을 비즈니스 논리 흐름의 입력으로 사용해야 할 때 사용합니다.

온라인 예측을 요청하려면 먼저 모델을 배포해야 합니다. 배포한 모델에는 요금이 부과됩니다. 온라인 예측 작성이 끝나면 추가 배포 요금이 부과되지 않도록 모델 배포를 취소할 수 있습니다. 자세히 알아보기

예측을 계속 제공하려면 6개월마다 모델을 다시 학습시켜야 합니다.

온라인 예측 얻기

콘솔

일반적으로 온라인 예측을 사용하여 비즈니스 애플리케이션 내에서 예측을 가져옵니다. 그러나 Google Cloud Console에서 AutoML Tables를 사용하면 특정 입력 집합이 포함된 모델 또는 데이터 형식을 테스트할 수 있습니다.

  1. Google Cloud Console의 AutoML Tables 페이지로 이동합니다.

    AutoML Tables 페이지로 이동

  2. 모델을 선택하고 사용할 모델을 선택합니다.

  3. 테스트 및 사용 탭을 선택하고 온라인 예측을 클릭합니다.

  4. 모델이 아직 배포되지 않았다면 모델 배포를 클릭하여 바로 배포합니다.

    온라인 예측을 사용하려면 모델을 배포해야 합니다. 모델을 배포하면 비용이 발생합니다. 자세한 내용은 가격 책정 페이지를 참조하세요.

  5. 제공된 텍스트 상자에 입력 값을 제공합니다.

    또는 JSON 형식으로 제공하려면 JSON 코드 뷰를 선택합니다.

  6. 각 특성이 예측에 미치는 영향을 확인하려면 특성 중요도 생성을 선택합니다.

    Google Cloud Console은 가독성을 위해 로컬 특성 중요도 값을 자릅니다. 정확한 값이 필요하면 Cloud AutoML API를 사용해 예측 요청을 실행합니다.

    특성 중요도에 대한 자세한 내용은 로컬 특성 중요도를 참조하세요.

  7. 예측을 클릭하여 예측을 얻습니다.

    AutoML Tables 예측 페이지

    예측 결과 해석에 대한 자세한 내용은 예측 결과 해석을 참조하세요. 로컬 특성 중요도에 대한 자세한 내용은 로컬 특성 중요도를 참조하세요.

  8. (선택사항) 더 이상 온라인 예측을 요청할 계획이 없으면 모델 배포 취소를 클릭해 모델의 배포를 취소하여 배포 요금이 부과되지 않도록 하세요.

curl

값 모음에 대한 예측을 요청하려면 특성 값을 사용해 JSON 객체를 만들고 model.predict 메서드를 사용해 예측을 얻어야 합니다.

값에는 학습에 포함한 정확한 열이 있어야 하며, 평가 탭에서 포함된 열 링크를 클릭하면 표시되는 순서와 일치해야 합니다.

값의 순서를 바꾸려면 열 사양 ID 모음을 값의 순서대로 포함하면 됩니다. 열 사양 ID는 모델 객체의 TablesModelMetadata.inputFeatureColumnSpecs 필드에서 얻을 수 있습니다.

행 객체에 있는 각 값(특성)의 데이터 유형은 특성의 AutoML Tables 유형에 따라 달라집니다. 허용되는 데이터 유형 목록을 AutoML Tables 데이터 유형별로 보려면 행 객체 형식을 참조하세요.

  1. 아직 모델을 배포하지 않았다면 지금 배포하세요. 자세히 알아보기

  2. 예측을 요청합니다.

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

    • endpoint: 전역 위치인 경우 automl.googleapis.com, EU 리전인 경우 eu-automl.googleapis.com입니다.
    • project-id: Google Cloud 프로젝트 ID입니다.
    • location: 리소스의 위치로 전역인 경우 us-central1, 유럽 연합인 경우 eu입니다.
    • model-id: 모델의 ID입니다. 예를 들면 TBL543입니다.
    • valueN: 각 열의 값이 올바른 순서로 표시됩니다.

    HTTP 메서드 및 URL:

    POST https://endpoint/v1beta1/projects/project-id/locations/location/models/model-id:predict

    JSON 요청 본문:

    {
      "payload": {
        "row": {
          "values": [
            value1, value2,...
          ]
        }
      }
    }
    

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

    curl

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

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "x-goog-user-project: project-id" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://endpoint/v1beta1/projects/project-id/locations/location/models/model-id:predict"

    PowerShell

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

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://endpoint/v1beta1/projects/project-id/locations/location/models/model-id:predict" | Select-Object -Expand Content
      로컬 특성 중요도 결과를 포함하려면 feature_importance 매개변수를 포함하세요. 로컬 특성 중요도에 대한 자세한 내용은 로컬 특성 중요도를 참조하세요.

  3. 결과를 확인합니다.

    분류 모델에서는 다음 예와 비슷한 출력이 표시됩니다. 신뢰도 추정치(score)가 있는 결과 2개가 반환되는지 확인하세요. 신뢰도 추정치는 0과 1 사이이며 모델이 이를 올바른 예측치라고 생각할 확률을 나타냅니다. 신뢰도 추정치 사용 방법에 대한 자세한 내용은 예측 결과 해석을 참조하세요.

    {
     "payload": [
       {
         "tables": {
           "score": 0.11210235,
           "value": "1"
         }
       },
       {
         "tables": {
           "score": 0.8878976,
           "value": "2"
         }
       }
     ]
    }
    

    회귀 모델의 경우 결과에 예측 값과 예측 간격이 포함됩니다. 예측 간격은 모델이 학습된 데이터를 기반으로 시간의 true 값 95%를 포함하는 범위를 제공합니다. 예측 간격이 중앙값을 중심으로 하는 반면 예측 값은 예상 값(또는 평균)이므로 예측 값이 간격의 중심에 있지 않을 수도 있습니다(간격을 벗어나는 경우도 있음).

    {
     "payload": [
       {
         "tables": {
           "value": 207.18209838867188,
           "predictionInterval": {
             "start": 29.712770462036133,
             "end": 937.42041015625
           }
         }
       }
     ]
    }
    

    로컬 특성 중요도 결과에 대한 자세한 내용은 로컬 특성 중요도를 참조하세요.

  4. (선택사항) 온라인 예측이 끝났으면 모델의 배포를 취소하여 배포 요금이 부과되지 않도록 하세요. 자세히 알아보기

Java

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

import com.google.cloud.automl.v1beta1.AnnotationPayload;
import com.google.cloud.automl.v1beta1.ExamplePayload;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.PredictRequest;
import com.google.cloud.automl.v1beta1.PredictResponse;
import com.google.cloud.automl.v1beta1.PredictionServiceClient;
import com.google.cloud.automl.v1beta1.Row;
import com.google.cloud.automl.v1beta1.TablesAnnotation;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class TablesPredict {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    // Values should match the input expected by your model.
    List<Value> values = new ArrayList<>();
    // values.add(Value.newBuilder().setBoolValue(true).build());
    // values.add(Value.newBuilder().setNumberValue(10).build());
    // values.add(Value.newBuilder().setStringValue("YOUR_STRING").build());
    predict(projectId, modelId, values);
  }

  static void predict(String projectId, String modelId, List<Value> values) throws IOException {
    // 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 client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);
      Row row = Row.newBuilder().addAllValues(values).build();
      ExamplePayload payload = ExamplePayload.newBuilder().setRow(row).build();

      // Feature importance gives you visibility into how the features in a specific prediction
      // request informed the resulting prediction. For more info, see:
      // https://cloud.google.com/automl-tables/docs/features#local
      PredictRequest request =
          PredictRequest.newBuilder()
              .setName(name.toString())
              .setPayload(payload)
              .putParams("feature_importance", "true")
              .build();

      PredictResponse response = client.predict(request);

      System.out.println("Prediction results:");
      for (AnnotationPayload annotationPayload : response.getPayloadList()) {
        TablesAnnotation tablesAnnotation = annotationPayload.getTables();
        System.out.format(
            "Classification label: %s%n", tablesAnnotation.getValue().getStringValue());
        System.out.format("Classification score: %.3f%n", tablesAnnotation.getScore());
        // Get features of top importance
        tablesAnnotation
            .getTablesModelColumnInfoList()
            .forEach(
                info ->
                    System.out.format(
                        "\tColumn: %s - Importance: %.2f%n",
                        info.getColumnDisplayName(), info.getFeatureImportance()));
      }
    }
  }
}

Node.js

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기


/**
 * Demonstrates using the AutoML client to request prediction from
 * automl tables using csv.
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
// const computeRegion = '[REGION_NAME]' e.g., "us-central1";
// const modelId = '[MODEL_ID]' e.g., "TBL000000000000";
// const inputs = [{ numberValue: 1 }, { stringValue: 'value' }, { stringValue: 'value2' } ...]

const automl = require('@google-cloud/automl');

// Create client for prediction service.
const automlClient = new automl.v1beta1.PredictionServiceClient();

// Get the full path of the model.
const modelFullId = automlClient.modelPath(projectId, computeRegion, modelId);

async function predict() {
  // Set the payload by giving the row values.
  const payload = {
    row: {
      values: inputs,
    },
  };

  // Params is additional domain-specific parameters.
  // Currently there is no additional parameters supported.
  const [response] = await automlClient.predict({
    name: modelFullId,
    payload: payload,
    params: {feature_importance: true},
  });
  console.log('Prediction results:');

  for (const result of response.payload) {
    console.log(`Predicted class name: ${result.displayName}`);
    console.log(`Predicted class score: ${result.tables.score}`);

    // Get features of top importance
    const featureList = result.tables.tablesModelColumnInfo.map(
      columnInfo => {
        return {
          importance: columnInfo.featureImportance,
          displayName: columnInfo.columnDisplayName,
        };
      }
    );
    // Sort features by their importance, highest importance first
    featureList.sort((a, b) => {
      return b.importance - a.importance;
    });

    // Print top 10 important features
    console.log('Features of top importance');
    console.log(featureList.slice(0, 10));
  }
}
predict();

Python

AutoML Tables용 클라이언트 라이브러리에는 AutoML Tables API로 간소화할 수 있는 추가 Python 메서드가 포함됩니다. 이러한 메서드는 데이터세트와 모델을 id가 아닌 이름으로 지칭합니다. 데이터 세트와 모델 이름은 고유해야 합니다. 자세한 내용은 클라이언트 참조를 확인하세요.

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

# TODO(developer): Uncomment and set the following variables
# project_id = 'PROJECT_ID_HERE'
# compute_region = 'COMPUTE_REGION_HERE'
# model_display_name = 'MODEL_DISPLAY_NAME_HERE'
# inputs = {'value': 3, ...}

from google.cloud import automl_v1beta1 as automl

client = automl.TablesClient(project=project_id, region=compute_region)

if feature_importance:
    response = client.predict(
        model_display_name=model_display_name,
        inputs=inputs,
        feature_importance=True,
    )
else:
    response = client.predict(model_display_name=model_display_name, inputs=inputs)

print("Prediction results:")
for result in response.payload:
    print(f"Predicted class name: {result.tables.value}")
    print(f"Predicted class score: {result.tables.score}")

    if feature_importance:
        # get features of top importance
        feat_list = [
            (column.feature_importance, column.column_display_name)
            for column in result.tables.tables_model_column_info
        ]
        feat_list.sort(reverse=True)
        if len(feat_list) < 10:
            feat_to_show = len(feat_list)
        else:
            feat_to_show = 10

        print("Features of top importance:")
        for feat in feat_list[:feat_to_show]:
            print(feat)

다음 단계