AutoML-Modelle zur Textklassifizierung bewerten und iterieren

Auf dieser Seite erfahren Sie, wie Sie Ihre AutoML-Modelle zur Textklassifizierung bewerten, um Ihr Modell iterieren zu können.

Vertex AI bietet Messwerte für die Modellbewertung, damit Sie die Leistung Ihrer Modelle bewerten können, z. B. die Precision- und Recall-Messwerte. Vertex AI berechnet Bewertungsmesswerte mithilfe des Test-Datasets.

Verwendung von Modellbewertungsmesswerten

Modellbewertungsmesswerte liefern quantitative Messungen der Leistung Ihres Modells im Test-Dataset. Wie diese Messwerte interpretiert und verwendet werden sollten, hängt von Ihren geschäftlichen Anforderungen und dem Problem ab, für dessen Lösung das Modell trainiert wurde. Sie haben z. B. eine geringere Toleranz für falsch positive Ergebnisse als für falsch negative, oder andersherum. Diese Fragen haben Einfluss darauf, welche Messwerte für Sie besonders wichtig sind.

Weitere Informationen dazu, wie Sie Ihr Modell iterieren, um die Leistung zu verbessern, finden Sie unter Modell iterieren.

Von Vertex AI zurückgegebene Bewertungsmesswerte

Vertex AI gibt verschiedene Bewertungsmesswerte zurück, z. B. die Precision, der Recall und die Konfidenzgrenzwerte. Die von Vertex AI zurückgegebenen Messwerte hängen vom Ziel des Modells ab. Vertex AI beispielsweise unterschiedliche Bewertungsmesswerte für ein Bildklassifizierungsmodell im Vergleich zu einem Bildobjekterkennungsmodell.

Eine Schemadatei, die von einem Cloud Storage-Speicherort heruntergeladen werden kann, bestimmt, welche Bewertungsmesswerte Vertex AI für jedes Ziel bereitstellt. Die folgenden Tabs enthalten Links zu den Schemadateien und beschreiben die Bewertungsmesswerte für jedes Modellziel.

Sie können Schemadateien unter dem folgenden Cloud Storage-Speicherort ansehen und herunterladen:
gs://google-cloud-aiplatform/schema/modelevaluation/

  • AuPRC: Der Bereich unter der Precision-/Recall-Kurve (Area Under the Precision/Recall Curve, AuPRC), auch als durchschnittliche Precision bezeichnet. Dieser Wert reicht von null bis eins, wobei ein höherer Wert auf ein Modell von höherer Qualität verweist.
  • Logarithmischer Verlust: Die Kreuzentropie zwischen den Modellvorhersagen und den Zielwerten. Dieser Wert reicht von null bis unendlich, wobei ein niedrigerer Wert auf ein Modell von höherer Qualität hinweist.
  • Konfidenzgrenzwert: Ein Konfidenzwert, der bestimmt, welche Vorhersagen zurückgegeben werden. Ein Modell gibt Vorhersagen mit diesem Wert oder höher zurück. Ein höherer Konfidenzgrenzwert erhöht die Precision, verringert aber den Recall. Vertex AI gibt Konfidenzmesswerte mit unterschiedlichen Grenzwerten zurück, um festzustellen, wie sich der Grenzwert auf die Precision und den Recall auswirkt.
  • Recall: Der Anteil an Vorhersagen mit dieser Klasse, die das Modell korrekt vorhergesagt hat. Wird als Rate richtig positiver Ergebnisse bezeichnet.
  • Rückruf bei 1: Die Trefferquote unter alleiniger Berücksichtigung des Labels, das für jedes Beispiel den höchsten Vorhersagewert hat, der nicht unter dem Konfidenzwert liegt.
  • Präzision: Der Anteil an Klassifizierungsvorhersagen des Modells, die richtig waren.
  • Genauigkeit bei 1: Die Genauigkeit, wenn nur das Label mit dem höchsten Vorhersagewert und nicht der Konfidenzwert für jedes Beispiel berücksichtigt wird.
  • F1-Wert: der harmonische Mittelwert von Precision und Recall. F1 ist ein nützlicher Messwert, wenn Sie ein Gleichgewicht zwischen Precision und Recall anstreben und die Klassenverteilung ungleichmäßig ist
  • F1-Wert bei 1: Der harmonische Mittelwert von Trefferquote bei 1 und Genauigkeit bei 1.
  • Wahrheitsmatrix: Eine Wahrheitsmatrix gibt an, wie oft ein Modell ein Ergebnis korrekt vorhergesagt hat. Bei falsch vorhergesagten Ergebnissen zeigt die Matrix, was das Modell stattdessen vorhergesagt hat. Die Wahrheitsmatrix hilft Ihnen zu verstehen, wo Ihr Modell zwei Ergebnisse „vermischt“.

Bewertungsmesswerte abrufen

Sie können eine ganze Reihe von zusammengefassten Modellbewertungsmesswerten und, für einige Ziele, Bewertungsmesswerte für eine bestimmte Klasse oder ein bestimmtes Label abrufen. Bewertungsmesswerte für eine bestimmte Klasse oder ein bestimmtes Label werden auch als ein Bewertungssegment bezeichnet. Im Folgenden wird beschrieben, wie Sie mit der Google Cloud Console oder der API zusammengefasste Bewertungsmesswerte und Bewertungssegmente abrufen können.

Google Cloud Console

  1. Rufen Sie in der Google Cloud Console im Abschnitt "Vertex AI" die Seite Model Registry auf.

    Zur Seite Model Registry

  2. Wählen Sie im Drop-down-Menü Region die Region aus, in der sich Ihr Modell befindet.

  3. Klicken Sie in der Liste der Modelle auf Ihr Modell, um den Tab Bewerten des Modells zu öffnen.

    Auf dem Tab Bewerten werden die zusammengefassten Bewertungsmesswerte des Modells angezeigt, zum Beispiel die durchschnittliche Precision und den Recall.

    Wenn das Modellziel Bewertungssegmente enthält, wird in der Console eine Liste mit Labels angezeigt. Sie können auf ein Label klicken, um Bewertungsmesswerte für dieses Label anzusehen, wie im folgenden Beispiel gezeigt:

    Labelauswahl in der Console

API

API-Anfragen zum Abrufen von Bewertungsmesswerten sind für jeden Datentyp und jedes Ziel identisch, aber die Ausgaben unterscheiden sich. Die folgenden Beispiele zeigen dieselbe Anfrage, aber unterschiedliche Antworten.

Zusammengefasste Modellbewertungsmesswerte abrufen

Die Gesamtbewertungsmesswerte für das Modell liefern Informationen über das Modell als Ganzes. Wenn Sie Informationen zu einem bestimmten Segment abrufen möchten, listen Sie die Modellbewertungssegmente auf.

Verwenden Sie die Methode projects.locations.models.evaluations.get, um zusammengefasste Modellbewertungsmesswerte anzusehen.

Vertex AI gibt ein Array von Konfidenzmesswerten zurück. Jedes Element zeigt Bewertungsmesswerte mit einem anderen confidenceThreshold-Wert an (beginnend von 0 bis maximal 1). Durch die Anzeige verschiedener Grenzwerte können Sie feststellen, wie sich der Grenzwert auf andere Messwerte wie Precision und Recall auswirkt.

Wählen Sie einen Tab für Ihre Sprache oder Umgebung aus:

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • LOCATION: Region, in der Ihr Modell gespeichert ist
  • PROJECT: Ihre Projekt-ID.
  • MODEL_ID: Die ID der Modellressource.
  • PROJECT_NUMBER: Die automatisch generierte Projektnummer Ihres Projekts.
  • EVALUATION_ID: ID für die Modellbewertung (wird in der Antwort angezeigt)

HTTP-Methode und URL:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations

Senden Sie die Anfrage mithilfe einer der folgenden Optionen:

curl

Führen Sie folgenden Befehl aus:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations"

PowerShell

Führen Sie folgenden Befehl aus:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations" | Select-Object -Expand Content

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

Java

Bevor Sie dieses Beispiel anwenden, folgen Sie den Java-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Java API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.aiplatform.v1.ModelEvaluation;
import com.google.cloud.aiplatform.v1.ModelEvaluationName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;

public class GetModelEvaluationTextClassificationSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // To obtain evaluationId run the code block below after setting modelServiceSettings.
    //
    // try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings))
    // {
    //   String location = "us-central1";
    //   ModelName modelFullId = ModelName.of(project, location, modelId);
    //   ListModelEvaluationsRequest modelEvaluationsrequest =
    //   ListModelEvaluationsRequest.newBuilder().setParent(modelFullId.toString()).build();
    //   for (ModelEvaluation modelEvaluation :
    //     modelServiceClient.listModelEvaluations(modelEvaluationsrequest).iterateAll()) {
    //       System.out.format("Model Evaluation Name: %s%n", modelEvaluation.getName());
    //   }
    // }
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String evaluationId = "YOUR_EVALUATION_ID";

    getModelEvaluationTextClassificationSample(project, modelId, evaluationId);
  }

  static void getModelEvaluationTextClassificationSample(
      String project, String modelId, String evaluationId) throws IOException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // 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 (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";

      ModelEvaluationName modelEvaluationName =
          ModelEvaluationName.of(project, location, modelId, evaluationId);
      ModelEvaluation modelEvaluation = modelServiceClient.getModelEvaluation(modelEvaluationName);

      System.out.println("Get Model Evaluation Text Classification Response");
      System.out.format("\tModel Name: %s\n", modelEvaluation.getName());
      System.out.format("\tMetrics Schema Uri: %s\n", modelEvaluation.getMetricsSchemaUri());
      System.out.format("\tMetrics: %s\n", modelEvaluation.getMetrics());
      System.out.format("\tCreate Time: %s\n", modelEvaluation.getCreateTime());
      System.out.format("\tSlice Dimensions: %s\n", modelEvaluation.getSliceDimensionsList());
    }
  }
}

Node.js

Bevor Sie dieses Beispiel anwenden, folgen Sie den Node.js-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Node.js API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * TODO(developer): Uncomment these variables before running the sample
 * (not necessary if passing values as arguments). To obtain evaluationId,
 * instantiate the client and run the following the commands.
 */
// const parentName = `projects/${project}/locations/${location}/models/${modelId}`;
// const evalRequest = {
//   parent: parentName
// };
// const [evalResponse] = await modelServiceClient.listModelEvaluations(evalRequest);
// console.log(evalResponse);

// const modelId = 'YOUR_MODEL_ID';
// const evaluationId = 'YOUR_EVALUATION_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function getModelEvaluationTextClassification() {
  // Configure the resources
  const name = `projects/${project}/locations/${location}/models/${modelId}/evaluations/${evaluationId}`;
  const request = {
    name,
  };

  // Get model evaluation request
  const [response] = await modelServiceClient.getModelEvaluation(request);

  console.log('Get model evaluation text classification response :');
  console.log(`\tName : ${response.name}`);
  console.log(`\tMetrics schema uri : ${response.metricsSchemaUri}`);
  console.log(`\tMetrics : ${JSON.stringify(response.metrics)}`);

  const modelExplanation = response.modelExplanation;
  console.log('\tModel explanation');
  if (modelExplanation === null) {
    console.log('\t\t{}');
  } else {
    const meanAttributions = modelExplanation.meanAttributions;
    if (meanAttributions === null) {
      console.log('\t\t\t []');
    } else {
      for (const meanAttribution of meanAttributions) {
        console.log('\t\tMean attribution');
        console.log(
          `\t\t\tBaseline output value : \
            ${meanAttribution.baselineOutputValue}`
        );
        console.log(
          `\t\t\tInstance output value : \
            ${meanAttribution.instanceOutputValue}`
        );
        console.log(
          `\t\t\tFeature attributions : \
            ${JSON.stringify(meanAttribution.featureAttributions)}`
        );
        console.log(`\t\t\tOutput index : ${meanAttribution.outputIndex}`);
        console.log(
          `\t\t\tOutput display name : \
            ${meanAttribution.outputDisplayName}`
        );
        console.log(
          `\t\t\tApproximation error : \
            ${meanAttribution.approximationError}`
        );
      }
    }
  }
}
getModelEvaluationTextClassification();

Python

Informationen zum Installieren oder Aktualisieren von Python finden Sie unter Vertex AI SDK für Python installieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Python API.

from google.cloud import aiplatform

def get_model_evaluation_text_classification_sample(
    project: str,
    model_id: str,
    evaluation_id: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    """
    To obtain evaluation_id run the following commands where LOCATION
    is the region where the model is stored, PROJECT is the project ID,
    and MODEL_ID is the ID of your model.

    model_client = aiplatform.gapic.ModelServiceClient(
        client_options={
            'api_endpoint':'LOCATION-aiplatform.googleapis.com'
            }
        )
    evaluations = model_client.list_model_evaluations(parent='projects/PROJECT/locations/LOCATION/models/MODEL_ID')
    print("evaluations:", evaluations)
    """
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
    name = client.model_evaluation_path(
        project=project, location=location, model=model_id, evaluation=evaluation_id
    )
    response = client.get_model_evaluation(name=name)
    print("response:", response)

Alle Bewertungssegmente auflisten

Die Methode projects.locations.models.evaluations.slices.list listet alle Bewertungssegmente für Ihr Modell auf. Sie müssen die Bewertungs-ID des Modells haben, die Sie beim Aufrufen der zusammengefassten Bewertungsmesswerte erhalten.

Mit Modellbewertungssegmenten können Sie die Leistung des Modells bei einem bestimmten Label ermitteln. Das Feld value gibt an, für welches Label die Messwerte gelten.

Vertex AI gibt ein Array von Konfidenzmesswerten zurück. Jedes Element zeigt Bewertungsmesswerte mit einem anderen confidenceThreshold-Wert an (beginnend von 0 bis maximal 1). Durch die Anzeige verschiedener Grenzwerte können Sie feststellen, wie sich der Grenzwert auf andere Messwerte wie Precision und Recall auswirkt.

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • LOCATION: Region, in der sich das Modell befindet. Beispiel: us-central1.
  • PROJECT: Ihre Projekt-ID.
  • MODEL_ID: ID Ihres Modells.
  • EVALUATION_ID: ID der Modellbewertung, die die Bewertungssegmente enthält, die aufgelistet werden sollen.

HTTP-Methode und URL:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations/EVALUATION_ID/slices

Senden Sie die Anfrage mithilfe einer der folgenden Optionen:

curl

Führen Sie folgenden Befehl aus:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations/EVALUATION_ID/slices"

PowerShell

Führen Sie folgenden Befehl aus:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations/EVALUATION_ID/slices" | Select-Object -Expand Content

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

Java

Bevor Sie dieses Beispiel anwenden, folgen Sie den Java-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Java API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.aiplatform.v1.ModelEvaluationName;
import com.google.cloud.aiplatform.v1.ModelEvaluationSlice;
import com.google.cloud.aiplatform.v1.ModelEvaluationSlice.Slice;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;

public class ListModelEvaluationSliceSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // To obtain evaluationId run the code block below after setting modelServiceSettings.
    //
    // try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings))
    // {
    //   String location = "us-central1";
    //   ModelName modelFullId = ModelName.of(project, location, modelId);
    //   ListModelEvaluationsRequest modelEvaluationsrequest =
    //   ListModelEvaluationsRequest.newBuilder().setParent(modelFullId.toString()).build();
    //   for (ModelEvaluation modelEvaluation :
    //     modelServiceClient.listModelEvaluations(modelEvaluationsrequest).iterateAll()) {
    //       System.out.format("Model Evaluation Name: %s%n", modelEvaluation.getName());
    //   }
    // }
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String evaluationId = "YOUR_EVALUATION_ID";
    listModelEvaluationSliceSample(project, modelId, evaluationId);
  }

  static void listModelEvaluationSliceSample(String project, String modelId, String evaluationId)
      throws IOException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // 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 (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      ModelEvaluationName modelEvaluationName =
          ModelEvaluationName.of(project, location, modelId, evaluationId);

      for (ModelEvaluationSlice modelEvaluationSlice :
          modelServiceClient.listModelEvaluationSlices(modelEvaluationName).iterateAll()) {
        System.out.format("Model Evaluation Slice Name: %s\n", modelEvaluationSlice.getName());
        System.out.format("Metrics Schema Uri: %s\n", modelEvaluationSlice.getMetricsSchemaUri());
        System.out.format("Metrics: %s\n", modelEvaluationSlice.getMetrics());
        System.out.format("Create Time: %s\n", modelEvaluationSlice.getCreateTime());

        Slice slice = modelEvaluationSlice.getSlice();
        System.out.format("Slice Dimensions: %s\n", slice.getDimension());
        System.out.format("Slice Value: %s\n\n", slice.getValue());
      }
    }
  }
}

Node.js

Bevor Sie dieses Beispiel anwenden, folgen Sie den Node.js-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Node.js API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * TODO(developer): Uncomment these variables before running the sample
 * (not necessary if passing values as arguments). To obtain evaluationId,
 * instantiate the client and run the following the commands.
 */
// const parentName = `projects/${project}/locations/${location}/models/${modelId}`;
// const evalRequest = {
//   parent: parentName
// };
// const [evalResponse] = await modelServiceClient.listModelEvaluations(evalRequest);
// console.log(evalResponse);

// const modelId = 'YOUR_MODEL_ID';
// const evaluationId = 'YOUR_EVALUATION_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function listModelEvaluationSlices() {
  // Configure the parent resources
  const parent = `projects/${project}/locations/${location}/models/${modelId}/evaluations/${evaluationId}`;
  const request = {
    parent,
  };

  // Get and print out a list of all the evaluation slices for this resource
  const [response] =
    await modelServiceClient.listModelEvaluationSlices(request);
  console.log('List model evaluation response', response);
  console.log(response);
}
listModelEvaluationSlices();

Python

Informationen zum Installieren oder Aktualisieren von Python finden Sie unter Vertex AI SDK für Python installieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Python API.

from google.cloud import aiplatform

def list_model_evaluation_slices_sample(
    project: str,
    model_id: str,
    evaluation_id: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    """
    To obtain evaluation_id run the following commands where LOCATION
    is the region where the model is stored, PROJECT is the project ID,
    and MODEL_ID is the ID of your model.

    model_client = aiplatform.gapic.ModelServiceClient(
        client_options={
            'api_endpoint':'LOCATION-aiplatform.googleapis.com'
            }
        )
    evaluations = model_client.list_model_evaluations(parent='projects/PROJECT/locations/LOCATION/models/MODEL_ID')
    print("evaluations:", evaluations)
    """
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
    parent = client.model_evaluation_path(
        project=project, location=location, model=model_id, evaluation=evaluation_id
    )
    response = client.list_model_evaluation_slices(parent=parent)
    for model_evaluation_slice in response:
        print("model_evaluation_slice:", model_evaluation_slice)

Messwerte für ein einzelnes Segment abrufen

Verwenden Sie die Methode projects.locations.models.evaluations.slices.get, um Bewertungsmesswerte für ein einzelnes Segment aufzurufen. Sie benötigen die Segment-ID, die Sie erhalten, wenn Sie alle Segmente auflisten. Das folgende Beispiel gilt für alle Datentypen und Ziele.

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • LOCATION: Region, in der sich das Modell befindet. Beispiel: us-central1.
  • PROJECT: Ihre Projekt-ID.
  • MODEL_ID: ID Ihres Modells.
  • EVALUATION_ID: ID der Modellbewertung, die das abzurufende Bewertungssegment enthält.
  • SLICE_ID: ID eines abzurufenden Bewertungssegments.
  • PROJECT_NUMBER: Die automatisch generierte Projektnummer Ihres Projekts.
  • EVALUATION_METRIC_SCHEMA_FILE_NAME: Der Name einer Schemadatei, die die Bewertungsmesswerte definiert, die zurückgegeben werden sollen, z. B. classification_metrics_1.0.0.

HTTP-Methode und URL:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations/EVALUATION_ID/slices/SLICE_ID

Senden Sie die Anfrage mithilfe einer der folgenden Optionen:

curl

Führen Sie folgenden Befehl aus:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations/EVALUATION_ID/slices/SLICE_ID"

PowerShell

Führen Sie folgenden Befehl aus:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID/evaluations/EVALUATION_ID/slices/SLICE_ID" | Select-Object -Expand Content

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

Java

Bevor Sie dieses Beispiel anwenden, folgen Sie den Java-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Java API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.aiplatform.v1.ModelEvaluationSlice;
import com.google.cloud.aiplatform.v1.ModelEvaluationSlice.Slice;
import com.google.cloud.aiplatform.v1.ModelEvaluationSliceName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;

public class GetModelEvaluationSliceSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // To obtain evaluationId run the code block below after setting modelServiceSettings.
    //
    // try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings))
    // {
    //   String location = "us-central1";
    //   ModelName modelFullId = ModelName.of(project, location, modelId);
    //   ListModelEvaluationsRequest modelEvaluationsrequest =
    //   ListModelEvaluationsRequest.newBuilder().setParent(modelFullId.toString()).build();
    //   for (ModelEvaluation modelEvaluation :
    //     modelServiceClient.listModelEvaluations(modelEvaluationsrequest).iterateAll()) {
    //       System.out.format("Model Evaluation Name: %s%n", modelEvaluation.getName());
    //   }
    // }
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String evaluationId = "YOUR_EVALUATION_ID";
    String sliceId = "YOUR_SLICE_ID";
    getModelEvaluationSliceSample(project, modelId, evaluationId, sliceId);
  }

  static void getModelEvaluationSliceSample(
      String project, String modelId, String evaluationId, String sliceId) throws IOException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // 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 (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      ModelEvaluationSliceName modelEvaluationSliceName =
          ModelEvaluationSliceName.of(project, location, modelId, evaluationId, sliceId);

      ModelEvaluationSlice modelEvaluationSlice =
          modelServiceClient.getModelEvaluationSlice(modelEvaluationSliceName);

      System.out.println("Get Model Evaluation Slice Response");
      System.out.format("Model Evaluation Slice Name: %s\n", modelEvaluationSlice.getName());
      System.out.format("Metrics Schema Uri: %s\n", modelEvaluationSlice.getMetricsSchemaUri());
      System.out.format("Metrics: %s\n", modelEvaluationSlice.getMetrics());
      System.out.format("Create Time: %s\n", modelEvaluationSlice.getCreateTime());

      Slice slice = modelEvaluationSlice.getSlice();
      System.out.format("Slice Dimensions: %s\n", slice.getDimension());
      System.out.format("Slice Value: %s\n", slice.getValue());
    }
  }
}

Node.js

Bevor Sie dieses Beispiel anwenden, folgen Sie den Node.js-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Node.js API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * TODO(developer): Uncomment these variables before running the sample
 * (not necessary if passing values as arguments). To obtain evaluationId,
 * instantiate the client and run the following the commands.
 */
// const parentName = `projects/${project}/locations/${location}/models/${modelId}`;
// const evalRequest = {
//   parent: parentName
// };
// const [evalResponse] = await modelServiceClient.listModelEvaluations(evalRequest);
// console.log(evalResponse);

// const modelId = 'YOUR_MODEL_ID';
// const evaluationId = 'YOUR_EVALUATION_ID';
// const sliceId = 'YOUR_SLICE_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');
// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};
// Specifies the location of the api endpoint
const modelServiceClient = new ModelServiceClient(clientOptions);

async function getModelEvaluationSlice() {
  // Configure the parent resource
  const name = `projects/${project}/locations/${location}/models/${modelId}/evaluations/${evaluationId}/slices/${sliceId}`;
  const request = {
    name,
  };

  // Get and print out a list of all the endpoints for this resource
  const [response] =
    await modelServiceClient.getModelEvaluationSlice(request);

  console.log('Get model evaluation slice');
  console.log(`\tName : ${response.name}`);
  console.log(`\tMetrics_Schema_Uri : ${response.metricsSchemaUri}`);
  console.log(`\tMetrics : ${JSON.stringify(response.metrics)}`);
  console.log(`\tCreate time : ${JSON.stringify(response.createTime)}`);

  console.log('Slice');
  const slice = response.slice;
  console.log(`\tDimension :${slice.dimension}`);
  console.log(`\tValue :${slice.value}`);
}
getModelEvaluationSlice();

Python

Informationen zum Installieren oder Aktualisieren von Python finden Sie unter Vertex AI SDK für Python installieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Python API.

from google.cloud import aiplatform

def get_model_evaluation_slice_sample(
    project: str,
    model_id: str,
    evaluation_id: str,
    slice_id: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    """
    To obtain evaluation_id run the following commands where LOCATION
    is the region where the model is stored, PROJECT is the project ID,
    and MODEL_ID is the ID of your model.

    model_client = aiplatform.gapic.ModelServiceClient(
        client_options={
            'api_endpoint':'LOCATION-aiplatform.googleapis.com'
            }
        )
    evaluations = model_client.list_model_evaluations(parent='projects/PROJECT/locations/LOCATION/models/MODEL_ID')
    print("evaluations:", evaluations)
    """
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
    name = client.model_evaluation_slice_path(
        project=project,
        location=location,
        model=model_id,
        evaluation=evaluation_id,
        slice=slice_id,
    )
    response = client.get_model_evaluation_slice(name=name)
    print("response:", response)

Modell durchlaufen

Modellbewertungsmesswerte bieten einen Ausgangspunkt für das Debugging Ihres Modells, sollte das Modell Ihre Erwartungen nicht erfüllen. Beispielsweise können niedrige Precision- und Recall-Werte darauf hinweisen, dass das Modell zusätzliche Trainingsdaten benötigt oder inkonsistente Labels enthält. Perfekte Precision- und Recall-Werte können darauf hindeuten, dass die Testdaten zu einfach vorherzusagen sind und sich unter Umständen nicht gut verallgemeinern lassen.

Sie können die Trainingsdaten iterieren und ein neues Modell erstellen. Nachdem Sie ein neues Modell erstellt haben, können Sie die Bewertungsmesswerte zwischen dem vorhandenen Modell und dem neuen Modell vergleichen.

Die folgenden Vorschläge können helfen, Modelle zu verbessern, die Elemente mit Labels versehen, z. B. Klassifizierungs- oder Erkennungsmodelle:

  • Sie sollten weitere Beispiele oder eine größere Auswahl an Beispielen in die Trainingsdaten aufnehmen.
  • Sie können Klassen oder Labels entfernen, die nicht viele Beispiele haben. Unzureichende Beispiele verhindern, dass das Modell konsistent und sicher Vorhersagen zu diesen Klassen oder Labels macht.
  • Erweitern Sie Ihre Daten mit weiteren Beispielen für echt positive und echt negative Ergebnisse, insbesondere Beispiele, die nahe an einer Entscheidungsgrenze liegen, um die Verwechslungsgefahr bei dem Modell zu verringern.
  • Legen Sie Ihre eigene Datenaufteilung fest (Training, Validierung und Test). Vertex AI weist jeder Gruppe Elemente nach dem Zufallsprinzip zu. Daher können nahezu identische Duplikate in den Trainings- und Validierungs-Datasets zugewiesen werden. Dies kann zu einer Überanpassung und dann zu einer schlechten Leistung des Test-Datasets führen. Weitere Informationen zum Festlegen Ihrer eigenen Datenaufteilung finden Sie unter Datenaufteilungen für AutoML-Modelle.
  • Wenn die Bewertungsmesswerte Ihres Modells eine Wahrheitsmatrix enthalten, können Sie sehen, ob das Modell zwei Labels verwechselt, wo das Modell ein bestimmtes Label deutlich häufiger als das echte Label vorhersagt. Überprüfen Sie Ihre Daten und achten Sie darauf, dass die Beispiele mit dem richtigen Label versehen sind.
  • Wenn die Trainingszeit kurz war (niedrige maximale Anzahl an Knotenstunden), erhalten Sie möglicherweise ein Modell höherer Qualität, indem Sie es für einen längeren Zeitraum trainieren (höhere maximale Anzahl an Knotenstunden).