テキスト感情分析モデルから予測を取得する

このページでは、Google Cloud コンソールまたは Vertex AI API を使用して、テキスト感情分析モデルからオンライン(リアルタイム)予測とバッチ予測を取得する方法を説明します。

オンライン予測とバッチ予測の違い

オンライン予測は、モデルのエンドポイントに対して行われる同期リクエストです。アプリケーションの入力に応じてリクエストを行う場合や、タイムリーな推論が必要な場合は、オンライン予測を使用します。

バッチ予測は非同期リクエストです。エンドポイントにモデルをデプロイすることなく、モデルリソースからバッチ予測を直接リクエストします。テキストデータで、すぐにレスポンスを必要とせず 1 回のリクエストで累積データを処理したい場合は、バッチ予測を使用します。

オンライン予測を取得する

エンドポイントにモデルをデプロイする

オンライン予測用にモデルを配信する前に、モデルをエンドポイントにデプロイする必要があります。モデルのデプロイでは、少ないレイテンシでオンライン予測を提供できるように、モデルに物理リソースを関連付けます。

1 つのエンドポイントに複数のモデルをデプロイすることも、モデルを複数のエンドポイントにデプロイすることもできます。モデルのデプロイにおけるオプションとユースケースの詳細については、モデルのデプロイについてをご覧ください。

モデルをデプロイするには、次のいずれかの方法を使用します。

コンソール

  1. Google Cloud コンソールの [Vertex AI] セクションで、[モデル] ページに移動します。

    [モデル] ページに移動

  2. デプロイするモデルの名前をクリックして、詳細ページを開きます。

  3. [デプロイとテスト] タブを選択します。

    モデルがいずれかのエンドポイントにデプロイされている場合は、[モデルのデプロイ] セクションに一覧表示されます。

  4. [エンドポイントへのデプロイ] をクリックします。

  5. 新しいエンドポイントにモデルをデプロイするには、[新しいエンドポイントを作成する] を選択し、新しいエンドポイントの名前を指定します。モデルを既存のエンドポイントにデプロイするには、[既存のエンドポイントに追加] を選択して、プルダウン リストからエンドポイントを選択します。

    1 つのエンドポイントに複数のモデルを追加することも、モデルを複数のエンドポイントに追加することもできます。詳細

  6. 1 つ以上のモデルがデプロイされている既存のエンドポイントにモデルをデプロイする場合は、すべての割合の合計が 100% になるように、デプロイするモデルとデプロイ済みのモデルのトラフィック分割の割合を更新する必要があります。

  7. [AutoML Text] を選択して、次のように構成します。

    1. モデルを新しいエンドポイントにデプロイする場合は、トラフィック分割を 100 にします。それ以外の場合は、合計が 100 になるように、エンドポイントにあるすべてのモデルのトラフィック分割値を調整します。

    2. モデルの [完了] をクリックします。すべてのトラフィック分割の割合が正しい場合は、[続行] をクリックします。

      モデルがデプロイされるリージョンが表示されます。これは、モデルを作成したリージョンにする必要があります。

    3. [デプロイ] をクリックして、エンドポイントにモデルをデプロイします。

API

Vertex AI API を使用してモデルをデプロイする場合は、次の手順を行います。

  1. 必要に応じてエンドポイントを作成します。
  2. エンドポイント ID を取得します。
  3. エンドポイントにモデルをデプロイします。

エンドポイントを作成する

既存のエンドポイントにモデルをデプロイする場合は、この手順を省略できます。

gcloud

次の例では、gcloud ai endpoints create コマンドを使用します。

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

次のように置き換えます。

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • ENDPOINT_NAME: エンドポイントの表示名。

Google Cloud CLI ツールがエンドポイントを作成するまでに数秒かかる場合があります。

REST

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

  • LOCATION_ID: 使用するリージョン。
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_NAME: エンドポイントの表示名。

HTTP メソッドと URL:

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

リクエストの本文(JSON):

 {   "display_name": "ENDPOINT_NAME" } 

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

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

 {   "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"     }   } } 
レスポンスに "done": true が含まれるまで、オペレーションのステータスをポーリングできます。

Java

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

 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

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

Vertex AI SDK for Python

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Vertex AI SDK for 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  

エンドポイント ID を取得する

モデルをデプロイするには、エンドポイント ID が必要です。

gcloud

次の例では、gcloud ai endpoints list コマンドを使用します。

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

次のように置き換えます。

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • ENDPOINT_NAME: エンドポイントの表示名。

ENDPOINT_ID 列に表示される番号をメモします。この ID は次の手順で使用します。

REST

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

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_NAME: エンドポイントの表示名。

HTTP メソッドと URL:

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

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

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

 {   "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"     }   ] } 
ENDPOINT_ID に注意してください。

モデルをデプロイする

お使いの言語または環境に応じて、以下のタブを選択してください。

gcloud

次の例では、gcloud ai endpoints deploy-model コマンドを使用しています。

次の例では、複数の DeployedModel リソース間でトラフィックを分割せずに ModelEndpoint にデプロイします。

後述のコマンドデータを使用する前に、次のように置き換えます。

  • ENDPOINT_ID: エンドポイントの ID。
  • LOCATION_ID: Vertex AI を使用するリージョン。
  • MODEL_ID: デプロイするモデルの ID。
  • DEPLOYED_MODEL_NAME: DeployedModel の名前。DeployedModelModel の表示名を使用することもできます。
  • MIN_REPLICA_COUNT: このデプロイの最小ノード数。ノード数は、予測負荷に応じてノードの最大数まで増減できますが、この数より少なくすることはできません。
  • MAX_REPLICA_COUNT: このデプロイの最大ノード数。ノード数は、予測負荷に応じてこのノード数まで増減に応じて増減できますが、最大値を超えることはできません。--max-replica-count フラグを省略した場合、最大ノード数は --min-replica-count の値に設定されます。

gcloud ai endpoints deploy-model コマンドを実行します。

Linux、macOS、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-split=0=100 フラグでは、Endpoint が受信する新しい予測トラフィックの 100% を新しい DeployedModel に送信します。これは、一時的な ID 0 で表されます。Endpoint にすでに他の DeployedModel リソースがある場合は、新しい DeployedModel と古いリソースとの間でトラフィックを分割できます。たとえば、トラフィックの 20% を新しい DeployedModel に、80% を古いリソースに送信するには、次のコマンドを実行します。

後述のコマンドデータを使用する前に、次のように置き換えます。

  • OLD_DEPLOYED_MODEL_ID: 既存の DeployedModel の ID。

gcloud ai endpoints deploy-model コマンドを実行します。

Linux、macOS、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

モデルをデプロイします。

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

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_ID: エンドポイントの ID。
  • MODEL_ID: デプロイするモデルの ID。
  • DEPLOYED_MODEL_NAME: DeployedModel の名前。DeployedModelModel の表示名を使用することもできます。
  • TRAFFIC_SPLIT_THIS_MODEL: このオペレーションでデプロイするモデルにルーティングされる、このエンドポイントへの予測トラフィックの割合。デフォルトは 100 です。すべてのトラフィックの割合の合計は 100 になる必要があります。トラフィック分割の詳細
  • DEPLOYED_MODEL_ID_N: 省略可。他のモデルがこのエンドポイントにデプロイされている場合は、すべての割合の合計が 100 になるように、トラフィック分割の割合を更新する必要があります。
  • TRAFFIC_SPLIT_MODEL_N: デプロイされたモデル ID キーのトラフィック分割の割合値。
  • PROJECT_NUMBER: プロジェクトに自動生成されたプロジェクト番号

HTTP メソッドと URL:

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

リクエストの本文(JSON):

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

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

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

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

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

 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

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

Vertex AI SDK for Python

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Vertex AI SDK for 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  

オペレーションのステータスを取得する

一部のリクエストでは、完了までに長時間かかるオペレーションが実行されます。このようなリクエストではオペレーション名が返されます。そのオペレーション名を使用して、オペレーションのステータス確認やキャンセルを行うことができます。Vertex AI には、長時間実行オペレーションに対して呼び出しを行うためのヘルパー メソッドが用意されています。詳細については、長時間実行オペレーションによる作業をご覧ください。

デプロイされたモデルを使用してオンライン予測を行う

オンライン予測を行うには、モデルに分析のためのテスト項目を 1 つ以上送信し、モデルがモデルの目的に基づいて結果を返します。予測結果の詳細については、結果を解釈するをご覧ください。

コンソール

Google Cloud コンソールを使用してオンライン予測をリクエストします。モデルはエンドポイントにデプロイする必要があります。

  1. Google Cloud コンソールの [Vertex AI] セクションで、[モデル] ページに移動します。

    [モデル] ページに移動

  2. モデルのリストで、予測をリクエストするモデルの名前をクリックします。

  3. [デプロイとテスト] タブを選択します。

  4. [モデルのテスト] セクションで、予測をリクエストするテスト項目を追加します。

    テキスト目的の AutoML モデルでは、テキスト フィールドにコンテンツを入力して [予測] をクリックする必要があります。

    ローカル特徴量の重要度については、説明を取得するをご覧ください。

    予測が完了すると、Vertex AI がコンソールに結果を返します。

API

Vertex AI API を使用してオンライン予測をリクエストします。モデルはエンドポイントにデプロイする必要があります。

gcloud

  1. 次の内容のファイルを request.json という名前で作成します。

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

    次のように置き換えます。

    • CONTENT: 予測に使用されるテキスト スニペット。
  2. 次のコマンドを実行します。

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

    次のように置き換えます。

    • ENDPOINT_ID: エンドポイントの ID。
    • LOCATION_ID: Vertex AI を使用するリージョン。

REST

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

  • LOCATION_ID: エンドポイントが配置されているリージョン。例: us-central1
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_ID: エンドポイントの ID
  • CONTENT: 予測に使用されるテキスト スニペット。
  • DEPLOYED_MODEL_ID: 予測に使用されたデプロイ済みモデルの ID。

HTTP メソッドと URL:

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

リクエストの本文(JSON):

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

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

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$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

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

 {   "prediction":     {       sentiment": 8     },   "deployedModelId": "1234567890123456789" } 

Java

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

 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.gson.JsonObject; import com.google.protobuf.Value; import com.google.protobuf.util.JsonFormat; import java.io.IOException; import java.util.ArrayList; import java.util.List;  public class PredictTextSentimentAnalysisSample {    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";      predictTextSentimentAnalysis(project, content, endpointId);   }    static void predictTextSentimentAnalysis(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";        // Use JsonObject to ensure safe serialization of the content; handles characters like `"`.       JsonObject contentJsonObject = new JsonObject();       contentJsonObject.addProperty("content", content);        EndpointName endpointName = EndpointName.of(project, location, endpointId);        Value parameter = Value.newBuilder().setNumberValue(0).setNumberValue(5).build();       Value.Builder instance = Value.newBuilder();       JsonFormat.parser().merge(contentJsonObject.toString(), instance);        List<Value> instances = new ArrayList<>();       instances.add(instance.build());        PredictResponse predictResponse =           predictionServiceClient.predict(endpointName, instances, parameter);       System.out.println("Predict Text Sentiment Analysis Response");       System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());        System.out.println("Predictions");       for (Value prediction : predictResponse.getPredictionsList()) {         System.out.format("\tPrediction: %s\n", prediction);       }     }   } }

Node.js

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**  * 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 predictTextSentimentAnalysis() {   // Configure the endpoint resource   const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;    const instanceObj = new instance.TextSentimentPredictionInstance({     content: text,   });   const instanceVal = instanceObj.toValue();    const instances = [instanceVal];   const request = {     endpoint,     instances,   };    // Predict request   const [response] = await predictionServiceClient.predict(request);    console.log('Predict text sentiment analysis response:');   console.log(`\tDeployed model id : ${response.deployedModelId}`);    console.log('\nPredictions :');   for (const predictionResultValue of response.predictions) {     const predictionResult =       prediction.TextSentimentPredictionResult.fromValue(         predictionResultValue       );     console.log(`\tSentiment measure: ${predictionResult.sentiment}`);   } } predictTextSentimentAnalysis();

Vertex AI SDK for Python

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Vertex AI SDK for Python API のリファレンス ドキュメントをご覧ください。

def predict_text_sentiment_analysis_sample(project, location, endpoint_id, content):      aiplatform.init(project=project, location=location)      endpoint = aiplatform.Endpoint(endpoint_id)      response = endpoint.predict(instances=[{"content": content}], parameters={})      for prediction_ in response.predictions:         print(prediction_)  

テキスト感情分析モデルからバッチ予測を取得する

バッチ予測リクエストでは、入力ソースと、Vertex AI が予測結果を格納する出力先を指定します。

入力データの要件

一括リクエストの入力では、予測用のモデルに送信するアイテムを指定します。テキスト感情分析モデルでは、予測を行うドキュメントのリストを JSON Lines ファイルに指定し、このファイルを Cloud Storage バケットに格納できます。次のサンプルは、入力 JSON Lines ファイルの 1 行を示しています。

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

バッチ予測をリクエストする

バッチ予測リクエストの場合、Google Cloud コンソールまたは Vertex AI API を使用できます。送信した入力アイテム数によっては、バッチ予測タスクが完了するまでに時間がかかることがあります。

Google Cloud コンソール

Google Cloud コンソールを使用してバッチ予測をリクエストします。

  1. Google Cloud コンソールの [Vertex AI] セクションで、[バッチ予測] ページに移動します。

    [バッチ予測] ページに移動

  2. [作成] をクリックして [新しいバッチ予測] ウィンドウを開き、次の操作を行います。

    1. バッチ予測の名前を入力します。
    2. [モデル名] で、このバッチ予測に使用するモデルの名前を選択します。
    3. [転送元のパス] に、JSON Lines 入力ファイルがある Cloud Storage のロケーションを指定します。
    4. [宛先のパス] に、バッチ予測結果が保存される Cloud Storage のロケーションを指定します。出力形式はモデルの目標によって決まります。テキスト目的の AutoML モデルは、JSON Lines ファイルを出力します。

API

Vertex AI API を使用してバッチ予測リクエストを送信します。

REST

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

  • LOCATION_IS: モデルを保存し、バッチ予測ジョブを実行するリージョン。例: us-central1
  • PROJECT_ID: 実際のプロジェクト ID
  • BATCH_JOB_NAME: バッチジョブの表示名
  • MODEL_ID: 予測に使用するモデルの ID
  • URI: 入力 JSON Lines ファイルが存在する Cloud Storage URI。
  • BUCKET: Cloud Storage バケット
  • PROJECT_NUMBER: プロジェクトに自動生成されたプロジェクト番号

HTTP メソッドと URL:

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

リクエストの本文(JSON):

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

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

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$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

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

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

ジョブ stateJOB_STATE_SUCCEEDED になるまで、BATCH_JOB_ID を使用してバッチジョブのステータスをポーリングできます。

Java

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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 CreateBatchPredictionJobTextSentimentAnalysisSample {    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";     createBatchPredictionJobTextSentimentAnalysisSample(         project, location, displayName, modelId, gcsSourceUri, gcsDestinationOutputUriPrefix);   }    static void createBatchPredictionJobTextSentimentAnalysisSample(       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

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**  * 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 createBatchPredictionJobTextSentimentAnalysis() {   // 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 sentiment analysis response');   console.log(`Name : ${response.name}`);   console.log('Raw response:');   console.log(JSON.stringify(response, null, 2)); } createBatchPredictionJobTextSentimentAnalysis();

Vertex AI SDK for Python

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Vertex AI SDK for 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  

バッチ予測の結果を取得する

バッチ予測タスクが完了すると、リクエストで指定した Cloud Storage バケットに予測の出力が保存されます。

バッチ予測結果の例

テキスト感情分析モデルによるバッチ予測の結果の例を次に示します。

 {   "instance": {"content": "gs://bucket/text.txt", "mimeType": "text/plain"},   "prediction": {"sentiment": 8} }