Vorhersagen aus einem Klassifizierungsmodell für Texte abrufen

Auf dieser Seite wird beschrieben, wie Sie mit der Google Cloud Console oder der Vertex AI API Onlinevorhersagen (in Echtzeit) und Batchvorhersagen aus Ihren Textklassifizierungsmodellen erhalten.

Unterschied zwischen Online- und Batchvorhersagen

Onlinevorhersagen sind synchrone Anfragen an einen Modellendpunkt. Verwenden Sie Onlinevorhersagen, wenn Sie Anfragen als Reaktion auf Anwendungseingaben stellen oder wenn zeitnahe Inferenzen erforderlich sind.

Batchvorhersagen sind asynchrone Anfragen. Sie können Batchvorhersagen direkt von der Modellressource anfordern, ohne das Modell auf einem Endpunkt bereitstellen zu müssen. Verwenden Sie für Textdaten Batchvorhersagen, wenn Sie nicht sofort eine Antwort benötigen und akkumulierte Daten in einer einzigen Anfrage verarbeiten möchten.

Onlinevorhersagen abrufen

Modell auf einem Endpunkt bereitstellen

Sie müssen ein Modell auf einem Endpunkt bereitstellen, bevor es für Onlinevorhersagen verwendet werden kann. Durch die Bereitstellung eines Modells werden dem Modell physische Ressourcen zugeordnet, sodass es Onlinevorhersagen mit niedriger Latenz bereitstellen kann.

Sie können mehrere Modelle auf einem Endpunkt bereitstellen und ein Modell auf mehreren Endpunkten bereitstellen. Weitere Informationen zu Optionen und Anwendungsfällen für die Bereitstellung von Modellen finden Sie unter Modelle bereitstellen.

Verwenden Sie eine der folgenden Methoden, um ein Modell bereitzustellen:

Google Cloud Console

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

    Zur Seite "Modelle"

  2. Klicken Sie auf den Namen des Modells, das Sie bereitstellen möchten, um die Detailseite zu öffnen.

  3. Wählen Sie den Tab Deploy & Test (Bereitstellen und testen) aus.

    Wenn Ihr Modell bereits für Endpunkte bereitgestellt ist, werden diese im Abschnitt Modell bereitstellen aufgeführt.

  4. Klicken Sie auf In Endpunkt bereitstellen.

  5. Wählen Sie Neuen Endpunkt erstellen aus und geben Sie einen Namen für den neuen Endpunkt an, um Ihr Modell auf einem neuen Endpunkt bereitzustellen. Zum Bereitstellen des Modells auf einem vorhandenen Endpunkt wählen Sie Zu vorhandenem Endpunkt hinzufügen und anschließend den Endpunkt aus der Drop-down-Liste aus.

    Sie können einem Endpunkt mehrere Modelle hinzufügen und ein Modell mehreren Endpunkten hinzufügen. Weitere Informationen

  6. Wenn Sie das Modell auf einem vorhandenen Endpunkt bereitstellen, auf dem ein oder mehrere Modelle bereitgestellt werden, müssen Sie den Prozentsatz für die Trafficaufteilung für das bereitzustellende Modell und die bereits bereitgestellten Modelle aktualisieren, sodass alle Prozentwerte zusammengenommen 100 % ergeben.

  7. Wählen Sie AutoML Text aus und konfigurieren Sie es so:

    1. Wenn Sie Ihr Modell auf einem neuen Endpunkt bereitstellen, akzeptieren Sie für die Trafficaufteilung 100. Andernfalls passen Sie die Werte der Trafficaufteilung für alle Modelle auf dem Endpunkt an, sodass sie 100 ergeben.

    2. Klicken Sie für Ihr Modell auf Fertig. Wenn alle Prozentsätze für Trafficaufteilung korrekt sind, klicken Sie auf Weiter.

      Die Region, in der Ihr bereitgestelltes Modell angezeigt wird. Dies muss die Region sein, in der Sie Ihr Modell erstellt haben.

    3. Klicken Sie auf Deploy, um Ihr Modell auf dem Endpunkt bereitzustellen.

API

Wenn Sie ein Modell mit der Vertex AI API bereitstellen, führen Sie die folgenden Schritte aus:

  1. Erstellen Sie bei Bedarf einen Endpunkt.
  2. Rufen Sie die Endpunkt-ID ab.
  3. Stellen Sie das Modell für den Endpunkt bereit.

Endpunkt erstellen

Wenn Sie ein Modell auf einem vorhandenen Endpunkt bereitstellen, können Sie diesen Schritt überspringen.

gcloud

Im folgenden Beispiel wir der Befehl gcloud ai endpoints create verwendet:

gcloud ai endpoints create \
  --region=LOCATION \
  --display-name=ENDPOINT_NAME

Dabei gilt:

  • LOCATION_ID: Die Region, in der Sie Vertex AI verwenden.
  • ENDPOINT_NAME: Der Anzeigename für den Endpunkt.

Es kann einige Sekunden dauern, bis das Google Cloud CLI den Endpunkt erstellt.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • LOCATION_ID: Ihre Region.
  • PROJECT_ID: Ihre Projekt-ID.
  • ENDPOINT_NAME: Der Anzeigename für den Endpunkt.

HTTP-Methode und URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints

JSON-Text anfordern:

{
  "display_name": "ENDPOINT_NAME"
}

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.CreateEndpointOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-11-05T17:45:42.812656Z",
      "updateTime": "2020-11-05T17:45:42.812656Z"
    }
  }
}
Sie können den Status des Vorgangs abfragen, bis in der Antwort "done": true angegeben wird.

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.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.CreateEndpointOperationMetadata;
import com.google.cloud.aiplatform.v1.Endpoint;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateEndpointSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String endpointDisplayName = "YOUR_ENDPOINT_DISPLAY_NAME";
    createEndpointSample(project, endpointDisplayName);
  }

  static void createEndpointSample(String project, String endpointDisplayName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    EndpointServiceSettings endpointServiceSettings =
        EndpointServiceSettings.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 (EndpointServiceClient endpointServiceClient =
        EndpointServiceClient.create(endpointServiceSettings)) {
      String location = "us-central1";
      LocationName locationName = LocationName.of(project, location);
      Endpoint endpoint = Endpoint.newBuilder().setDisplayName(endpointDisplayName).build();

      OperationFuture<Endpoint, CreateEndpointOperationMetadata> endpointFuture =
          endpointServiceClient.createEndpointAsync(locationName, endpoint);
      System.out.format("Operation name: %s\n", endpointFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      Endpoint endpointResponse = endpointFuture.get(300, TimeUnit.SECONDS);

      System.out.println("Create Endpoint Response");
      System.out.format("Name: %s\n", endpointResponse.getName());
      System.out.format("Display Name: %s\n", endpointResponse.getDisplayName());
      System.out.format("Description: %s\n", endpointResponse.getDescription());
      System.out.format("Labels: %s\n", endpointResponse.getLabelsMap());
      System.out.format("Create Time: %s\n", endpointResponse.getCreateTime());
      System.out.format("Update Time: %s\n", endpointResponse.getUpdateTime());
    }
  }
}

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

// const endpointDisplayName = 'YOUR_ENDPOINT_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

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

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

// Instantiates a client
const endpointServiceClient = new EndpointServiceClient(clientOptions);

async function createEndpoint() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const endpoint = {
    displayName: endpointDisplayName,
  };
  const request = {
    parent,
    endpoint,
  };

  // Get and print out a list of all the endpoints for this resource
  const [response] = await endpointServiceClient.createEndpoint(request);
  console.log(`Long running operation : ${response.name}`);

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

  console.log('Create endpoint response');
  console.log(`\tName : ${result.name}`);
  console.log(`\tDisplay name : ${result.displayName}`);
  console.log(`\tDescription : ${result.description}`);
  console.log(`\tLabels : ${JSON.stringify(result.labels)}`);
  console.log(`\tCreate time : ${JSON.stringify(result.createTime)}`);
  console.log(`\tUpdate time : ${JSON.stringify(result.updateTime)}`);
}
createEndpoint();

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.

def create_endpoint_sample(
    project: str,
    display_name: str,
    location: str,
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint.create(
        display_name=display_name,
        project=project,
        location=location,
    )

    print(endpoint.display_name)
    print(endpoint.resource_name)
    return endpoint

Endpunkt-ID abrufen

Sie benötigen die Endpunkt-ID, um das Modell bereitzustellen.

gcloud

Im folgenden Beispiel wir der Befehl gcloud ai endpoints list verwendet:

gcloud ai endpoints list \
  --region=LOCATION \
  --filter=display_name=ENDPOINT_NAME

Dabei gilt:

  • LOCATION_ID: Die Region, in der Sie Vertex AI verwenden.
  • ENDPOINT_NAME: Der Anzeigename für den Endpunkt.

Notieren Sie sich die Zahl, die in der Spalte ENDPOINT_ID angezeigt wird. Verwenden Sie diese ID im folgenden Schritt.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • LOCATION_ID: Die Region, in der Sie Vertex AI verwenden.
  • PROJECT_ID: Ihre Projekt-ID.
  • ENDPOINT_NAME: Der Anzeigename für den Endpunkt.

HTTP-Methode und URL:

GET https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints?filter=display_name=ENDPOINT_NAME

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "endpoints": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID",
      "displayName": "ENDPOINT_NAME",
      "etag": "AMEw9yPz5pf4PwBHbRWOGh0PcAxUdjbdX2Jm3QO_amguy3DbZGP5Oi_YUKRywIE-BtLx",
      "createTime": "2020-04-17T18:31:11.585169Z",
      "updateTime": "2020-04-17T18:35:08.568959Z"
    }
  ]
}
Beachten Sie die ENDPOINT_ID.

Modell bereitstellen

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

gcloud

In den folgenden Beispielen wird der Befehl gcloud ai endpoints deploy-model verwendet.

Im folgenden Beispiel wird ein Model an einen Endpoint bereitgestellt, ohne den Traffic auf mehrere DeployedModel-Ressourcen aufzuteilen:

Ersetzen Sie folgende Werte, bevor sie einen der Befehlsdaten verwenden:

  • ENDPOINT_ID: Die ID des Endpunkts.
  • LOCATION_ID: Die Region, in der Sie Vertex AI verwenden.
  • MODEL_ID: Die ID des bereitzustellenden Modells.
  • DEPLOYED_MODEL_NAME: Ein Name für DeployedModel. Sie können auch den Anzeigenamen von Model für DeployedModel verwenden.
  • MIN_REPLICA_COUNT: Die minimale Anzahl von Knoten für diese Bereitstellung. Die Knotenzahl kann je nach der Vorhersagelast erhöht oder verringert werden, bis zur maximalen Anzahl von Knoten und niemals auf weniger als diese Anzahl von Knoten.
  • MAX_REPLICA_COUNT: Die maximale Anzahl von Knoten für diese Bereitstellung. Die Knotenzahl kann je nach der Vorhersagelast erhöht oder verringert werden, bis zu dieser Anzahl von Knoten und niemals auf weniger als die minimale Anzahl von Knoten. Wenn Sie das Flag --max-replica-count weglassen, wird die maximale Anzahl von Knoten auf den Wert von --min-replica-count festgelegt.

Führen Sie den Befehl gcloud ai endpoints deploy-model aus:

Linux, macOS oder Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --traffic-split=0=100

Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --traffic-split=0=100

Windows (cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION_ID ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --traffic-split=0=100
 

Traffic aufteilen

Das Flag --traffic-split=0=100 in den vorherigen Beispielen sendet 100 % des Vorhersagetraffics, den der Endpoint empfängt, an das neue DeployedModel, das durch die temporäre ID 0 dargestellt wird. Wenn Ihr Endpoint bereits andere DeployedModel-Ressourcen hat, können Sie den Traffic zwischen dem neuen DeployedModel und den alten aufteilen. Um z. B. 20 % des Traffics an das neue DeployedModel und 80% an ein älteres zu senden, führen Sie den folgenden Befehl aus:

Ersetzen Sie folgende Werte, bevor sie einen der Befehlsdaten verwenden:

  • OLD_DEPLOYED_MODEL_ID: die ID des vorhandenen DeployedModel.

Führen Sie den Befehl gcloud ai endpoints deploy-model aus:

Linux, macOS oder Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT \
  --max-replica-count=MAX_REPLICA_COUNT \
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT `
  --max-replica-count=MAX_REPLICA_COUNT `
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

Windows (cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION_ID ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80
 

REST

Modell bereitstellen

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • LOCATION_ID: Die Region, in der Sie Vertex AI verwenden.
  • PROJECT_ID: Ihre Projekt-ID.
  • ENDPOINT_ID: Die ID des Endpunkts.
  • MODEL_ID: Die ID des bereitzustellenden Modells.
  • DEPLOYED_MODEL_NAME: Ein Name für DeployedModel. Sie können auch den Anzeigenamen von Model für DeployedModel verwenden.
  • TRAFFIC_SPLIT_THIS_MODEL: Der Prozentsatz des Vorhersagetraffics an diesen Endpunkt, der an das Modell mit diesem Vorgang weitergeleitet werden soll. Die Standardeinstellung ist 100. Alle Traffic-Prozentsätze müssen zusammen 100 % ergeben. Weitere Informationen zu Traffic-Splits
  • DEPLOYED_MODEL_ID_N: Optional. Wenn andere Modelle für diesen Endpunkt bereitgestellt werden, müssen Sie die Prozentsätze der Trafficaufteilung aktualisieren, sodass alle Prozentsätze zusammen 100 % ergeben.
  • TRAFFIC_SPLIT_MODEL_N: Der Prozentwert der Trafficaufteilung für den bereitgestellten Modell-ID-Schlüssel.
  • PROJECT_NUMBER: Die automatisch generierte Projektnummer Ihres Projekts.

HTTP-Methode und URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:deployModel

JSON-Text anfordern:

{
  "deployedModel": {
    "model": "projects/PROJECT_ID/locations/us-central1/models/MODEL_ID",
    "displayName": "DEPLOYED_MODEL_NAME",
    "automaticResources": {
     }
  },
  "trafficSplit": {
    "0": TRAFFIC_SPLIT_THIS_MODEL,
    "DEPLOYED_MODEL_ID_1": TRAFFIC_SPLIT_MODEL_1,
    "DEPLOYED_MODEL_ID_2": TRAFFIC_SPLIT_MODEL_2
  },
}

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeployModelOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-19T17:53:16.502088Z",
      "updateTime": "2020-10-19T17:53:16.502088Z"
    }
  }
}

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.api.gax.longrunning.OperationFuture;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.aiplatform.v1.AutomaticResources;
import com.google.cloud.aiplatform.v1.DedicatedResources;
import com.google.cloud.aiplatform.v1.DeployModelOperationMetadata;
import com.google.cloud.aiplatform.v1.DeployModelResponse;
import com.google.cloud.aiplatform.v1.DeployedModel;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.stub.EndpointServiceStubSettings;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.threeten.bp.Duration;

public class DeployModelSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String deployedModelDisplayName = "YOUR_DEPLOYED_MODEL_DISPLAY_NAME";
    String endpointId = "YOUR_ENDPOINT_NAME";
    String modelId = "YOUR_MODEL_ID";
    int timeout = 900;
    deployModelSample(project, deployedModelDisplayName, endpointId, modelId, timeout);
  }

  static void deployModelSample(
      String project,
      String deployedModelDisplayName,
      String endpointId,
      String modelId,
      int timeout)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {

    // Set long-running operations (LROs) timeout
    final OperationTimedPollAlgorithm operationTimedPollAlgorithm =
        OperationTimedPollAlgorithm.create(
            RetrySettings.newBuilder()
                .setInitialRetryDelay(Duration.ofMillis(5000L))
                .setRetryDelayMultiplier(1.5)
                .setMaxRetryDelay(Duration.ofMillis(45000L))
                .setInitialRpcTimeout(Duration.ZERO)
                .setRpcTimeoutMultiplier(1.0)
                .setMaxRpcTimeout(Duration.ZERO)
                .setTotalTimeout(Duration.ofSeconds(timeout))
                .build());

    EndpointServiceStubSettings.Builder endpointServiceStubSettingsBuilder =
        EndpointServiceStubSettings.newBuilder();
    endpointServiceStubSettingsBuilder
        .deployModelOperationSettings()
        .setPollingAlgorithm(operationTimedPollAlgorithm);
    EndpointServiceStubSettings endpointStubSettings = endpointServiceStubSettingsBuilder.build();
    EndpointServiceSettings endpointServiceSettings =
        EndpointServiceSettings.create(endpointStubSettings);
    endpointServiceSettings =
        endpointServiceSettings.toBuilder()
            .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 (EndpointServiceClient endpointServiceClient =
        EndpointServiceClient.create(endpointServiceSettings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);
      // key '0' assigns traffic for the newly deployed model
      // Traffic percentage values must add up to 100
      // Leave dictionary empty if endpoint should not accept any traffic
      Map<String, Integer> trafficSplit = new HashMap<>();
      trafficSplit.put("0", 100);
      ModelName modelName = ModelName.of(project, location, modelId);
      AutomaticResources automaticResourcesInput =
          AutomaticResources.newBuilder().setMinReplicaCount(1).setMaxReplicaCount(1).build();
      DeployedModel deployedModelInput =
          DeployedModel.newBuilder()
              .setModel(modelName.toString())
              .setDisplayName(deployedModelDisplayName)
              .setAutomaticResources(automaticResourcesInput)
              .build();

      OperationFuture<DeployModelResponse, DeployModelOperationMetadata> deployModelResponseFuture =
          endpointServiceClient.deployModelAsync(endpointName, deployedModelInput, trafficSplit);
      System.out.format(
          "Operation name: %s\n", deployModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      DeployModelResponse deployModelResponse = deployModelResponseFuture.get(20, TimeUnit.MINUTES);

      System.out.println("Deploy Model Response");
      DeployedModel deployedModel = deployModelResponse.getDeployedModel();
      System.out.println("\tDeployed Model");
      System.out.format("\t\tid: %s\n", deployedModel.getId());
      System.out.format("\t\tmodel: %s\n", deployedModel.getModel());
      System.out.format("\t\tDisplay Name: %s\n", deployedModel.getDisplayName());
      System.out.format("\t\tCreate Time: %s\n", deployedModel.getCreateTime());

      DedicatedResources dedicatedResources = deployedModel.getDedicatedResources();
      System.out.println("\t\tDedicated Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", dedicatedResources.getMinReplicaCount());

      MachineSpec machineSpec = dedicatedResources.getMachineSpec();
      System.out.println("\t\t\tMachine Spec");
      System.out.format("\t\t\t\tMachine Type: %s\n", machineSpec.getMachineType());
      System.out.format("\t\t\t\tAccelerator Type: %s\n", machineSpec.getAcceleratorType());
      System.out.format("\t\t\t\tAccelerator Count: %s\n", machineSpec.getAcceleratorCount());

      AutomaticResources automaticResources = deployedModel.getAutomaticResources();
      System.out.println("\t\tAutomatic Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", automaticResources.getMinReplicaCount());
      System.out.format("\t\t\tMax Replica Count: %s\n", automaticResources.getMaxReplicaCount());
    }
  }
}

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

// const modelId = "YOUR_MODEL_ID";
// const endpointId = 'YOUR_ENDPOINT_ID';
// const deployedModelDisplayName = 'YOUR_DEPLOYED_MODEL_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

const modelName = `projects/${project}/locations/${location}/models/${modelId}`;
const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
// Imports the Google Cloud Endpoint Service Client library
const {EndpointServiceClient} = require('@google-cloud/aiplatform');

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

// Instantiates a client
const endpointServiceClient = new EndpointServiceClient(clientOptions);

async function deployModel() {
  // Configure the parent resource
  // key '0' assigns traffic for the newly deployed model
  // Traffic percentage values must add up to 100
  // Leave dictionary empty if endpoint should not accept any traffic
  const trafficSplit = {0: 100};
  const deployedModel = {
    // format: 'projects/{project}/locations/{location}/models/{model}'
    model: modelName,
    displayName: deployedModelDisplayName,
    // AutoML Vision models require `automatic_resources` field
    // Other model types may require `dedicated_resources` field instead
    automaticResources: {minReplicaCount: 1, maxReplicaCount: 1},
  };
  const request = {
    endpoint,
    deployedModel,
    trafficSplit,
  };

  // Get and print out a list of all the endpoints for this resource
  const [response] = await endpointServiceClient.deployModel(request);
  console.log(`Long running operation : ${response.name}`);

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

  console.log('Deploy model response');
  const modelDeployed = result.deployedModel;
  console.log('\tDeployed model');
  if (!modelDeployed) {
    console.log('\t\tId : {}');
    console.log('\t\tModel : {}');
    console.log('\t\tDisplay name : {}');
    console.log('\t\tCreate time : {}');

    console.log('\t\tDedicated resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMachine spec {}');
    console.log('\t\t\t\tMachine type : {}');
    console.log('\t\t\t\tAccelerator type : {}');
    console.log('\t\t\t\tAccelerator count : {}');

    console.log('\t\tAutomatic resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMax replica count : {}');
  } else {
    console.log(`\t\tId : ${modelDeployed.id}`);
    console.log(`\t\tModel : ${modelDeployed.model}`);
    console.log(`\t\tDisplay name : ${modelDeployed.displayName}`);
    console.log(`\t\tCreate time : ${modelDeployed.createTime}`);

    const dedicatedResources = modelDeployed.dedicatedResources;
    console.log('\t\tDedicated resources');
    if (!dedicatedResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMachine spec {}');
      console.log('\t\t\t\tMachine type : {}');
      console.log('\t\t\t\tAccelerator type : {}');
      console.log('\t\t\t\tAccelerator count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${dedicatedResources.minReplicaCount}`
      );
      const machineSpec = dedicatedResources.machineSpec;
      console.log('\t\t\tMachine spec');
      console.log(`\t\t\t\tMachine type : ${machineSpec.machineType}`);
      console.log(
        `\t\t\t\tAccelerator type : ${machineSpec.acceleratorType}`
      );
      console.log(
        `\t\t\t\tAccelerator count : ${machineSpec.acceleratorCount}`
      );
    }

    const automaticResources = modelDeployed.automaticResources;
    console.log('\t\tAutomatic resources');
    if (!automaticResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMax replica count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${automaticResources.minReplicaCount}`
      );
      console.log(
        `\t\t\tMax replica count : \
          ${automaticResources.maxReplicaCount}`
      );
    }
  }
}
deployModel();

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.

def deploy_model_with_automatic_resources_sample(
    project,
    location,
    model_name: str,
    endpoint: Optional[aiplatform.Endpoint] = None,
    deployed_model_display_name: Optional[str] = None,
    traffic_percentage: Optional[int] = 0,
    traffic_split: Optional[Dict[str, int]] = None,
    min_replica_count: int = 1,
    max_replica_count: int = 1,
    metadata: Optional[Sequence[Tuple[str, str]]] = (),
    sync: bool = True,
):
    """
    model_name: A fully-qualified model resource name or model ID.
          Example: "projects/123/locations/us-central1/models/456" or
          "456" when project and location are initialized or passed.
    """

    aiplatform.init(project=project, location=location)

    model = aiplatform.Model(model_name=model_name)

    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=deployed_model_display_name,
        traffic_percentage=traffic_percentage,
        traffic_split=traffic_split,
        min_replica_count=min_replica_count,
        max_replica_count=max_replica_count,
        metadata=metadata,
        sync=sync,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    return model

Vorgangsstatus abrufen

Einige Anfragen starten lang andauernde Vorgänge, die viel Zeit in Anspruch nehmen. Diese Anfragen geben einen Vorgangsnamen zurück, mit dem Sie den Status des Vorgangs aufrufen oder den Vorgang abbrechen können. Vertex AI stellt Hilfsmethoden bereit, um Aufrufe für Vorgänge mit langer Laufzeit auszuführen. Weitere Informationen finden Sie unter Mit lang andauernden Vorgängen arbeiten.

Mit dem bereitgestellten Modell eine Onlinevorhersage treffen

Um eine Onlinevorhersage zu erstellen, senden Sie ein oder mehrere Testelemente zur Analyse an ein Modell. Das Modell gibt dann Ergebnisse zurück, die auf den Zielen des Modells basieren. Weitere Informationen zu Vorhersageergebnissen finden Sie auf der Seite Ergebnisse interpretieren.

Console

Verwenden Sie die Google Cloud Console, um eine Onlinevorhersage anzufordern. Ihr Modell muss für einen Endpunkt bereitgestellt sein.

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

    Zur Seite "Modelle"

  2. Klicken Sie in der Liste der Modelle auf den Namen des Modells, von dem Sie Vorhersagen anfordern möchten.

  3. Wählen Sie den Tab Bereitstellen und Testen aus.

  4. Fügen Sie im Abschnitt Modell testen Testelemente hinzu, um eine Vorhersage anzufordern.

    Bei AutoML-Modellen für Textziele müssen Sie Inhalte in ein Textfeld eingeben und auf Vorhersagen klicken.

    Informationen über die lokale Merkmalwichtigkeit finden Sie unter Erläuterungen abrufen.

    Nach Abschluss der Vorhersage gibt Vertex AI die Ergebnisse in der Konsole zurück.

API

Fordern Sie mit der Vertex AI API eine Onlinevorhersage an. Ihr Modell muss für einen Endpunkt bereitgestellt sein.

gcloud

  1. Erstellen Sie eine Datei mit dem Namen request.json und mit folgendem Inhalt:

    {
      "instances": [{
        "mimeType": "text/plain",
        "content": "CONTENT"
      }]
    }
    

    Dabei gilt:

    • CONTENT: Das Text-Snippet, das für eine Vorhersage verwendet wird.
  2. Führen Sie dazu diesen Befehl aus:

    gcloud ai endpoints predict ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json
    

    Dabei gilt:

    • ENDPOINT_ID: Die ID des Endpunkts.
    • LOCATION_ID: Die Region, in der Sie Vertex AI verwenden.

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • LOCATION_ID: Die Region, in der sich der Endpunkt befindet. Beispiel: us-central1.
  • PROJECT_ID: Ihre Projekt-ID
  • ENDPOINT_ID: Die ID des Endpunkts
  • CONTENT: Das Text-Snippet, das für eine Vorhersage verwendet wird.
  • DEPLOYED_MODEL_ID: Die ID des bereitgestellten Modells, mit dem die Vorhersage erstellt wird.

HTTP-Methode und URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict

JSON-Text der Anfrage:

{
  "instances": [{
    "mimeType": "text/plain",
    "content": "CONTENT"
  }]
}

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 "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict"

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" }

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

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "predictions": [
    {
      "ids": [
        "1234567890123456789",
        "2234567890123456789",
        "3234567890123456789"
      ],
      "displayNames": [
        "GreatService",
        "Suggestion",
        "InfoRequest"
      ],
      "confidences": [
        0.8986392080783844,
        0.81984345316886902,
        0.7722353458404541
      ]
    }
  ],
  "deployedModelId": "0123456789012345678"
}

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.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.instance.TextClassificationPredictionInstance;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.ClassificationPredictionResult;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PredictTextClassificationSingleLabelSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String content = "YOUR_TEXT_CONTENT";
    String endpointId = "YOUR_ENDPOINT_ID";

    predictTextClassificationSingleLabel(project, content, endpointId);
  }

  static void predictTextClassificationSingleLabel(
      String project, String content, String endpointId) throws IOException {
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.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 (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      TextClassificationPredictionInstance predictionInstance =
          TextClassificationPredictionInstance.newBuilder().setContent(content).build();

      List<Value> instances = new ArrayList<>();
      instances.add(ValueConverter.toValue(predictionInstance));

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, ValueConverter.EMPTY_VALUE);
      System.out.println("Predict Text Classification Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions:\n\n");
      for (Value prediction : predictResponse.getPredictionsList()) {

        ClassificationPredictionResult.Builder resultBuilder =
            ClassificationPredictionResult.newBuilder();

        // Display names and confidences values correspond to
        // IDs in the ID list.
        ClassificationPredictionResult result =
            (ClassificationPredictionResult) ValueConverter.fromValue(resultBuilder, prediction);
        int counter = 0;
        for (Long id : result.getIdsList()) {
          System.out.printf("Label ID: %d\n", id);
          System.out.printf("Label: %s\n", result.getDisplayNames(counter));
          System.out.printf("Confidence: %.4f\n", result.getConfidences(counter));
          counter++;
        }
      }
    }
  }
}

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

// const text = 'YOUR_PREDICTION_TEXT';
// const endpointId = 'YOUR_ENDPOINT_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {instance, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Model Service Client library
const {PredictionServiceClient} = aiplatform.v1;

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

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function predictTextClassification() {
  // Configure the resources
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const predictionInstance =
    new instance.TextClassificationPredictionInstance({
      content: text,
    });
  const instanceValue = predictionInstance.toValue();

  const instances = [instanceValue];
  const request = {
    endpoint,
    instances,
  };

  const [response] = await predictionServiceClient.predict(request);
  console.log('Predict text classification response');
  console.log(`\tDeployed model id : ${response.deployedModelId}\n\n`);

  console.log('Prediction results:');

  for (const predictionResultValue of response.predictions) {
    const predictionResult =
      prediction.ClassificationPredictionResult.fromValue(
        predictionResultValue
      );

    for (const [i, label] of predictionResult.displayNames.entries()) {
      console.log(`\tDisplay name: ${label}`);
      console.log(`\tConfidences: ${predictionResult.confidences[i]}`);
      console.log(`\tIDs: ${predictionResult.ids[i]}\n\n`);
    }
  }
}
predictTextClassification();

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.

def predict_text_classification_single_label_sample(
    project, location, endpoint, content
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint)

    response = endpoint.predict(instances=[{"content": content}], parameters={})

    for prediction_ in response.predictions:
        print(prediction_)

Batchvorhersagen abrufen

Für eine Batchvorhersage geben Sie eine Eingabequelle und einen Ausgabeort an, an dem Vertex AI Vorhersageergebnisse speichert.

Anforderungen an Eingabedaten

Die Eingabe für Batchanfragen gibt die Elemente an, die zur Vorhersage an Ihr Modell gesendet werden sollen. Bei Textklassifizierungsmodellen können Sie eine JSON-Lines-Datei verwenden, um eine Liste von Dokumenten anzugeben, zu denen Vorhersagen getroffen werden sollen. Anschließend können Sie die JSON Lines-Datei in einem Cloud Storage-Bucket speichern. Das folgende Beispiel zeigt eine einzelne Zeile in einer JSON Lines-Eingabedatei.

{"content": "gs://sourcebucket/datasets/texts/source_text.txt", "mimeType": "text/plain"}

Eine Batchvorhersage anfordern

Für Batchvorhersageanfragen können Sie die Google Cloud Console oder die Vertex AI API verwenden. Abhängig von der Anzahl der Eingabeelemente, die Sie eingereicht haben, kann die Batchvorhersage eine Weile dauern.

Google Cloud Console

Verwenden Sie die Google Cloud Console, um eine Batchvorhersage anzufordern.

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

    Zur Seite "Batchvorhersagen"

  2. Klicken Sie auf Erstellen, um das Fenster Neue Batchvorhersage zu öffnen, und führen Sie die folgenden Schritte aus:

    1. Geben Sie einen Namen für die Batchvorhersage ein.
    2. Wählen Sie für Modellname den Namen des Modells aus, das für diese Batchvorhersage verwendet werden soll.
    3. Geben Sie unter Quellpfad den Cloud Storage-Speicherort an, in dem sich Ihre JSON Lines-Eingabedatei befindet.
    4. Geben Sie als Zielpfad einen Cloud Storage-Speicherort an, an dem die Ergebnisse der Batchvorhersage gespeichert werden. Das Format der Ausgabe wird durch das Ziel des Modells bestimmt. AutoML-Modelle für Textziele geben JSON Lines-Ausgabedateien aus.

API

Verwenden Sie die Vertex AI API zum Senden von Batchvorhersageanfragen.

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • LOCATION_IS: Region, in der das Modell gespeichert ist .und der Batchvorhersagejob ausgeführt wird. Beispiel: us-central1.
  • PROJECT_ID: Ihre Projekt-ID
  • BATCH_JOB_NAME: Anzeigename für den Batchjob
  • MODEL_ID: Die ID für das Modell, das für Vorhersagen verwendet werden soll
  • URI: Der Cloud Storage-URI, in dem sich die JSON Lines-Eingabedatei befindet
  • BUCKET: Ihr Cloud Storage-Bucket
  • PROJECT_NUMBER: Die automatisch generierte Projektnummer Ihres Projekts.

HTTP-Methode und URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/batchPredictionJobs

JSON-Text der Anfrage:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT_ID/locations/LOCATION_ID/models/MODEL_ID",
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"]
        }
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET"
        }
    }
}

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 "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/batchPredictionJobs"

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" }

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

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME",
  "model": "projects/PROJECT_NUMBER/locations/LOCATION/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "completionStats": {
    "incompleteCount": "-1"
  },
  "createTime": "2022-12-19T20:33:48.906074Z",
  "updateTime": "2022-12-19T20:33:48.906074Z",
  "modelVersionId": "1"
}

Sie können den Status des Batch-Jobs mit BATCH_JOB_ID abfragen, bis der Job state den Wert JOB_STATE_SUCCEEDED hat.

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.api.gax.rpc.ApiException;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import java.io.IOException;

public class CreateBatchPredictionJobTextClassificationSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String location = "us-central1";
    String displayName = "DISPLAY_NAME";
    String modelId = "MODEL_ID";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobTextClassificationSample(
        project, location, displayName, modelId, gcsSourceUri, gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobTextClassificationSample(
      String project,
      String location,
      String displayName,
      String modelId,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    // The AI Platform services require regional API endpoints.
    JobServiceSettings settings =
        JobServiceSettings.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 (JobServiceClient client = JobServiceClient.create(settings)) {
      try {
        String modelName = ModelName.of(project, location, modelId).toString();
        GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
        BatchPredictionJob.InputConfig inputConfig =
            BatchPredictionJob.InputConfig.newBuilder()
                .setInstancesFormat("jsonl")
                .setGcsSource(gcsSource)
                .build();
        GcsDestination gcsDestination =
            GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
        BatchPredictionJob.OutputConfig outputConfig =
            BatchPredictionJob.OutputConfig.newBuilder()
                .setPredictionsFormat("jsonl")
                .setGcsDestination(gcsDestination)
                .build();
        BatchPredictionJob batchPredictionJob =
            BatchPredictionJob.newBuilder()
                .setDisplayName(displayName)
                .setModel(modelName)
                .setInputConfig(inputConfig)
                .setOutputConfig(outputConfig)
                .build();
        LocationName parent = LocationName.of(project, location);
        BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
        System.out.format("response: %s\n", response);
      } catch (ApiException ex) {
        System.out.format("Exception: %s\n", ex.getLocalizedMessage());
      }
    }
  }
}

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

// const batchPredictionDisplayName = 'YOUR_BATCH_PREDICTION_DISPLAY_NAME';
// const modelId = 'YOUR_MODEL_ID';
// const gcsSourceUri = 'YOUR_GCS_SOURCE_URI';
// const gcsDestinationOutputUriPrefix = 'YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Job Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform').v1;

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

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createBatchPredictionJobTextClassification() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const modelName = `projects/${project}/locations/${location}/models/${modelId}`;

  const inputConfig = {
    instancesFormat: 'jsonl',
    gcsSource: {uris: [gcsSourceUri]},
  };
  const outputConfig = {
    predictionsFormat: 'jsonl',
    gcsDestination: {outputUriPrefix: gcsDestinationOutputUriPrefix},
  };
  const batchPredictionJob = {
    displayName: batchPredictionDisplayName,
    model: modelName,
    inputConfig,
    outputConfig,
  };
  const request = {
    parent,
    batchPredictionJob,
  };

  // Create batch prediction job request
  const [response] = await jobServiceClient.createBatchPredictionJob(request);

  console.log('Create batch prediction job text classification response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createBatchPredictionJobTextClassification();

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.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

Batchvorhersageergebnisse abrufen

Wenn eine Batchvorhersage abgeschlossen ist, wird die Ausgabe der Vorhersage in dem Cloud Storage-Bucket gespeichert, den Sie in der Anfrage angegeben haben.

Beispielergebnisse für Batchvorhersagen

Das folgende Beispiel zeigt die Batchvorhersage aus einem Textklassifizierungsmodell.

{
  "instance": {"content": "gs://bucket/text.txt", "mimeType": "text/plain"},
  "predictions": [
    {
      "ids": [
        "1234567890123456789",
        "2234567890123456789",
        "3234567890123456789"
      ],
      "displayNames": [
        "GreatService",
        "Suggestion",
        "InfoRequest"
      ],
      "confidences": [
        0.8986392080783844,
        0.81984345316886902,
        0.7722353458404541
      ]
    }
  ]
}