モデルの評価

モデルをトレーニングした後、AutoML Vision は TEST セットの項目を使用して、新しいモデルの品質と精度を評価します。

評価の概要

AutoML Vision には、モデルが全体的にどの程度適切に機能するかを示す評価指標のセットと、モデルが特定のラベルに対してどの程度適切に機能するかを示す各カテゴリラベルの評価指標が用意されています。

  • AuPRC: 適合率 / 再現率曲線の下の部分の面積で、「平均適合率」とも呼ばれます。通常は、0.5 から 1.0 の間です。値が高いほど、モデルの精度が高いことを示します。

  • 信頼しきい値曲線は、さまざまな信頼しきい値が適合率、再現率、真陽性率、および偽陽性率にどのように影響するかを示します。適合率と再現率の関係をご覧ください。

  • 混同行列: 画像ごとに単一のラベルがあるモデルにのみ存在します。トレーニング セット内の各ラベルについて、評価中にラベルが予測された回数の割合を表します。

    サンプル混同行列

    たとえば、ラベル 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 Vision は、最大 10 個のラベルの混同行列を作成します。10 個以上のラベルがある場合、行列には混同が最も多い 10 個のラベルが含まれます(誤った予測)。

このデータを使用して、モデルの準備状況を評価します。混同が多い、AUC スコアが低い、または適合率スコアと再現率スコアが低い場合は、モデルに追加のトレーニング データが必要であるか、ラベルに一貫性がないことを示している可能性があります。AUC スコアが非常に高く、適合率と再現率が完璧な場合は、データが単純すぎて適切に一般化できないことを示している可能性があります。

モデル評価の一覧表示

モデルをトレーニングしたら、そのモデルの評価指標を一覧表示できます。

ウェブ UI

  1. AutoML Translation UI を開き、左側のナビゲーション バーで電球のアイコンがある [モデル] をクリックし、使用可能なモデルを表示します。

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

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

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

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

    モデル評価ページ

REST

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

  • project-id: GCP プロジェクト ID
  • model-id: モデルを作成したときにレスポンスで返されたモデルの ID。この ID は、モデルの名前の最後の要素です。例:
    • モデル名: projects/project-id/locations/location-id/models/IOD4412217016962778756
    • モデル ID: IOD4412217016962778756
  • model-evaluation-id: モデル評価の ID 値。モデル評価 ID は、list モデル評価オペレーションから取得できます。

HTTP メソッドと URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models/MODEL_ID/modelEvaluations/MODEL_EVALUATION_ID

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models/MODEL_ID/modelEvaluations/MODEL_EVALUATION_ID"

PowerShell

次のコマンドを実行します。

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models/MODEL_ID/modelEvaluations/MODEL_EVALUATION_ID" | Select-Object -Expand Content

次のサンプルのような JSON レスポンスが返されます。わかりやすいように、オブジェクト検出に固有の主要フィールドを太字で示し、classificationEvaluationMetrics エントリは短縮版で示しています。

Go

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

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
}

Java

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。


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

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

/**
 * 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();

Python

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

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
        )
    )

その他の言語

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

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

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

モデル評価値の取得

評価 ID を使用して、特定のラベル(displayName)に対するモデル評価を取得することもできます。モデル評価 ID を取得するには、モデル評価の一覧表示に示されているモデル評価一覧表示関数を実行します。

ウェブ UI

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

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

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

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

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

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

    モデル評価ページ固有のラベル

REST

特定のラベルの評価指標のみを取得するには、レスポンスから上記のリクエストに /{MODEL_EVALUATION_ID} を追加します。

たとえば、list オペレーションから返された評価名の rose ラベル(displayName)のモデル評価 ID を検索できます。

  • "name": "projects/PROJECT_ID/locations/us-central1/models/MODEL_ID/modelEvaluations/858136867710915695"

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

  • project-id: GCP プロジェクト ID
  • model-id: モデルを作成したときにレスポンスで返されたモデルの ID。この ID は、モデルの名前の最後の要素です。例:
    • モデル名: projects/project-id/locations/location-id/models/IOD4412217016962778756
    • モデル ID: IOD4412217016962778756
  • model-evaluation-id: モデル評価の ID 値。モデル評価 ID は、list モデル評価オペレーションから取得できます。

HTTP メソッドと URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models/MODEL_ID/modelEvaluations/MODEL_EVALUATION_ID

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models/MODEL_ID/modelEvaluations/MODEL_EVALUATION_ID"

PowerShell

次のコマンドを実行します。

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models/MODEL_ID/modelEvaluations/MODEL_EVALUATION_ID" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

Go

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

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, "Classification model evaluation metrics: %v\n", evaluation.GetClassificationEvaluationMetrics())

	return nil
}

Java

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。


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

Node.js

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

/**
 * 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(
    `Classification model evaluation metrics: ${response.classificationEvaluationMetrics}`
  );
}

getModelEvaluation();

Python

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

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(
    "Classification model evaluation metrics: {}".format(
        response.classification_evaluation_metrics
    )
)

真陽性、偽陰性、偽陽性(UI のみ)

ユーザー インターフェースで、モデル パフォーマンスの特定のサンプルを確認できます。たとえば、TRAINING セットと VALIDATION のセットから真陽性(TP)偽陰性(FN)偽陽性(FP)のインスタンスを確認できます。

ウェブ UI

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

UI で TP、FN、FP ビューにアクセスするには、[評価] タブをクリックして特定のラベルを選択します。

これらの予測の傾向を表示すると、トレーニング セットを変更し、モデルのパフォーマンスを向上させることができます。

真陽性の画像は、トレーニング済みのモデルに提供された画像で、モデルはこの画像に正しいアノテーションを付けています。

真陽性の表示

偽陰性の画像も同様にトレーニング済みのモデルに提供されますが、モデルは指定されたラベルの画像に対して正しいアノテーションを付けていません。

偽陰性の表示

偽陽性の画像は、トレーニング済みのモデルに提供されていますが、モデルは、指定されたラベルに対して本来設定すべきでないアノテーションを付けています。

偽陽性の表示

このモデルでは、めったにない面白いケースを選択していますが、これらを参考に定義とラベルを調整すれば、モデルによるラベルの解釈の理解度を向上させることができるでしょう。たとえば、より厳密な定義を行うことで、バラの抽象画を「バラ」と認識するべきかどうかモデルに理解させることができます。

ラベル、トレーニング、評価のループを繰り返すことで、データに存在する別のあいまいさが表面化することがあります。

また、ユーザー インターフェースのこのビューでスコアしきい値を調整すると、表示されている TP、FN、FP の各画像にしきい値の変化が反映されます。

しきい値を更新した後の真陽性

モデルの反復

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

  • AutoML Vision では、モデルの「混同」の度合い、真のラベル、予測されたラベルによって、画像を並べ替えることができます。これらの画像に目を通し、適切にラベルが付けられていることを確認してください。
  • 低品質のラベルにさらに画像を追加することを検討してください。
  • さまざまなタイプの画像を追加しなければならない場合があります(たとえば、構図の拡大、解像度の増減、異なる視点など)。
  • 十分なトレーニング画像が存在しない場合は、ラベルを完全に削除することを検討してください。
  • マシンにはラベル名の意味は理解できません。つまり、ラベル名はマシンにとって単なるランダムな文字列にすぎません。「door」というラベルと「door_with_knob」という別のラベルがある場合、マシンにはそのラベルが付いた動画以外にニュアンスを把握する方法はありません。
  • 真陽性と真陰性のサンプルを追加してデータを強化してください。特に重要なサンプルは、意思決定の境界に近いものです(混同を招く可能性があるが、正しくラベル付けされているもの)。
  • 独自の TRAIN、TEST、VALIDATION の分割を指定してください。ツールは画像をランダムに割り当てますが、割り当てが重複に近い場合は TRAIN と VALIDATION の過学習につながり、TEST セットのパフォーマンスが低下する可能性があります。

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