모델 평가

AutoML Natural Language는 모델을 학습한 후 테스트 세트의 문서를 사용하여 새 모델의 품질과 정확성을 평가합니다.

AutoML Natural Language는 모델이 전반적으로 성능이 어떠한지를 나타내는 종합적인 평가 측정항목과 모델이 해당 라벨에 대해 성능이 어떠한지를 나타내는 카테고리별 라벨 평가 측정항목을 제공합니다.

정밀도재현율은 모델이 정보를 얼마나 잘 포착하고 있는지와 정보를 얼마나 놓치고 있는지를 측정합니다. 정밀도는 특정 항목 또는 라벨로 식별된 전체 문서 중에서 실제로 해당 항목 또는 라벨로 지정되어야 했던 문서가 몇 개인지를 나타냅니다. 재현율은 특정 항목 또는 라벨로 식별되어야 했던 모든 문서 중에서 실제로 해당 항목 또는 라벨에 지정된 문서가 몇 개인지를 나타냅니다.

혼동 행렬은 이미지당 라벨이 하나인 모델에만 있으며, 각 라벨이 평가 중에 학습 세트에서 예측된 횟수의 백분율을 나타냅니다. 예를 들면 라벨 one은 라벨 one으로 분류된 문서에만 지정되는 것이 이상적이므로 완벽한 행렬의 모양은 다음과 같습니다.

100  0   0   0
 0  100  0   0
 0   0  100  0
 0   0   0  100

위의 예시에서 문서는 one으로 분류되었지만 모델이 two로 예측했다면 첫 행은 다음과 같이 표시됩니다.

99  1  0  0

AutoML Natural Language는 최대 10개의 라벨에 대한 혼동 행렬을 생성합니다. 라벨이 10개를 초과하는 경우 행렬에는 혼동이 가장 많은(예측이 부정확한) 라벨 10개가 포함됩니다.

감정 모델:

  • 평균 절대 오차(MAE)평균 제곱 오차(MSE)는 예측 감정 값과 실제 감정 값 사이의 차이를 측정합니다. 값이 작을수록 모델이 정확하다는 의미입니다.

  • 선형 가중치 카파2차 가중치 카파는 모델에서 지정된 감정 값이 수동 평가자가 지정한 감정 값과 얼마나 일치하는지를 결정합니다. 값이 클수록 모델이 정확한 것입니다.

이러한 측정항목을 사용하여 모델의 준비 상태를 평가합니다. 정밀도와 재현율 점수가 낮다면 모델에 학습 데이터가 더 많이 필요하거나 주석이 일관되지 않은 경우일 수 있습니다. 정밀도와 재현율이 완벽하다면 데이터가 너무 쉬워서 일반화가 잘 되지 않는 경우일 수 있습니다. 모델 평가에 대한 추가 팁은 초보자용 가이드를 참조하세요.

품질 수준이 만족스럽지 않은 경우 이전 단계로 돌아가서 다음과 같이 품질을 높일 수 있습니다.

  • 품질이 낮은 라벨에 문서를 더 추가해 봅니다.
  • 다른 유형의 문서를 추가해야 할 수도 있습니다. 예를 들어 더 길거나 더 짧은 문서 또는 문구나 스타일이 다른 작성자가 만든 문서를 추가해야 합니다.
  • 라벨을 삭제할 수 있습니다.
  • 학습 문서가 부족하다면 라벨을 모두 삭제해 봅니다.

변경을 마친 후 품질 수준이 충분히 향상될 때까지 모델을 학습하고 평가합니다.

웹 UI

모델의 평가 측정항목을 검토하려면 다음 안내를 따르세요.

  1. 왼쪽 탐색 메뉴에서 전구 아이콘을 클릭하여 사용 가능한 모델을 표시합니다.

    다른 프로젝트의 모델을 보려면 제목 표시줄 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

  2. 평가하려는 모델의 행을 클릭합니다.

  3. 필요하면 제목 표시줄 아래에 있는 평가 탭을 클릭합니다.

    모델에 대한 학습이 끝나면 AutoML Natural Language는 평가 측정항목을 표시합니다.

    평가 페이지

  4. 특정 라벨의 측정항목을 보려면 페이지 하단에 있는 라벨 목록에서 라벨 이름을 선택합니다.

코드 샘플

샘플은 모델을 종합적으로 평가합니다. 평가 ID를 사용하여 특정 라벨(displayName)의 측정항목을 가져올 수도 있습니다.

REST

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

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu
  • model-id: 모델 ID

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1/projects/project-id/locations/location-id/models/model-id/modelEvaluations

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

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

{
  "modelEvaluation": [
    {
      "name": "projects/434039606874/locations/us-central1/models/7537307368641647584/modelEvaluations/9009741181387603448",
      "annotationSpecId": "17040929661974749",
      "classificationMetrics": {
        "auPrc": 0.99772006,
        "baseAuPrc": 0.21706384,
        "evaluatedExamplesCount": 377,
        "confidenceMetricsEntry": [
          {
            "recall": 1,
            "precision": -1.3877788e-17,
            "f1Score": -2.7755576e-17,
            "recallAt1": 0.9761273,
            "precisionAt1": 0.9761273,
            "f1ScoreAt1": 0.9761273
          },
          {
            "confidenceThreshold": 0.05,
            "recall": 0.997,
            "precision": 0.867,
            "f1Score": 0.92746675,
            "recallAt1": 0.9761273,
            "precisionAt1": 0.9761273,
            "f1ScoreAt1": 0.9761273
          },
          {
            "confidenceThreshold": 0.1,
            "recall": 0.995,
            "precision": 0.905,
            "f1Score": 0.9478684,
            "recallAt1": 0.9761273,
            "precisionAt1": 0.9761273,
            "f1ScoreAt1": 0.9761273
          },
          {
            "confidenceThreshold": 0.15,
            "recall": 0.992,
            "precision": 0.932,
            "f1Score": 0.96106446,
            "recallAt1": 0.9761273,
            "precisionAt1": 0.9761273,
            "f1ScoreAt1": 0.9761273
          },
          {
            "confidenceThreshold": 0.2,
            "recall": 0.989,
            "precision": 0.951,
            "f1Score": 0.96962786,
            "recallAt1": 0.9761273,
            "precisionAt1": 0.9761273,
            "f1ScoreAt1": 0.9761273
          },
          {
            "confidenceThreshold": 0.25,
            "recall": 0.987,
            "precision": 0.957,
            "f1Score": 0.9717685,
            "recallAt1": 0.9761273,
            "precisionAt1": 0.9761273,
            "f1ScoreAt1": 0.9761273
          },
        ...
        ],
      },
      "createTime": "2018-04-30T23:06:14.746840Z"
    },
    {
      "name": "projects/434039606874/locations/us-central1/models/7537307368641647584/modelEvaluations/9009741181387603671",
      "annotationSpecId": "1258823357545045636",
      "classificationMetrics": {
        "auPrc": 0.9972302,
        "baseAuPrc": 0.1883289,
      ...
      },
      "createTime": "2018-04-30T23:06:14.649260Z"
    }
  ]
}

Python

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

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

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)

print("List of model evaluations:")
for evaluation in client.list_model_evaluations(parent=model_full_id, filter=""):
    print(f"Model evaluation name: {evaluation.name}")
    print(f"Model annotation spec id: {evaluation.annotation_spec_id}")
    print(f"Create Time: {evaluation.create_time}")
    print(f"Evaluation example count: {evaluation.evaluated_example_count}")
    print(
        "Classification model evaluation metrics: {}".format(
            evaluation.classification_evaluation_metrics
        )
    )

Java

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

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


import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ListModelEvaluationsRequest;
import com.google.cloud.automl.v1.ModelEvaluation;
import com.google.cloud.automl.v1.ModelName;
import java.io.IOException;

class ListModelEvaluations {

  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";
    listModelEvaluations(projectId, modelId);
  }

  // List model evaluations
  static void listModelEvaluations(String projectId, String modelId) 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 (AutoMlClient client = AutoMlClient.create()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
      ListModelEvaluationsRequest modelEvaluationsrequest =
          ListModelEvaluationsRequest.newBuilder().setParent(modelFullId.toString()).build();

      // List all the model evaluations in the model by applying filter.
      System.out.println("List of model evaluations:");
      for (ModelEvaluation modelEvaluation :
          client.listModelEvaluations(modelEvaluationsrequest).iterateAll()) {

        System.out.format("Model Evaluation Name: %s\n", modelEvaluation.getName());
        System.out.format("Model Annotation Spec Id: %s", modelEvaluation.getAnnotationSpecId());
        System.out.println("Create Time:");
        System.out.format("\tseconds: %s\n", modelEvaluation.getCreateTime().getSeconds());
        System.out.format("\tnanos: %s", modelEvaluation.getCreateTime().getNanos() / 1e9);
        System.out.format(
            "Evalution Example Count: %d\n", modelEvaluation.getEvaluatedExampleCount());
        System.out.format(
            "Classification Model Evaluation Metrics: %s\n",
            modelEvaluation.getClassificationEvaluationMetrics());
      }
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function listModelEvaluations() {
  // Construct request
  const request = {
    parent: client.modelPath(projectId, location, modelId),
    filter: '',
  };

  const [response] = await client.listModelEvaluations(request);

  console.log('List of model evaluations:');
  for (const evaluation of response) {
    console.log(`Model evaluation name: ${evaluation.name}`);
    console.log(`Model annotation spec id: ${evaluation.annotationSpecId}`);
    console.log(`Model display name: ${evaluation.displayName}`);
    console.log('Model create time');
    console.log(`\tseconds ${evaluation.createTime.seconds}`);
    console.log(`\tnanos ${evaluation.createTime.nanos / 1e9}`);
    console.log(
      `Evaluation example count: ${evaluation.evaluatedExampleCount}`
    );
    console.log(
      `Classification model evaluation metrics: ${evaluation.classificationEvaluationMetrics}`
    );
  }
}

listModelEvaluations();

Go

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

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

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
	"google.golang.org/api/iterator"
)

// listModelEvaluation lists existing model evaluations.
func listModelEvaluations(w io.Writer, projectID string, location string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TRL123456789..."

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.ListModelEvaluationsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

	it := client.ListModelEvaluations(ctx, req)

	// Iterate over all results
	for {
		evaluation, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListModelEvaluations.Next: %w", err)
		}

		fmt.Fprintf(w, "Model evaluation name: %v\n", evaluation.GetName())
		fmt.Fprintf(w, "Model annotation spec id: %v\n", evaluation.GetAnnotationSpecId())
		fmt.Fprintf(w, "Create Time:\n")
		fmt.Fprintf(w, "\tseconds: %v\n", evaluation.GetCreateTime().GetSeconds())
		fmt.Fprintf(w, "\tnanos: %v\n", evaluation.GetCreateTime().GetNanos())
		fmt.Fprintf(w, "Evaluation example count: %v\n", evaluation.GetEvaluatedExampleCount())
		fmt.Fprintf(w, "Classification model evaluation metrics: %v\n", evaluation.GetClassificationEvaluationMetrics())
	}

	return nil
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.