모델 평가

AutoML Translation은 모델을 학습한 후 테스트 세트의 항목을 사용하여 새 모델의 품질과 정확성을 평가합니다. BLEU(Bilingual Evaluation Understudy) 점수로 모델 품질을 표현합니다. 이 점수는 후보 텍스트가 참조 텍스트와 얼마나 비슷한지를 나타내며, 값이 1에 가까울수록 더 비슷합니다.

BLEU 점수는 모델 품질에 관한 전반적인 평가를 제공합니다. 모델 예측과 함께 테스트 세트를 내보내 특정 데이터 항목의 모델 출력을 평가할 수도 있습니다. 내보낸 데이터에는 원본 데이터 세트의 참조 텍스트와 모델의 후보 텍스트가 모두 포함되어 있습니다.

이 데이터를 사용하여 모델의 준비 상태를 평가합니다. 품질 수준이 만족스럽지 않은 경우 학습 문장 쌍의 개수를 늘리고 유형을 다변화해 보세요. 문장 쌍을 더 추가해 볼 수 있습니다. 제목 표시줄에서 파일 추가 링크를 클릭합니다. 파일을 추가했으면 학습 페이지에서 새 모델 학습 버튼을 클릭하여 새 모델을 학습합니다. 품질 수준이 충분히 향상될 때까지 이 과정을 반복합니다.

모델 평가 가져오기

웹 UI

  1. AutoML Translation 콘솔을 열고 왼쪽 탐색 메뉴에서 모델 옆의 전구 아이콘을 클릭합니다. 사용 가능한 모델이 표시됩니다. 각 모델에는 학습한 모델의 데이터 세트, 출발어, 도착어, 모델을 학습하는 데 사용된 기본 모델 정보가 포함됩니다.

    하나의 모델이 나열된 모델 탭

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

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

    예측 탭이 열립니다.

    여기에서 모델을 테스트하고 커스텀 모델과 학습에 사용한 기본 모델의 결과를 볼 수 있습니다.

  3. 제목 표시줄 바로 아래에 있는 학습 탭을 클릭합니다.

    모델 학습이 완료되면 AutoML Translation은 평가 측정항목을 표시합니다.

    모델 평가 결과가 표시된 my_dataset의 학습 탭

REST

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

  • model-name: 모델의 전체 이름입니다. 프로젝트 이름과 위치가 포함됩니다. 모델 이름의 예를 들면 projects/project-id/locations/us-central1/models/model-id입니다.
  • project-id: Google Cloud Platform 프로젝트 ID

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1/model-name/modelEvaluations

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

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

{
  "modelEvaluation": [
    {
      "name": "projects/project-number/locations/us-central1/models/model-id/modelEvaluations/evaluation-id",
      "createTime": "2019-10-02T00:20:30.972732Z",
      "evaluatedExampleCount": 872,
      "translationEvaluationMetrics": {
        "bleuScore": 48.355409502983093,
        "baseBleuScore": 39.071375131607056
      }
    }
  ]
}

Go

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

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

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// getModelEvaluation gets a model evaluation.
func getModelEvaluation(w io.Writer, projectID string, location string, modelID string, modelEvaluationID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TRL123456789..."
	// modelEvaluationID := "123456789..."

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

	req := &automlpb.GetModelEvaluationRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s/modelEvaluations/%s", projectID, location, modelID, modelEvaluationID),
	}

	evaluation, err := client.GetModelEvaluation(ctx, req)
	if err != nil {
		return fmt.Errorf("GetModelEvaluation: %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, "Translation model evaluation metrics: %v\n", evaluation.GetTranslationEvaluationMetrics())

	return nil
}

Java

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

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


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

class GetModelEvaluation {

  static void getModelEvaluation() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String modelEvaluationId = "YOUR_MODEL_EVALUATION_ID";
    getModelEvaluation(projectId, modelId, modelEvaluationId);
  }

  // Get a model evaluation
  static void getModelEvaluation(String projectId, String modelId, String modelEvaluationId)
      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 evaluation.
      ModelEvaluationName modelEvaluationFullId =
          ModelEvaluationName.of(projectId, "us-central1", modelId, modelEvaluationId);

      // Get complete detail of the model evaluation.
      ModelEvaluation modelEvaluation = client.getModelEvaluation(modelEvaluationFullId);

      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(
          "Translate Model Evaluation Metrics: %s\n",
          modelEvaluation.getTranslationEvaluationMetrics());
    }
  }
}

Node.js

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

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

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

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

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

async function getModelEvaluation() {
  // Construct request
  const request = {
    name: client.modelEvaluationPath(
      projectId,
      location,
      modelId,
      modelEvaluationId
    ),
  };

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

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

getModelEvaluation();

Python

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

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

from google.cloud import automl

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

client = automl.AutoMlClient()
# Get the full path of the model evaluation.
model_path = client.model_path(project_id, "us-central1", model_id)
model_evaluation_full_id = f"{model_path}/modelEvaluations/{model_evaluation_id}"

# Get complete detail of the model evaluation.
response = client.get_model_evaluation(name=model_evaluation_full_id)

print(f"Model evaluation name: {response.name}")
print(f"Model annotation spec id: {response.annotation_spec_id}")
print(f"Create Time: {response.create_time}")
print(f"Evaluation example count: {response.evaluated_example_count}")
print(
    "Translation model evaluation metrics: {}".format(
        response.translation_evaluation_metrics
    )
)

추가 언어

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

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

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML 번역 참조 문서를 참조하세요.

모델 예측과 함께 테스트 데이터 내보내기

AutoML Translation은 모델을 학습한 후 테스트 세트의 항목을 사용하여 새 모델의 품질과 정확성을 평가합니다. AutoML Translation 콘솔에서 TEST 세트를 내보내 모델 출력이 원래 데이터 세트의 참조 텍스트와 어떻게 비교되는지 확인할 수 있습니다. AutoML Translation은 TSV 파일을 Google Cloud Storage 버킷에 저장하며, 각 행의 형식은 다음과 같습니다.

Source sentence Reference translation Model candidate translation

웹 UI

  1. AutoML Translation 콘솔을 열고 왼쪽 탐색 메뉴의 '모델' 왼쪽에 있는 전구 아이콘을 클릭하면 사용 가능한 모델이 표시됩니다.

    하나의 모델이 나열된 모델 탭

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

  2. 모델을 선택합니다.

  3. 제목 표시줄에서 데이터 내보내기 버튼을 클릭합니다.

  4. 내보낸 .tsv 파일을 저장할 Google Cloud Storage 버킷의 전체 경로를 입력합니다.

    현재 프로젝트와 연결된 버킷을 사용해야 합니다.

  5. 테스트 데이터를 내보낼 모델을 선택합니다.

    모델 예측으로 세트 테스트 드롭다운 목록에 동일한 입력 데이터 세트를 사용하여 학습한 모델이 나열됩니다.

  6. 내보내기를 클릭합니다.

    AutoML Translation은 지정된 Google Cloud Storage 버킷에 model-name_evaluated.tsv라는 파일을 작성합니다.

새 테스트 세트를 사용하여 모델 평가 및 비교

AutoML Translation 콘솔에서 새 테스트 데이터 세트를 사용하여 기존 모델을 다시 평가할 수 있습니다. 단일 평가에서 최대 5개의 서로 다른 모델을 포함한 후 결과를 비교할 수 있습니다.

테스트 데이터를 Cloud Storage에 탭으로 구분된 값(.tsv) 파일 또는 Translation Memory eXchange(.tmx) 파일로 업로드합니다.

AutoML Translation은 테스트 세트를 기준으로 모델을 평가한 다음 평가 점수를 생성합니다. 선택적으로 각 모델의 결과를 Cloud Storage 버킷에 .tsv 파일로 저장할 수 있습니다. 각 행의 형식은 다음과 같습니다.

Source sentence tab Model candidate translation tab Reference translation

웹 UI

  1. AutoML Translation 콘솔을 열고 왼쪽 탐색창에서 모델을 클릭하여 사용 가능한 모델을 표시합니다.

    하나의 모델이 나열된 모델 탭

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

  2. 평가하려는 모델 중 하나를 선택합니다.

  3. 제목 표시줄 바로 아래에 있는 평가 탭을 클릭합니다.

    my_dataset 데이터 세트의 평가 탭

  4. 평가 탭에서 새 평가를 클릭합니다.

    my_model 모델의 새 평가 탭

    • 평가하고 비교할 모델을 선택합니다. 현재 모델을 선택해야 하며 기본적으로 Google NMT가 선택되어 있으며 선택을 해제할 수 있습니다.
    • 테스트 세트 이름의 이름을 지정하여 다른 평가와 구별한 다음 Cloud Storage에서 새 테스트 세트를 선택합니다.
    • 테스트 세트를 기반으로 하는 예측을 내보내려면 결과가 저장될 Cloud Storage 버킷을 지정합니다(문자당 표준 요율의 가격이 적용됩니다.).
  5. 완료를 클릭합니다.

    AutoML Translation은 평가가 완료된 후 콘솔의 테이블 형식으로 평가 점수를 표시합니다. 한 번에 하나의 평가만 실행할 수 있습니다. 예측 결과를 저장할 버킷을 지정한 경우 AutoML Translation은 model-name_test-set-name.tsv이라는 파일을 버킷에 작성합니다.

BLEU 점수 이해

BLEU(BiLingual Evaluation Understudy)는 기계 번역된 텍스트를 자동으로 평가하는 측정항목입니다. BLEU 점수는 기계 번역된 텍스트와 고품질 참조 번역 세트의 유사성을 측정하는 0과 1 사이의 숫자입니다. 값이 0이면 기계 번역된 출력이 참조 번역과 겹치는 부분이 없는 것을 의미하고(저품질), 1이면 참조 번역과 완벽하게 겹치는 것을 의미합니다(고품질).

BLEU 점수는 사람이 번역 품질을 판단한 결과와 상관관계가 높은 것으로 확인되었습니다. 참고로, 번역사도 1.0의 완벽한 점수를 얻지는 못합니다.

AutoML은 BLEU 점수를 0과 1 사이의 십진수가 아닌 백분율로 나타냅니다.

해석

서로 다른 말뭉치 및 언어 간에는 BLEU 점수를 비교하지 않는 것이 좋습니다. 말뭉치는 동일하지만 참조 번역 수가 다른 BLEU 점수를 비교하는 경우에도 잘못된 해석으로 이어질 수 있습니다.

다음 BLEU 점수 해석(숫자가 아닌 백분율로 표시)을 대략적인 지침으로 활용하면 도움이 될 수 있습니다.

BLEU 점수 해석
10점 미만 거의 의미 없음
10~19점 핵심을 파악하기 어려움
20~29점 요점은 명확하지만 많은 문법적 오류가 있음
30~40점 이해할 수 있는 양호한 번역
40~50점 고품질 번역
50~60점 매우 우수한 품질의 적절하고 유창한 번역
60점 초과 대체적으로 사람보다 우수한 품질

다음과 같은 색상 그라디언트를 BLEU 점수 해석의 일반 척도로 사용할 수 있습니다.

척도의 일반 해석 가능성

수학적 세부정보

수학적으로 BLEU 점수는 다음과 같이 정의됩니다.

$$ \text{BLEU} = \underbrace{\vphantom{\prod_i^4}\min\Big(1, \exp\big(1-\frac{\text{reference-length}} {\text{output-length}}\big)\Big)}_{\text{brevity penalty}} \underbrace{\Big(\prod_{i=1}^{4} precision_i\Big)^{1/4}}_{\text{n-gram overlap}} $$

\[ precision_i = \dfrac{\sum_{\text{snt}\in\text{Cand-Corpus}}\sum_{i\in\text{snt}}\min(m^i_{cand}, m^i_{ref})} {w_t^i = \sum_{\text{snt'}\in\text{Cand-Corpus}}\sum_{i'\in\text{snt'}} m^{i'}_{cand}} \]

각 항목의 의미는 다음과 같습니다.

  • \(m_{cand}^i\hphantom{xi}\)은 참조 번역에 일치하는 후보 번역의 I-그램 수입니다.
  • \(m_{ref}^i\hphantom{xxx}\)은 참조 번역의 I-그램 수입니다.
  • \(w_t^i\hphantom{m_{max}}\)은 후보 번역의 총 I-그램 수입니다.

수식은 축약 패널티(Brevity Penalty)와 N-그램 중복(N-gram Overlap)이라는 두 부분으로 구성됩니다.

  • 축약 페널티
    축약 페널티는 지수 감소를 근거로, 의미가 가장 가까운 참조 길이에 비해 지나치게 짧게 생성된 번역에 페널티를 적용합니다. 이 페널티는 BLEU 점수에 재현율 조건이 없다는 단점을 보완합니다.

  • N-그램 중복
    N-그램 중복은 참조 번역에서 유니그램, 바이그램, 트라이그램, 포그램(i=1,...,4)이 그에 해당하는 N-그램과 얼마나 일치하는지 측정합니다. 이 조건은 정밀도 측정항목의 역할을 합니다. 유니그램은 적합성을 나타내며, 더 긴 N-그램은 번역의 유창성을 나타냅니다. 과잉 계산을 방지하기 위해 참조에서 발생하는 최대 N-그램 수(\(m_{ref}^n\))에 맞게 N-그램 수를 자릅니다.

\(precision_1\) 계산

다음 참조 문장과 후보 번역을 고려하세요.

참조 : the cat is on the mat
후보 : the the the cat mat

첫 번째 단계에서는 참조 문장과 후보 문장에서 각 유니그램 항목 수를 계산합니다. BLEU 측정항목은 대소문자를 구분합니다.

유니그램 \(m_{cand}^i\hphantom{xi}\) \(m_{ref}^i\hphantom{xxx}\) \(\min(m^i_{cand}, m^i_{ref})\)
the 3 2 2
cat 1 1 1
is 0 1 0
on 0 1 0
mat 1 1 1

후보 문장의 총 유니그램 수(\(w_t^1\))는 5이므로 \(precision_1\) = (2 + 1 + 1)/5 = 0.8입니다.

BLEU 점수 계산

참조:     The NASA Opportunity rover is battling a massive dust storm on Mars .
후보 1: The Opportunity rover is combating a big sandstorm on Mars .
후보 2: A NASA rover is fighting a massive storm on Mars .

위의 예시는 하나의 참조 번역과 2개의 후보 번역으로 구성됩니다. 위에 설명한 대로 BLEU 점수를 계산하기 전에 문장을 토큰화합니다. 예를 들어 마침표는 별도의 토큰으로 계산됩니다.

번역별 BLEU 점수를 계산하기 위해 다음 통계를 계산합니다.

  • N-그램 정밀도
    다음 표에는 두 후보 문장의 N-그램 정밀도가 포함되어 있습니다.
  • 축약 페널티
    후보 1과 후보 2 문장은 모두 11개의 토큰으로 구성되므로 두 문장의 축약 페널티는 동일합니다.
  • BLEU 점수
    0보다 큰 BLEU 점수를 얻으려면 하나 이상의 상응하는 포그램이 필요합니다. 후보 번역 1에는 대응하는 포그램이 없으므로 BLEU 점수가 0입니다.
측정항목 후보 1 후보 2
\(precision_1\)(1그램) 8/11 9/11
\(precision_2\)(2그램) 4/10 5/10
\(precision_3\)(3그램) 2/9 2/9
\(precision_4\)(4그램) 0/8 1/8
축약 패널티 0.83 0.83
BLEU 점수 0.0 0.27

속성

  • BLEU: 말뭉치 기반 측정항목
    BLEU 측정항목은 개별 문장을 평가하는 데 사용될 경우 올바르게 이행되지 않습니다. 예를 들어 예시의 두 문장은 대부분의 의미를 반영하지만 BLEU 점수가 매우 낮습니다. 개별 문장의 N-그램 통계가 유의미하지 않고 BLEU는 기본적으로 말뭉치 기반 측정항목이기 때문입니다. 즉, 점수를 계산할 때 전체 말뭉치에 대한 통계가 누적됩니다. 위에 정의된 BLEU 측정항목을 개별 문장에 관해 인수 분해할 수 없습니다.

  • 내용어와 기능어 간 구분 없음
    BLEU 측정항목은 내용어와 기능어를 구분하지 않습니다. 즉, 'a'와 같은 기능어가 누락되면 이름 'NASA'를 'ESA'로 잘못 입력된 경우와 동일한 페널티가 적용됩니다.

  • 문장의 의미와 문법이 잘 파악되지 않음
    'not'과 같은 한 단어가 누락되는 경우 문장의 긍정, 부정이 바뀔 수 있습니다. n≤4인 N-그램만 고려할 경우 간격이 먼 호응 단어는 무시되므로 BLEU에서 문법적 오류가 있는 문장에 작은 페널티만 부과하는 경우가 종종 있습니다.

  • 정규화 및 토큰화
    BLEU 점수를 계산하기 전에 참조 번역과 후보 번역이 모두 정규화되고 토큰화됩니다. 정규화 및 토큰화 단계의 선택은 최종 BLEU 점수에 큰 영향을 줍니다.