<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Vertex AI AutoML text entity extractionn model
Installation
Install the latest (preview) version of Vertex SDK.
Step1:  Install the Google cloud-storage library as well.
Step2:  Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.
Step3:  Before you begin
GPU run-time
Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU
Set up your GCP project
The following steps are required, regardless of your notebook environment.
Select or create a GCP project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex APIs and Compute Engine APIs.
Google Cloud SDK is already installed in Google Cloud Notebooks.
Enter your project ID in the cell below. Then run the  cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note
Step4:  Region
You can also change the REGION variable, which is used for operations
throughout the rest of this notebook.  Below are regions supported for Vertex AI. We recommend when possible, to choose the region closest to you.
Americas
Step5:  Timestamp
If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.
Step6:  Authenticate your GCP account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
Note
Step7:  Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
Step8:  Only if your bucket doesn't already exist
Step9:  Finally, validate access to your Cloud Storage bucket by examining its contents
Step10:  Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
Import Vertex SDK
Import the Vertex SDK into our Python environment.
Step11:  Vertex AI constants
Setup up the following constants for Vertex AI
Step12:  AutoML constants
Next, setup constants unique to AutoML Text Entity Extraction datasets and training
Step13:  Clients
The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).
You will use several clients in this tutorial, so set them all up upfront.
Dataset Service for managed datasets.
Model Service for managed models.
Pipeline Service for training.
Endpoint Service for deployment.
Job Service for batch jobs and custom training.
Prediction Service for serving. Note
Step14:  Example output
Step15:  Example output
Step16:  Response
Step17:  Example output
Step18:  projects.locations.datasets.import
Request
Step19:  Example output
Step20:  Response
Step21:  Example output
Step22:  Example output
Step23:  Response
Step24:  Example output
Step25:  projects.locations.trainingPipelines.get
Call
Step26:  Response
Step27:  Example output
Step28:  Evaluate the model
projects.locations.models.evaluations.list
Call
Step29:  Response
Step30:  Example output
Step31:  Response
Step32:  Example output
Step33:  Example output
Step34:  Example output
Step35:  Response
Step36:  Example output
Step37:  projects.locations.batchPredictionJobs.get
Call
Step38:  Response
Step39:  Example output
Step40:  Example output
Step41:  Example output
Step42:  Response
Step43:  Example output
Step44:  projects.locations.endpoints.deployModel
Request
Step45:  Example output
Step46:  Response
Step47:  Example output
Step48:  projects.locations.endpoints.predict
Prepare data item for online prediction
Step49:  Request
Step50:  Example output
Step51:  Response
Step52:  Example output
Step53:  Response
Step54:  Example output
<ASSISTANT_TASK:>
Python Code:
! pip3 install -U google-cloud-aiplatform --user
Explanation: Vertex AI AutoML text entity extractionn model
Installation
Install the latest (preview) version of Vertex SDK.
End of explanation
! pip3 install google-cloud-storage
Explanation: Install the Google cloud-storage library as well.
End of explanation
import os
if not os.getenv("AUTORUN"):
    # Automatically restart kernel after installs
    import IPython
    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)
Explanation: Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.
End of explanation
PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
    # Get your GCP project id from gcloud
    shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
    PROJECT_ID = shell_output[0]
    print("Project ID:", PROJECT_ID)
! gcloud config set project $PROJECT_ID
Explanation: Before you begin
GPU run-time
Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU
Set up your GCP project
The following steps are required, regardless of your notebook environment.
Select or create a GCP project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex APIs and Compute Engine APIs.
Google Cloud SDK is already installed in Google Cloud Notebooks.
Enter your project ID in the cell below. Then run the  cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.
Project ID
If you don't know your project ID, try to get your project ID using gcloud command by executing the second cell below.
End of explanation
REGION = "us-central1"  # @param {type: "string"}
Explanation: Region
You can also change the REGION variable, which is used for operations
throughout the rest of this notebook.  Below are regions supported for Vertex AI. We recommend when possible, to choose the region closest to you.
Americas: us-central1
Europe: europe-west4
Asia Pacific: asia-east1
You cannot use a Multi-Regional Storage bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see Region support for Vertex AI services
End of explanation
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
Explanation: Timestamp
If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.
End of explanation
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your Google Cloud account. This provides access
# to your Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# If on Vertex, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
    if "google.colab" in sys.modules:
        from google.colab import auth as google_auth
        google_auth.authenticate_user()
    # If you are running this tutorial in a notebook locally, replace the string
    # below with the path to your service account key and run this cell to
    # authenticate your Google Cloud account.
    else:
        %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json
    # Log in to your account on Google Cloud
    ! gcloud auth login
Explanation: Authenticate your GCP account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
Note: If you are on an Vertex notebook and run the cell, the cell knows to skip executing the authentication steps.
End of explanation
BUCKET_NAME = "[your-bucket-name]"  # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
    BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP
Explanation: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
End of explanation
! gsutil mb -l $REGION gs://$BUCKET_NAME
Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.
End of explanation
! gsutil ls -al gs://$BUCKET_NAME
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
import json
import os
import sys
import time
from google.cloud.aiplatform import gapic as aip
from google.protobuf import json_format
from google.protobuf.json_format import MessageToJson
from google.protobuf.struct_pb2 import Struct, Value
Explanation: Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
Import Vertex SDK
Import the Vertex SDK into our Python environment.
End of explanation
# API Endpoint
API_ENDPOINT = "us-central1-aiplatform.googleapis.com"
# Vertex AI location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION
Explanation: Vertex AI constants
Setup up the following constants for Vertex AI:
API_ENDPOINT: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.
PARENT: The Vertex AI location root path for dataset, model and endpoint resources.
End of explanation
# Text Dataset type
TEXT_SCHEMA = "google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml"
# Text Labeling type
IMPORT_SCHEMA_TEXT_EXTRACTION = "gs://google-cloud-aiplatform/schema/dataset/ioformat/text_extraction_io_format_1.0.0.yaml"
# Text Training task
TRAINING_TEXT_EXTRACTION_SCHEMA = "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_extraction_1.0.0.yaml"
Explanation: AutoML constants
Next, setup constants unique to AutoML Text Entity Extraction datasets and training:
Dataset Schemas: Tells the managed dataset service which type of dataset it is.
Data Labeling (Annotations) Schemas: Tells the managed dataset service how the data is labeled (annotated).
Dataset Training Schemas: Tells the Vertex AI Pipelines service the task (e.g., classification) to train the model for.
End of explanation
# client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}
def create_dataset_client():
    client = aip.DatasetServiceClient(client_options=client_options)
    return client
def create_model_client():
    client = aip.ModelServiceClient(client_options=client_options)
    return client
def create_pipeline_client():
    client = aip.PipelineServiceClient(client_options=client_options)
    return client
def create_endpoint_client():
    client = aip.EndpointServiceClient(client_options=client_options)
    return client
def create_prediction_client():
    client = aip.PredictionServiceClient(client_options=client_options)
    return client
def create_job_client():
    client = aip.JobServiceClient(client_options=client_options)
    return client
clients = {}
clients["dataset"] = create_dataset_client()
clients["model"] = create_model_client()
clients["pipeline"] = create_pipeline_client()
clients["endpoint"] = create_endpoint_client()
clients["prediction"] = create_prediction_client()
clients["job"] = create_job_client()
for client in clients.items():
    print(client)
IMPORT_FILE = "gs://cloud-samples-data/language/ucaip_ten_dataset.jsonl"
! gsutil cat $IMPORT_FILE | head -n 1
Explanation: Clients
The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).
You will use several clients in this tutorial, so set them all up upfront.
Dataset Service for managed datasets.
Model Service for managed models.
Pipeline Service for training.
Endpoint Service for deployment.
Job Service for batch jobs and custom training.
Prediction Service for serving. Note: Prediction has a different service endpoint.
End of explanation
DATA_SCHEMA = TEXT_SCHEMA
dataset = {
    "display_name": "ten_" + TIMESTAMP,
    "metadata_schema_uri": "gs://" + DATA_SCHEMA,
}
print(
    MessageToJson(
        aip.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__["_pb"]
    )
)
Explanation: Example output:
{'text_segment_annotations': [{'endOffset': 54, 'startOffset': 27, 'displayName': 'SpecificDisease'}, {'endOffset': 173, 'startOffset': 156, 'displayName': 'SpecificDisease'}, {'endOffset': 179, 'startOffset': 176, 'displayName': 'SpecificDisease'}, {'endOffset': 246, 'startOffset': 243, 'displayName': 'Modifier'}, {'endOffset': 340, 'startOffset': 337, 'displayName': 'Modifier'}, {'endOffset': 698, 'startOffset': 695, 'displayName': 'Modifier'}], 'textContent': '1301937\tMolecular basis of hexosaminidase A deficiency and pseudodeficiency in the Berks County Pennsylvania Dutch.\tFollowing the birth of two infants with Tay-Sachs disease ( TSD ) , a non-Jewish , Pennsylvania Dutch kindred was screened for TSD carriers using the biochemical assay . A high frequency of individuals who appeared to be TSD heterozygotes was detected ( Kelly et al . , 1975 ) . Clinical and biochemical evidence suggested that the increased carrier frequency was due to at least two altered alleles for the hexosaminidase A alpha-subunit . We now report two mutant alleles in this Pennsylvania Dutch kindred , and one polymorphism . One allele , reported originally in a French TSD patient ( Akli et al . , 1991 ) , is a GT-- &gt; AT transition at the donor splice-site of intron 9 . The second , a C-- &gt; T transition at nucleotide 739 ( Arg247Trp ) , has been shown by Triggs-Raine et al . ( 1992 ) to be a clinically benign " pseudodeficient " allele associated with reduced enzyme activity against artificial substrate . Finally , a polymorphism [ G-- &gt; A ( 759 ) ] , which leaves valine at codon 253 unchanged , is described  .\n '}
Create a dataset
projects.locations.datasets.create
Request
End of explanation
request = clients["dataset"].create_dataset(parent=PARENT, dataset=dataset)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "dataset": {
    "displayName": "ten_20210301154552",
    "metadataSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml"
  }
}
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
# The full unique ID for the dataset
dataset_id = result.name
# The short numeric ID for the dataset
dataset_short_id = dataset_id.split("/")[-1]
print(dataset_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/datasets/1309228077611483136",
  "displayName": "ten_20210301154552",
  "metadataSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml",
  "labels": {
    "aiplatform.googleapis.com/dataset_metadata_schema": "TEXT"
  },
  "metadata": {
    "dataItemSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/dataitem/text_1.0.0.yaml"
  }
}
End of explanation
LABEL_SCHEMA = IMPORT_SCHEMA_TEXT_EXTRACTION
import_config = {
    "gcs_source": {"uris": [IMPORT_FILE]},
    "import_schema_uri": LABEL_SCHEMA,
}
print(
    MessageToJson(
        aip.ImportDataRequest(name=dataset_id, import_configs=[import_config]).__dict__[
            "_pb"
        ]
    )
)
Explanation: projects.locations.datasets.import
Request
End of explanation
request = clients["dataset"].import_data(
    name=dataset_id, import_configs=[import_config]
)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/datasets/1309228077611483136",
  "importConfigs": [
    {
      "gcsSource": {
        "uris": [
          "gs://cloud-samples-data/language/ucaip_ten_dataset.jsonl"
        ]
      },
      "importSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/ioformat/text_extraction_io_format_1.0.0.yaml"
    }
  ]
}
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
TRAINING_SCHEMA = TRAINING_TEXT_EXTRACTION_SCHEMA
task = Value(
    struct_value=Struct(
        fields={
            "multi_label": Value(bool_value=False),
            "budget_milli_node_hours": Value(number_value=1000),
            "model_type": Value(string_value="CLOUD"),
            "disable_early_stopping": Value(bool_value=False),
        }
    )
)
training_pipeline = {
    "display_name": "ten_" + TIMESTAMP,
    "input_data_config": {"dataset_id": dataset_short_id},
    "model_to_upload": {"display_name": "ten_" + TIMESTAMP},
    "training_task_definition": TRAINING_SCHEMA,
    "training_task_inputs": task,
}
print(
    MessageToJson(
        aip.CreateTrainingPipelineRequest(
            parent=PARENT,
            training_pipeline=training_pipeline,
        ).__dict__["_pb"]
    )
)
Explanation: Example output:
{}
Train a model
projects.locations.trainingPipelines.create
Request
End of explanation
request = clients["pipeline"].create_training_pipeline(
    parent=PARENT, training_pipeline=training_pipeline
)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "trainingPipeline": {
    "displayName": "ten_20210301154552",
    "inputDataConfig": {
      "datasetId": "1309228077611483136"
    },
    "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_extraction_1.0.0.yaml",
    "trainingTaskInputs": {
      "budget_milli_node_hours": 1000.0,
      "multi_label": false,
      "model_type": "CLOUD",
      "disable_early_stopping": false
    },
    "modelToUpload": {
      "displayName": "ten_20210301154552"
    }
  }
}
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
# The full unique ID for the training pipeline
training_pipeline_id = request.name
# The short numeric ID for the training pipeline
training_pipeline_short_id = training_pipeline_id.split("/")[-1]
print(training_pipeline_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/trainingPipelines/4643220011912003584",
  "displayName": "ten_20210301154552",
  "inputDataConfig": {
    "datasetId": "1309228077611483136"
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_extraction_1.0.0.yaml",
  "trainingTaskInputs": {},
  "modelToUpload": {
    "displayName": "ten_20210301154552"
  },
  "state": "PIPELINE_STATE_PENDING",
  "createTime": "2021-03-01T15:55:29.352065Z",
  "updateTime": "2021-03-01T15:55:29.352065Z"
}
End of explanation
request = clients["pipeline"].get_training_pipeline(name=training_pipeline_id)
Explanation: projects.locations.trainingPipelines.get
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
while True:
    response = clients["pipeline"].get_training_pipeline(name=training_pipeline_id)
    if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:
        print("Training job has not completed:", response.state)
        if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:
            break
    else:
        model_id = response.model_to_upload.name
        print("Training Time:", response.end_time - response.start_time)
        break
    time.sleep(60)
print(model_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/trainingPipelines/4643220011912003584",
  "displayName": "ten_20210301154552",
  "inputDataConfig": {
    "datasetId": "1309228077611483136"
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_extraction_1.0.0.yaml",
  "trainingTaskInputs": {},
  "modelToUpload": {
    "displayName": "ten_20210301154552"
  },
  "state": "PIPELINE_STATE_PENDING",
  "createTime": "2021-03-01T15:55:29.352065Z",
  "updateTime": "2021-03-01T15:55:29.352065Z"
}
End of explanation
request = clients["model"].list_model_evaluations(parent=model_id)
Explanation: Evaluate the model
projects.locations.models.evaluations.list
Call
End of explanation
model_evaluations = [json.loads(MessageToJson(mel.__dict__["_pb"])) for mel in request]
# The evaluation slice
evaluation_slice = request.model_evaluations[0].name
print(json.dumps(model_evaluations, indent=2))
Explanation: Response
End of explanation
request = clients["model"].get_model_evaluation(name=evaluation_slice)
Explanation: Example output:
```
[
  {
    "name": "projects/116273516712/locations/us-central1/models/4400738115568795648/evaluations/7959028222912364544",
    "metricsSchemaUri": "gs://google-cloud-aiplatform/schema/modelevaluation/text_extraction_metrics_1.0.0.yaml",
    "metrics": {
      "confusionMatrix": {
        "rows": [
          [
            0.0,
            24.0,
            23.0,
            1.0,
            27.0
          ],
          [
            9.0,
            40.0,
            0.0,
            0.0,
            10.0
          ],
          [
            11.0,
            0.0,
            87.0,
            0.0,
            2.0
          ],
          [
            3.0,
            0.0,
            0.0,
            5.0,
            0.0
          ],
          [
            32.0,
            16.0,
            7.0,
            1.0,
            186.0
          ]
        ],
        "annotationSpecs": [
          {
            "displayName": "NULL"
          },
          {
            "id": "2041829376663748608",
            "displayName": "DiseaseClass"
          },
          {
            "displayName": "Modifier",
            "id": "4347672385877442560"
          },
          {
            "displayName": "CompositeMention",
            "id": "6653515395091136512"
          },
          {
            "id": "7806436899697983488",
            "displayName": "SpecificDisease"
          }
        ]
      },
      "confidenceMetrics": [
        {
          "precision": 0.74125874,
          "f1Score": 0.7589499,
          "recall": 0.7775061,
          "confidenceThreshold": 0.04
        },
        {
          "recall": 0.7457213,
          "confidenceThreshold": 0.96,
          "precision": 0.8333333,
          "f1Score": 0.7870968
        },
    # REMOVED FOR BREVITY
    {
      "f1Score": 0.7596154,
      "recall": 0.77261615,
      "confidenceThreshold": 0.44,
      "precision": 0.7470449
    }
  ]
},
"createTime": "2021-03-01T17:59:23.638307Z",
"sliceDimensions": [
  "annotationSpec"
]
}
]
```
projects.locations.models.evaluations.get
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
import json
import tensorflow as tf
test_item = 'Molecular basis of hexosaminidase A deficiency and pseudodeficiency in the Berks County Pennsylvania Dutch.\\tFollowing the birth of two infants with Tay-Sachs disease ( TSD ) , a non-Jewish , Pennsylvania Dutch kindred was screened for TSD carriers using the biochemical assay . A high frequency of individuals who appeared to be TSD heterozygotes was detected ( Kelly et al . , 1975 ) . Clinical and biochemical evidence suggested that the increased carrier frequency was due to at least two altered alleles for the hexosaminidase A alpha-subunit . We now report two mutant alleles in this Pennsylvania Dutch kindred , and one polymorphism . One allele , reported originally in a French TSD patient ( Akli et al . , 1991 ) , is a GT-- > AT transition at the donor splice-site of intron 9 . The second , a C-- > T transition at nucleotide 739 ( Arg247Trp ) , has been shown by Triggs-Raine et al . ( 1992 ) to be a clinically benign " pseudodeficient " allele associated with reduced enzyme activity against artificial substrate . Finally , a polymorphism [ G-- > A ( 759 ) ] , which leaves valine at codon 253 unchanged , is described'
gcs_test_item = "gs://" + BUCKET_NAME + "/test.txt"
with tf.io.gfile.GFile(gcs_test_item, "w") as f:
    f.write(test_item + "\n")
gcs_input_uri = "gs://" + BUCKET_NAME + "/test.jsonl"
with tf.io.gfile.GFile(gcs_input_uri, "w") as f:
    f.write(json.dumps({"content": gcs_test_item, "mime_type": "text/plain"}) + "\n")
! gsutil cat $gcs_input_uri
! gsutil cat $gcs_test_item
Explanation: Example output:
```
{
  "name": "projects/116273516712/locations/us-central1/models/4400738115568795648/evaluations/7959028222912364544",
  "metricsSchemaUri": "gs://google-cloud-aiplatform/schema/modelevaluation/text_extraction_metrics_1.0.0.yaml",
  "metrics": {
    "confusionMatrix": {
      "rows": [
        [
          0.0,
          24.0,
          23.0,
          1.0,
          27.0
        ],
        [
          9.0,
          40.0,
          0.0,
          0.0,
          10.0
        ],
        [
          11.0,
          0.0,
          87.0,
          0.0,
          2.0
        ],
        [
          3.0,
          0.0,
          0.0,
          5.0,
          0.0
        ],
        [
          32.0,
          16.0,
          7.0,
          1.0,
          186.0
        ]
      ],
      "annotationSpecs": [
        {
          "displayName": "NULL"
        },
        {
          "id": "2041829376663748608",
          "displayName": "DiseaseClass"
        },
        {
          "displayName": "Modifier",
          "id": "4347672385877442560"
        },
        {
          "id": "6653515395091136512",
          "displayName": "CompositeMention"
        },
        {
          "displayName": "SpecificDisease",
          "id": "7806436899697983488"
        }
      ]
    },
    "confidenceMetrics": [
      {
        "precision": 0.74125874,
        "recall": 0.7775061,
        "confidenceThreshold": 0.04,
        "f1Score": 0.7589499
      },
      {
        "f1Score": 0.7870968,
        "recall": 0.7457213,
        "confidenceThreshold": 0.96,
        "precision": 0.8333333
      },
  # REMOVED FOR BREVITY
  {
    "precision": 0.745283,
    "f1Score": 0.7587035,
    "recall": 0.77261615,
    "confidenceThreshold": 0.43
  },
  {
    "precision": 0.7470449,
    "recall": 0.77261615,
    "confidenceThreshold": 0.44,
    "f1Score": 0.7596154
  }
]
},
  "createTime": "2021-03-01T17:59:23.638307Z",
  "sliceDimensions": [
    "annotationSpec"
  ]
}
```
Make batch predictions
Make a batch prediction file
End of explanation
batch_prediction_job = {
    "display_name": "ten_" + TIMESTAMP,
    "model": model_id,
    "input_config": {
        "instances_format": "jsonl",
        "gcs_source": {"uris": [gcs_input_uri]},
    },
    "output_config": {
        "predictions_format": "jsonl",
        "gcs_destination": {
            "output_uri_prefix": "gs://" + f"{BUCKET_NAME}/batch_output/"
        },
    },
    "dedicated_resources": {
        "machine_spec": {"machine_type": "n1-standard-2", "accelerator_count": 0},
        "starting_replica_count": 1,
        "max_replica_count": 1,
    },
}
print(
    MessageToJson(
        aip.CreateBatchPredictionJobRequest(
            parent=PARENT, batch_prediction_job=batch_prediction_job
        ).__dict__["_pb"]
    )
)
Explanation: Example output:
{"content": "gs://migration-ucaip-trainingaip-20210301154552/test.txt", "mime_type": "text/plain"}
Molecular basis of hexosaminidase A deficiency and pseudodeficiency in the Berks County Pennsylvania Dutch.\tFollowing the birth of two infants with Tay-Sachs disease ( TSD ) , a non-Jewish , Pennsylvania Dutch kindred was screened for TSD carriers using the biochemical assay . A high frequency of individuals who appeared to be TSD heterozygotes was detected ( Kelly et al . , 1975 ) . Clinical and biochemical evidence suggested that the increased carrier frequency was due to at least two altered alleles for the hexosaminidase A alpha-subunit . We now report two mutant alleles in this Pennsylvania Dutch kindred , and one polymorphism . One allele , reported originally in a French TSD patient ( Akli et al . , 1991 ) , is a GT-- &gt; AT transition at the donor splice-site of intron 9 . The second , a C-- &gt; T transition at nucleotide 739 ( Arg247Trp ) , has been shown by Triggs-Raine et al . ( 1992 ) to be a clinically benign " pseudodeficient " allele associated with reduced enzyme activity against artificial substrate . Finally , a polymorphism [ G-- &gt; A ( 759 ) ] , which leaves valine at codon 253 unchanged , is described
projects.locations.batchPredictionJobs.create
Request
End of explanation
request = clients["job"].create_batch_prediction_job(
    parent=PARENT, batch_prediction_job=batch_prediction_job
)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "batchPredictionJob": {
    "displayName": "ten_20210301154552",
    "model": "projects/116273516712/locations/us-central1/models/4400738115568795648",
    "inputConfig": {
      "instancesFormat": "jsonl",
      "gcsSource": {
        "uris": [
          "gs://migration-ucaip-trainingaip-20210301154552/test.jsonl"
        ]
      }
    },
    "outputConfig": {
      "predictionsFormat": "jsonl",
      "gcsDestination": {
        "outputUriPrefix": "gs://migration-ucaip-trainingaip-20210301154552/batch_output/"
      }
    },
    "dedicatedResources": {
      "machineSpec": {
        "machineType": "n1-standard-2"
      },
      "startingReplicaCount": 1,
      "maxReplicaCount": 1
    }
  }
}
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
# The fully qualified ID for the batch job
batch_job_id = request.name
# The short numeric ID for the batch job
batch_job_short_id = batch_job_id.split("/")[-1]
print(batch_job_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/batchPredictionJobs/3588251799200464896",
  "displayName": "ten_20210301154552",
  "model": "projects/116273516712/locations/us-central1/models/4400738115568795648",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "gs://migration-ucaip-trainingaip-20210301154552/test.jsonl"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "gs://migration-ucaip-trainingaip-20210301154552/batch_output/"
    }
  },
  "state": "JOB_STATE_PENDING",
  "completionStats": {
    "incompleteCount": "-1"
  },
  "createTime": "2021-03-01T17:59:42.777083Z",
  "updateTime": "2021-03-01T17:59:42.777083Z"
}
End of explanation
request = clients["job"].get_batch_prediction_job(name=batch_job_id)
Explanation: projects.locations.batchPredictionJobs.get
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
while True:
    response = clients["job"].get_batch_prediction_job(name=batch_job_id)
    if response.state != aip.JobState.JOB_STATE_SUCCEEDED:
        print("The job has not completed:", response.state)
        if response.state == aip.JobState.JOB_STATE_FAILED:
            break
    else:
        folder = response.output_config.gcs_destination.output_uri_prefix[:-1]
        ! gsutil ls $folder/prediction*/*.jsonl
        ! gsutil cat $folder/prediction*/*.jsonl
        break
    time.sleep(60)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/batchPredictionJobs/3588251799200464896",
  "displayName": "ten_20210301154552",
  "model": "projects/116273516712/locations/us-central1/models/4400738115568795648",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "gs://migration-ucaip-trainingaip-20210301154552/test.jsonl"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "gs://migration-ucaip-trainingaip-20210301154552/batch_output/"
    }
  },
  "state": "JOB_STATE_PENDING",
  "completionStats": {
    "incompleteCount": "-1"
  },
  "createTime": "2021-03-01T17:59:42.777083Z",
  "updateTime": "2021-03-01T17:59:42.777083Z"
}
End of explanation
endpoint = {"display_name": "ten_" + TIMESTAMP}
print(
    MessageToJson(
        aip.CreateEndpointRequest(parent=PARENT, endpoint=endpoint).__dict__["_pb"]
    )
)
Explanation: Example output:
gs://migration-ucaip-trainingaip-20210301154552/batch_output/prediction-ten_20210301154552-2021-03-01T17:59:42.638222Z/predictions_00001.jsonl
{"instance":{"content":"gs://migration-ucaip-trainingaip-20210301154552/test.txt","mimeType":"text/plain"},"prediction":{"ids":["7806436899697983488","7806436899697983488","7806436899697983488","4347672385877442560","4347672385877442560","4347672385877442560"],"displayNames":["SpecificDisease","SpecificDisease","SpecificDisease","Modifier","Modifier","Modifier"],"textSegmentStartOffsets":["149","19","169","236","688","330"],"textSegmentEndOffsets":["165","45","171","238","690","332"],"confidences":[0.99957836,0.9995628,0.9995044,0.9993287,0.9993144,0.99927235]}}
Make online predictions
projects.locations.endpoints.create
Request
End of explanation
request = clients["endpoint"].create_endpoint(parent=PARENT, endpoint=endpoint)
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "endpoint": {
    "displayName": "ten_20210301154552"
  }
}
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
# The fully qualified ID for the endpoint
endpoint_id = result.name
# The short numeric ID for the endpoint
endpoint_short_id = endpoint_id.split("/")[-1]
print(endpoint_id)
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/endpoints/8916247652891361280"
}
End of explanation
deployed_model = {
    "model": model_id,
    "display_name": "ten_" + TIMESTAMP,
    "automatic_resources": {"min_replica_count": 1, "max_replica_count": 1},
}
traffic_split = {"0": 100}
print(
    MessageToJson(
        aip.DeployModelRequest(
            endpoint=endpoint_id,
            deployed_model=deployed_model,
            traffic_split=traffic_split,
        ).__dict__["_pb"]
    )
)
Explanation: projects.locations.endpoints.deployModel
Request
End of explanation
request = clients["endpoint"].deploy_model(
    endpoint=endpoint_id, deployed_model=deployed_model, traffic_split=traffic_split
)
Explanation: Example output:
{
  "endpoint": "projects/116273516712/locations/us-central1/endpoints/8916247652891361280",
  "deployedModel": {
    "model": "projects/116273516712/locations/us-central1/models/4400738115568795648",
    "displayName": "ten_20210301154552",
    "automaticResources": {
      "minReplicaCount": 1,
      "maxReplicaCount": 1
    }
  },
  "trafficSplit": {
    "0": 100
  }
}
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
# The unique ID for the deployed model
deployed_model_id = result.deployed_model.id
print(deployed_model_id)
Explanation: Example output:
{
  "deployedModel": {
    "id": "3958065938133155840"
  }
}
End of explanation
test_item = 'Molecular basis of hexosaminidase A deficiency and pseudodeficiency in the Berks County Pennsylvania Dutch.\\tFollowing the birth of two infants with Tay-Sachs disease ( TSD ) , a non-Jewish , Pennsylvania Dutch kindred was screened for TSD carriers using the biochemical assay . A high frequency of individuals who appeared to be TSD heterozygotes was detected ( Kelly et al . , 1975 ) . Clinical and biochemical evidence suggested that the increased carrier frequency was due to at least two altered alleles for the hexosaminidase A alpha-subunit . We now report two mutant alleles in this Pennsylvania Dutch kindred , and one polymorphism . One allele , reported originally in a French TSD patient ( Akli et al . , 1991 ) , is a GT-- > AT transition at the donor splice-site of intron 9 . The second , a C-- > T transition at nucleotide 739 ( Arg247Trp ) , has been shown by Triggs-Raine et al . ( 1992 ) to be a clinically benign " pseudodeficient " allele associated with reduced enzyme activity against artificial substrate . Finally , a polymorphism [ G-- > A ( 759 ) ] , which leaves valine at codon 253 unchanged , is described'
Explanation: projects.locations.endpoints.predict
Prepare data item for online prediction
End of explanation
instances_list = [{"content": test_item}]
instances = [json_format.ParseDict(s, Value()) for s in instances_list]
prediction_request = aip.PredictRequest(
    endpoint=endpoint_id,
)
prediction_request.instances.append(instances)
print(MessageToJson(prediction_request.__dict__["_pb"]))
Explanation: Request
End of explanation
request = clients["prediction"].predict(endpoint=endpoint_id, instances=instances)
Explanation: Example output:
{
  "endpoint": "projects/116273516712/locations/us-central1/endpoints/8916247652891361280",
  "instances": [
    [
      {
        "content": "Molecular basis of hexosaminidase A deficiency and pseudodeficiency in the Berks County Pennsylvania Dutch.\\tFollowing the birth of two infants with Tay-Sachs disease ( TSD ) , a non-Jewish , Pennsylvania Dutch kindred was screened for TSD carriers using the biochemical assay . A high frequency of individuals who appeared to be TSD heterozygotes was detected ( Kelly et al . , 1975 ) . Clinical and biochemical evidence suggested that the increased carrier frequency was due to at least two altered alleles for the hexosaminidase A alpha-subunit . We now report two mutant alleles in this Pennsylvania Dutch kindred , and one polymorphism . One allele , reported originally in a French TSD patient ( Akli et al . , 1991 ) , is a GT-- &gt; AT transition at the donor splice-site of intron 9 . The second , a C-- &gt; T transition at nucleotide 739 ( Arg247Trp ) , has been shown by Triggs-Raine et al . ( 1992 ) to be a clinically benign \" pseudodeficient \" allele associated with reduced enzyme activity against artificial substrate . Finally , a polymorphism [ G-- &gt; A ( 759 ) ] , which leaves valine at codon 253 unchanged , is described"
      }
    ]
  ]
}
Call
End of explanation
print(MessageToJson(request.__dict__["_pb"]))
Explanation: Response
End of explanation
request = clients["endpoint"].undeploy_model(
    endpoint=endpoint_id,
    deployed_model_id=deployed_model_id,
    traffic_split={},
)
Explanation: Example output:
{
  "predictions": [
    {
      "displayNames": [
        "SpecificDisease",
        "SpecificDisease",
        "SpecificDisease",
        "Modifier",
        "Modifier",
        "Modifier"
      ],
      "confidences": [
        0.9995627999305725,
        0.9995783567428589,
        0.9995043873786926,
        0.9993286728858948,
        0.999272346496582,
        0.9993144273757935
      ],
      "textSegmentStartOffsets": [
        19.0,
        149.0,
        169.0,
        236.0,
        330.0,
        688.0
      ],
      "ids": [
        "7806436899697983488",
        "7806436899697983488",
        "7806436899697983488",
        "4347672385877442560",
        "4347672385877442560",
        "4347672385877442560"
      ],
      "textSegmentEndOffsets": [
        46.0,
        166.0,
        172.0,
        239.0,
        333.0,
        691.0
      ]
    }
  ],
  "deployedModelId": "3958065938133155840"
}
projects.locations.endpoints.undeployModel
Call
End of explanation
result = request.result()
print(MessageToJson(result.__dict__["_pb"]))
Explanation: Response
End of explanation
delete_dataset = True
delete_model = True
delete_endpoint = True
delete_pipeline = True
delete_batchjob = True
delete_bucket = True
# Delete the dataset using the Vertex AI fully qualified identifier for the dataset
try:
    if delete_dataset:
        clients["dataset"].delete_dataset(name=dataset_id)
except Exception as e:
    print(e)
# Delete the model using the Vertex AI fully qualified identifier for the model
try:
    if delete_model:
        clients["model"].delete_model(name=model_id)
except Exception as e:
    print(e)
# Delete the endpoint using the Vertex AI fully qualified identifier for the endpoint
try:
    if delete_endpoint:
        clients["endpoint"].delete_endpoint(name=endpoint_id)
except Exception as e:
    print(e)
# Delete the training pipeline using the Vertex AI fully qualified identifier for the training pipeline
try:
    if delete_pipeline:
        clients["pipeline"].delete_training_pipeline(name=training_pipeline_id)
except Exception as e:
    print(e)
# Delete the batch job using the Vertex AI fully qualified identifier for the batch job
try:
    if delete_batchjob:
        clients["job"].delete_batch_prediction_job(name=batch_job_id)
except Exception as e:
    print(e)
if delete_bucket and "BUCKET_NAME" in globals():
    ! gsutil rm -r gs://$BUCKET_NAME
Explanation: Example output:
{}
Cleaning up
To clean up all GCP resources used in this project, you can delete the GCP
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial.
End of explanation
<END_TASK>