モデルの評価

モデルをトレーニングした後、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)により、予測されたセンチメント値と実際のセンチメント値との間の差が測定されます。値が小さいほど、モデルの精度が高いことを示します。

  • 直線加重 Κ(カッパ)二次加重 K(カッパ)により、モデルによって割り当てられたセンチメント値が人間の評価者によって割り当てられた値とどの程度一致するかが測定されます。値が高いほど、モデルの精度が高いことを示します。

これらの指標を使用して、モデルの準備状況を評価します。適合率および再現率のスコアが低い場合、モデルのトレーニング データが不足しているか、アノテーションに一貫性がないことを意味します。適合率または再現率が 100% の場合、データが簡単すぎて、一般化できないことを意味します。モデルの評価に関するその他のヒントについては、初心者向けガイドをご覧ください。

品質水準に不満がある場合は、前のステップに戻って品質を向上させることができます。

  • 低品質のラベルにさらにドキュメントを追加することを検討してください。
  • さまざまなタイプのドキュメントを追加しなければならない場合があります。たとえば、より長いまたはより短いドキュメントや、さまざまな言い回しやスタイルが使用された複数の作成者によるドキュメントなどです。
  • ラベルをクリーンアップできます。
  • 十分なトレーニング ドキュメントが存在しない場合は、ラベルを完全に削除することを検討してください。

変更が完了したら、十分に高い品質水準に達するまで、モデルをトレーニングして評価します。

ウェブ UI

モデルの評価指標を確認するには、次のようにします。

  1. 左側のナビゲーション バーにある電球アイコンをクリックして、使用可能なモデルを表示します。

    別のプロジェクトのモデルを表示するには、タイトルバーの右上にあるプルダウン リストからプロジェクトを選択します。

  2. 評価するモデルの行をクリックします。

  3. 必要に応じて、タイトルバーのすぐ下にある [評価] タブをクリックします。

    モデルのトレーニングが完了している場合、AutoML Natural Language はその評価指標を表示します。

    評価ページ

  4. 特定のラベルの指標を表示するには、ページの下部にあるラベルのリストからラベル名を選択します。

コードサンプル

サンプルにより、モデル全体に対する評価が行われます。評価 ID を使用して、特定のラベル(displayName)に対する指標を得ることもできます。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: プロジェクト ID
  • location-id: リソースのロケーション。グローバル ロケーションの場合は us-central1、EU の場合は 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 Natural Language リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Natural Language リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Natural Language のリファレンス ドキュメントをご覧ください。