Datasets erstellen und Bilder importieren

Ein Dataset enthält repräsentative Beispiele für den zu klassifizierenden Inhaltstyp und ist mit den Kategorielabels gekennzeichnet, die das benutzerdefinierte Modell verwenden soll. Das Dataset dient als Eingabe zum Trainieren eines Modells.

Die wesentlichen Schritte zum Erstellen eines Datasets sind:

  1. Erstellen Sie ein Dataset und geben Sie an, ob für jedes Element mehrere Labels zulässig sein sollen.
  2. Importieren Sie Datenelemente in das Dataset.
  3. Sie versehen die Elemente mit Labels.

Wenn Sie Elemente mit bereits zugewiesenen Labels importieren, werden Schritte 2 und 3 zu einem zusammengefasst.

Dataset erstellen

Der erste Schritt zum Erstellen eines benutzerdefinierten Modells besteht darin, ein leeres Dataset zu erstellen, das mit den Trainingsdaten für das Modell gefüllt wird. Wenn Sie ein Dataset erstellen, geben Sie den Klassifizierungstyp an, den das benutzerdefinierte Modell ausführen soll:

  • MULTICLASS weist jedem klassifizierten Bild ein einzelnes Label zu
  • MULTILABEL kann einem Bild mehrere Labels zuweisen

Ab Version 1 der AutoML API gibt diese Anfrage die ID eines lang andauernden Vorgangs zurück.

Sobald der lang andauernde Vorgang abgeschlossen ist, können Sie mit dem Importieren von Bildern beginnen. Das neu erstellte Dataset enthält keine Daten, solange noch keine Bilder darin importiert wurden.

Speichern Sie die Dataset-ID des neuen Datasets aus der Antwort, um sie für andere Vorgänge zu verwenden, z. B. zum Importieren von Bildern in Ihr Dataset oder zum Trainieren eines Modells.

Web-UI

  1. Öffnen Sie das Vision Dashboard.

    Sie können diese Seite auch über die Console über das linke Navigationsmenü aufrufen: Künstliche Intelligenz > Vision. Dadurch gelangen Sie zum integrierten Vision-Dashboard. Wählen Sie die AutoML Vision-Karte aus.

    Integriertes UI Vision-Dashboard

  2. Wählen Sie Datasets aus dem linken Navigationsmenü aus.

  3. Wählen Sie oben die Option Neues Dataset aus, aktualisieren Sie den Dataset-Namen und wählen Sie entsprechend den vorhandenen Daten  Klassifizierung mit einem einzigen Label oder Klassifizierung mit mehreren Labels aus.

    Seite zum Auswählen des Modelltyps für das Dataset

  4. Nachdem Sie den Klassifizierungstyp festgelegt haben, wählen Sie Dataset erstellen aus.

  5. Auf der Seite Dataset erstellen können Sie eine CSV-Datei aus Google Cloud Storage oder lokale Bilddateien für den Import in das Dataset auswählen.

    Fenster zum Auswählen von CSV-Import

    Wählen Sie Weiter aus, um den Bildimport in Ihr Dataset zu starten. Während des Imports zeigt das Dataset den Status Wird ausgeführt: Bilder importieren.

  6. Sie erhalten eine E-Mail, wenn der Import abgeschlossen ist.

REST

Im folgenden Beispiel wird ein Dataset erstellt, das ein Label pro Element unterstützt (siehe MULTICLASS).

Das neu erstellte Dataset enthält keine Daten, solange noch keine Elemente darin importiert wurden.

Speichern Sie den Wert für "name" des neuen Datasets aus der Antwort für die Verwendung in anderen Vorgängen, z. B. zum Importieren von Elementen in Ihr Dataset und zum Trainieren eines Modells.

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • project-id: die ID Ihres GCP-Projekts.
  • display-name: ein anzuzeigender Stringname Ihrer Wahl.

HTTP-Methode und URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets

JSON-Text der Anfrage:

{
  "displayName": "DISPLAY_NAME",
  "imageClassificationDatasetMetadata": {
    "classificationType": "MULTICLASS"
  }
}

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets"

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets" | Select-Object -Expand Content

Die Ausgabe sieht in etwa so aus: Sie können den Status der Aufgabe anhand der Vorgangs-ID abrufen (in diesem Fall ICN3819960680614725486). Ein Beispiel finden Sie unter Mit lang andauernden Vorgängen arbeiten.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN3819960680614725486",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-11-14T16:49:13.667526Z",
    "updateTime": "2019-11-14T16:49:13.667526Z",
    "createDatasetDetails": {}
  }
}

Sobald der lang andauernde Vorgang abgeschlossen ist, können Sie die ID des Datasets über die gleiche Anfrage zum Vorgangsstatus abrufen. Die Antwort sollte in etwa so aussehen:

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN3819960680614725486",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-11-14T16:49:13.667526Z",
    "updateTime": "2019-11-14T16:49:17.975314Z",
    "createDatasetDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Dataset",
    "name": "projects/PROJECT_ID/locations/us-central1/datasets/ICN5496445433112696489"
  }
}

Go

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

import (
	"context"
	"fmt"
	"io"

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

// visionClassificationCreateDataset creates a dataset for image classification.
func visionClassificationCreateDataset(w io.Writer, projectID string, location string, datasetName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetName := "dataset_display_name"

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

	req := &automlpb.CreateDatasetRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Dataset: &automlpb.Dataset{
			DisplayName: datasetName,
			DatasetMetadata: &automlpb.Dataset_ImageClassificationDatasetMetadata{
				ImageClassificationDatasetMetadata: &automlpb.ImageClassificationDatasetMetadata{
					// Specify the classification type:
					// - MULTILABEL: Multiple labels are allowed for one example.
					// - MULTICLASS: At most one label is allowed per example.
					ClassificationType: automlpb.ClassificationType_MULTILABEL,
				},
			},
		},
	}

	op, err := client.CreateDataset(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateDataset: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	dataset, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Dataset name: %v\n", dataset.GetName())

	return nil
}

Java

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ClassificationType;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.ImageClassificationDatasetMetadata;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class VisionClassificationCreateDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String displayName = "YOUR_DATASET_NAME";
    createDataset(projectId, displayName);
  }

  // Create a dataset
  static void createDataset(String projectId, String displayName)
      throws IOException, ExecutionException, InterruptedException {
    // 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()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");

      // Specify the classification type
      // Types:
      // MultiLabel: Multiple labels are allowed for one example.
      // MultiClass: At most one label is allowed per example.
      ClassificationType classificationType = ClassificationType.MULTILABEL;
      ImageClassificationDatasetMetadata metadata =
          ImageClassificationDatasetMetadata.newBuilder()
              .setClassificationType(classificationType)
              .build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setImageClassificationDatasetMetadata(metadata)
              .build();
      OperationFuture<Dataset, OperationMetadata> future =
          client.createDatasetAsync(projectLocation, dataset);

      Dataset createdDataset = future.get();

      // Display the dataset information.
      System.out.format("Dataset name: %s\n", createdDataset.getName());
      // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
      // required for other methods.
      // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
      String[] names = createdDataset.getName().split("/");
      String datasetId = names[names.length - 1];
      System.out.format("Dataset id: %s\n", datasetId);
    }
  }
}

Node.js

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

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

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

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

async function createDataset() {
  // Construct request
  // Specify the classification type
  // Types:
  // MultiLabel: Multiple labels are allowed for one example.
  // MultiClass: At most one label is allowed per example.
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      imageClassificationDatasetMetadata: {
        classificationType: 'MULTILABEL',
      },
    },
  };

  // Create dataset
  const [operation] = await client.createDataset(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();

  console.log(`Dataset name: ${response.name}`);
  console.log(`
    Dataset id: ${
      response.name
        .split('/')
        [response.name.split('/').length - 1].split('\n')[0]
    }`);
}

createDataset();

Python

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

from google.cloud import automl

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

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# Specify the classification type
# Types:
# MultiLabel: Multiple labels are allowed for one example.
# MultiClass: At most one label is allowed per example.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#classificationtype
metadata = automl.ImageClassificationDatasetMetadata(
    classification_type=automl.ClassificationType.MULTILABEL
)
dataset = automl.Dataset(
    display_name=display_name,
    image_classification_dataset_metadata=metadata,
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(
    parent=project_location, dataset=dataset, timeout=300
)

created_dataset = response.result()

# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

Weitere Sprachen

C#: Folgen Sie der Anleitung zur Einrichtung von C# auf der Seite der Clientbibliotheken und rufen Sie dann die AutoML Vision-Referenzdokumentation für .NET auf.

PHP: Folgen Sie der Anleitung zur Einrichtung von PHP auf der Seite der Clientbibliotheken und rufen Sie dann die AutoML Vision-Referenzdokumentation für PHP auf.

Ruby: Folgen Sie der Anleitung zur Einrichtung von Ruby auf der Seite der Clientbibliotheken und rufen Sie dann die AutoML Vision-Referenzdokumentation für Ruby auf.

Elemente in ein Dataset importieren

Nachdem Sie ein Dataset erstellt haben, können Sie Element-URIs und Labels für Elemente aus einer CSV-Datei importieren, die in einem Google Cloud Storage-Bucket gespeichert ist. Weitere Informationen zum Vorbereiten von Daten und Erstellen einer CSV-Datei zum Importieren finden Sie unter Trainingsdaten vorbereiten.

Sie können Elemente in ein leeres Dataset importieren oder zusätzliche Elemente in ein vorhandenes Dataset importieren.

Web-UI

Mit der AutoML Vision-Benutzeroberfläche können Sie ein neues Dataset erstellen und Elemente von derselben Seite in dieses Dataset importieren (siehe Dataset erstellen). In den folgenden Schritten werden Elemente in ein vorhandenes Dataset importiert.

  1. Öffnen Sie die Vision Dashboard und wählen Sie das Dataset von der Seite Datasets aus.

    Seite mit Dataset-Liste

  2. Klicken Sie auf der Seite Bilder in der Titelleiste auf Elemente hinzufügen und wählen Sie die Importmethode aus der Dropdown-Liste aus.

    Sie haben folgende Möglichkeiten:

    • Sie können eine CSV-Datei mit den Trainingsbildern und den zugehörigen Kategorielabeln von Ihrem lokalen Computer oder von Google Cloud Storage hochladen.

    • Sie können TXT- oder ZIP-Dateien, die die Trainingsbilder enthalten, von Ihrem lokalen Computer hochladen.

  3. Wählen Sie die Datei(en) für den Import aus.

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • project-id: die ID Ihres GCP-Projekts.
  • dataset-id: die ID Ihres Datasets. Die ID ist das letzte Element des Dataset-Namens. Beispiel:
    • Dataset-Name: projects/project-id/locations/location-id/datasets/3104518874390609379
    • Dataset-ID: 3104518874390609379
  • input-storage-path: der Pfad zu einer in Google Cloud Storage gespeicherten CSV-Datei. Der anfragende Nutzer muss mindestens die Leseberechtigung für den Bucket haben.

HTTP-Methode und URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData

JSON-Text der Anfrage:

{
  "inputConfig": {
    "gcsSource": {
      "inputUris": [INPUT_STORAGE_PATH]
    }
  }
}

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData"

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData" | Select-Object -Expand Content

Die Ausgabe sieht in etwa so aus: Sie können den Status der Aufgabe anhand der Vorgangs-ID abrufen (in diesem Fall ICN3819960680614725486). Ein Beispiel finden Sie unter Mit Vorgängen mit langer Ausführungszeit arbeiten.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T15:56:29.176485Z",
    "importDataDetails": {}
  }
}

Go

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

import (
	"context"
	"fmt"
	"io"

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

// importDataIntoDataset imports data into a dataset.
func importDataIntoDataset(w io.Writer, projectID string, location string, datasetID string, inputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "TRL123456789..."
	// inputURI := "gs://BUCKET_ID/path_to_training_data.csv"

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

	req := &automlpb.ImportDataRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID),
		InputConfig: &automlpb.InputConfig{
			Source: &automlpb.InputConfig_GcsSource{
				GcsSource: &automlpb.GcsSource{
					InputUris: []string{inputURI},
				},
			},
		},
	}

	op, err := client.ImportData(ctx, req)
	if err != nil {
		return fmt.Errorf("ImportData: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Data imported.\n")

	return nil
}

Java

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DatasetName;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.InputConfig;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class ImportDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String path = "gs://BUCKET_ID/path_to_training_data.csv";
    importDataset(projectId, datasetId, path);
  }

  // Import a dataset
  static void importDataset(String projectId, String datasetId, String path)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 complete path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

      // Get multiple Google Cloud Storage URIs to import data from
      GcsSource gcsSource =
          GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();

      // Import data from the input URI
      InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
      System.out.println("Processing import...");

      // Start the import job
      OperationFuture<Empty, OperationMetadata> operation =
          client.importDataAsync(datasetFullId, inputConfig);

      System.out.format("Operation name: %s%n", operation.getName());

      // If you want to wait for the operation to finish, adjust the timeout appropriately. The
      // operation will still run if you choose not to wait for it to complete. You can check the
      // status of your operation using the operation's name.
      Empty response = operation.get(45, TimeUnit.MINUTES);
      System.out.format("Dataset imported. %s%n", response);
    } catch (TimeoutException e) {
      System.out.println("The operation's polling period was not long enough.");
      System.out.println("You can use the Operation's name to get the current status.");
      System.out.println("The import job is still running and will complete as expected.");
      throw e;
    }
  }
}

Node.js

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const datasetId = 'YOUR_DISPLAY_ID';
// const path = 'gs://BUCKET_ID/path_to_training_data.csv';

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

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

async function importDataset() {
  // Construct request
  const request = {
    name: client.datasetPath(projectId, location, datasetId),
    inputConfig: {
      gcsSource: {
        inputUris: path.split(','),
      },
    },
  };

  // Import dataset
  console.log('Proccessing import');
  const [operation] = await client.importData(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Dataset imported: ${response}`);
}

importDataset();

Python

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite Clientbibliotheken.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"
# path = "gs://YOUR_BUCKET_ID/path/to/data.csv"

client = automl.AutoMlClient()
# Get the full path of the dataset.
dataset_full_id = client.dataset_path(project_id, "us-central1", dataset_id)
# Get the multiple Google Cloud Storage URIs
input_uris = path.split(",")
gcs_source = automl.GcsSource(input_uris=input_uris)
input_config = automl.InputConfig(gcs_source=gcs_source)
# Import data from the input URI
response = client.import_data(name=dataset_full_id, input_config=input_config)

print("Processing import...")
print(f"Data imported. {response.result()}")

Trainingselemente mit Labels versehen

Jedem Element in einem Dataset muss mindestens ein Kategorielabel zugewiesen sein, damit es dem Trainieren eines Modells von Nutzen sein kann. Elemente ohne Kategorielabel werden von AutoML Vision ignoriert. Sie können Labels für Ihre Trainingselemente auf drei verschiedene Arten angeben:

  1. Fügen Sie Labels in die CSV-Datei ein.
  2. Versehen Sie Elemente in der AutoML Vision-Benutzeroberfläche mit Labels
  3. Labeling von einem Labeling-Dienst wie Google AI Platform Data Labeling Service anfordern

Benutzeroberfläche mit Labels versehen

Web-UI

Wählen Sie das Dataset auf der Seite mit der Dataset-Liste aus, um Elemente in der Benutzeroberfläche von AutoML Vision mit einem Label zu versehen und um Details zum Dataset anzeigen zu lassen.

In der Seitenleiste wird die Anzahl der Elemente mit und ohne Label zusammengefasst. Hier können Sie die Elementliste nach Label filtern oder Neues Label hinzufügen auswählen, um ein neues Label zu erstellen.

Seite "Bilder"

Auf diesem Bildschirm können Sie auch das Label eines Bildes hinzufügen oder ändern.

Wählen Sie ein Bild aus, das Sie hinzufügen oder dessen Label Sie ändern möchten.

Bildlabel hinzufügen oder ändern

Labeling anfordern

Sie können den AI Platform Data Labeling Service von Google verwenden, um Ihre Bilder mit Labels zu versehen. Weitere Informationen finden Sie in der Produktdokumentation.

Mit lang andauernden Vorgängen arbeiten

Sie können den Status eines lang andauernden Vorgangs anhand der folgenden Codebeispiele abrufen.

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • project-id: die ID Ihres GCP-Projekts.
  • operation-id: ID des Vorgangs. Die ID ist das letzte Element des Vorgangsnamens. Beispiel:
    • Name des Vorgangs: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • Vorgangs-ID: IOD5281059901324392598

HTTP-Methode und URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_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)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"

PowerShell

Führen Sie folgenden Befehl aus:

$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/operations/OPERATION_ID" | Select-Object -Expand Content
Die Ausgabe für einen abgeschlossenen Importvorgang sollte in etwa so aussehen:
{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T16:10:41.326614Z",
    "importDataDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

Die Ausgabe für einen abgeschlossenen -Vorgang zum Erstellen eines Modells sollte in etwa so aussehen:

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-07-22T18:35:06.881193Z",
    "updateTime": "2019-07-22T19:58:44.972235Z",
    "createModelDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Model",
    "name": "projects/PROJECT_ID/locations/us-central1/models/MODEL_ID"
  }
}

Go

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite APIs und Referenz > Clientbibliotheken.

import (
	"context"
	"fmt"
	"io"

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

// getOperationStatus gets an operation's status.
func getOperationStatus(w io.Writer, projectID string, location string, datasetID string, modelName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "ICN123456789..."
	// modelName := "model_display_name"

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

	req := &automlpb.CreateModelRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Model: &automlpb.Model{
			DisplayName: modelName,
			DatasetId:   datasetID,
			ModelMetadata: &automlpb.Model_ImageClassificationModelMetadata{
				ImageClassificationModelMetadata: &automlpb.ImageClassificationModelMetadata{
					TrainBudgetMilliNodeHours: 1000, // 1000 milli-node hours are 1 hour
				},
			},
		},
	}

	op, err := client.CreateModel(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Name: %v\n", op.Name())

	// Wait for the longrunning operation complete.
	resp, err := op.Wait(ctx)
	if err != nil && !op.Done() {
		fmt.Println("failed to fetch operation status", err)
		return err
	}
	if err != nil && op.Done() {
		fmt.Println("operation completed with error", err)
		return err
	}
	fmt.Fprintf(w, "Response: %v\n", resp)

	return nil
}

Java

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite APIs und Referenz > Clientbibliotheken.

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.longrunning.Operation;
import java.io.IOException;

class GetOperationStatus {

  static void getOperationStatus() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String operationFullId = "projects/[projectId]/locations/us-central1/operations/[operationId]";
    getOperationStatus(operationFullId);
  }

  // Get the status of an operation
  static void getOperationStatus(String operationFullId) 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 latest state of a long-running operation.
      Operation operation = client.getOperationsClient().getOperation(operationFullId);

      // Display operation details.
      System.out.println("Operation details:");
      System.out.format("\tName: %s\n", operation.getName());
      System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
      System.out.format("\tDone: %s\n", operation.getDone());
      if (operation.hasResponse()) {
        System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
      }
      if (operation.hasError()) {
        System.out.println("\tResponse:");
        System.out.format("\t\tError code: %s\n", operation.getError().getCode());
        System.out.format("\t\tError message: %s\n", operation.getError().getMessage());
      }
    }
  }
}

Node.js

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite APIs und Referenz > Clientbibliotheken.

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

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

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

async function getOperationStatus() {
  // Construct request
  const request = {
    name: `projects/${projectId}/locations/${location}/operations/${operationId}`,
  };

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

  console.log(`Name: ${response.name}`);
  console.log('Operation details:');
  console.log(`${response}`);
}

getOperationStatus();

Python

Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Einrichtungsanleitung für diese Sprache auf der Seite APIs und Referenz > Clientbibliotheken.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# operation_full_id = \
#     "projects/[projectId]/locations/us-central1/operations/[operationId]"

client = automl.AutoMlClient()
# Get the latest state of a long-running operation.
response = client._transport.operations_client.get_operation(operation_full_id)

print(f"Name: {response.name}")
print("Operation details:")
print(response)

Weitere Sprachen

C#: Folgen Sie der Anleitung zur Einrichtung von C# auf der Seite der Clientbibliotheken und rufen Sie dann die AutoML Vision-Referenzdokumentation für .NET auf.

PHP: Folgen Sie der Anleitung zur Einrichtung von PHP auf der Seite der Clientbibliotheken und rufen Sie dann die AutoML Vision-Referenzdokumentation für PHP auf.

Ruby: Folgen Sie der Anleitung zur Einrichtung von Ruby auf der Seite der Clientbibliotheken und rufen Sie dann die AutoML Vision-Referenzdokumentation für Ruby auf.