Files
model_garden/notebooks/community/migration/UJ8 legacy AutoML Natural Language - Text Sentiment Analysis.ipynb
T

45 KiB

In [ ]:
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

AutoML text sentiment analysis

Installation

Install the latest version of AutoML SDK.

In [ ]:
! pip3 install google-cloud-automl

Install the Google cloud-storage library as well.

In [ ]:
! pip3 install google-cloud-storage

Restart the Kernel

Once you've installed the AutoML SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.

In [ ]:
import os

if not os.getenv("AUTORUN"):
    # Automatically restart kernel after installs
    import IPython

    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)

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.

  1. Select or create a GCP project. When you first create an account, you get a $300 free credit towards your compute/storage costs.

  2. Make sure that billing is enabled for your project.

  3. Enable the AutoML APIs and Compute Engine APIs.

  4. Google Cloud SDK is already installed in AutoML Notebooks.

  5. 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.

In [ ]:
PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
In [ ]:
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)
In [ ]:
! gcloud config set project $PROJECT_ID

Region

You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for AutoML. 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 AutoML. Not all regions provide support for all AutoML services. For the latest support per region, see Region support for AutoML services

In [ ]:
REGION = "us-central1"  # @param {type: "string"}

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.

In [ ]:
from datetime import datetime

TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")

Authenticate your GCP account

If you are using AutoML Notebooks, your environment is already authenticated. Skip this step.

Note: If you are on an AutoML notebook and run the cell, the cell knows to skip executing the authentication steps.

In [ ]:
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

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.

In [ ]:
BUCKET_NAME = "[your-bucket-name]"  # @param {type:"string"}
In [ ]:
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
    BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP

Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.

In [ ]:
! gsutil mb -l $REGION gs://$BUCKET_NAME

Finally, validate access to your Cloud Storage bucket by examining its contents:

In [ ]:
! gsutil ls -al gs://$BUCKET_NAME

Set up variables

Next, set up some variables used throughout the tutorial.

Import libraries and define constants

Import AutoML SDK

Import the AutoM SDK into our Python environment.

In [ ]:
import json
import os
import sys
import time

from google.cloud import automl
from google.protobuf.json_format import MessageToJson
from google.protobuf.struct_pb2 import Value

AutoML constants

Setup up the following constants for AutoML:

  • PARENT: The AutoM location root path for dataset, model and endpoint resources.
In [ ]:
# AutoM location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION

Clients

The AutoML 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 (AutoML).

You will use several clients in this tutorial, so set them all up upfront.

In [ ]:
def automl_client():
    return automl.AutoMlClient()


def perdictions_client():
    return automl.PredictionServiceClient()


def operations_client():
    return automl.AutoMlClient()._transport.operations_client


clients = {}
clients["automl"] = automl_client()
clients["predictions"] = perdictions_client()
clients["operations"] = operations_client()

for client in clients.items():
    print(client)
In [ ]:
import tensorflow as tf

IMPORT_FILE = "gs://cloud-samples-data/language/claritin.csv"
with tf.io.gfile.GFile(IMPORT_FILE, "r") as f:
    content = f.readlines()

IMPORT_FILE = "gs://" + BUCKET_NAME + "/claritin.csv"
with tf.io.gfile.GFile(IMPORT_FILE, "w") as f:
    for line in content:
        f.write(",".join(line.split(",")[0:-1]) + "\n")
In [ ]:
! gsutil cat $IMPORT_FILE | head -n 10

Example output:

@freewrytin God is way too good for Claritin,2
I need Claritin. So bad. When did I become cursed with allergies?,3
Thank god for Claritin.,4
"And what's worse is that I reached my 3-day limit on the nose spray yesterday, which means I have to rely on Claritin.",2
Time to take some Claritin or Allegra or something. I need my voice,3
Oh my RT @imsydneycharles: I just want it to be on record somewhere that I took Claritin and Benadryl together...just in case I pass out,2
Bouta take a Claritin _‰Ûª‰Û_‰Ûª_‰ÛªÌâ FML !!,3
Commander Loratadine Generic A Sarcelles: Commander Loratadine Generic A Sarcelles Claritin =‰Ûª_‰Ûª__ http://t.co/mOleL8AM,2
"Zyrtec, Claritin, Suddafed, Nasal Spray.. I feel like a drug addict taking these Allergy medicine. Please Allergy season.. DISAPPEAR!!",1
"‰Ûª_‰Ûª_‰ÛªÕ@SheLovesThatD: If she has allergies, give her the Claritin D.‰Ûª_‰Ûª_Ì_å @Sweeno_thakid41 @B_Original16 @luke_CYwalker14",3

Create a dataset

Request

In [ ]:
dataset = {
    "display_name": "claritin_" + TIMESTAMP,
    "text_sentiment_dataset_metadata": {"sentiment_max": 4},
}


print(
    MessageToJson(
        automl.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__["_pb"]
    )
)

Example output:

{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "dataset": {
    "displayName": "claritin_20210304132912",
    "textSentimentDatasetMetadata": {
      "sentimentMax": 4
    }
  }
}

Call

In [ ]:
request = clients["automl"].create_dataset(parent=PARENT, dataset=dataset)

Response

In [ ]:
result = request.result()

print(MessageToJson(result.__dict__["_pb"]))

Example output:

{
  "name": "projects/116273516712/locations/us-central1/datasets/TST1994716952680988672"
}
In [ ]:
# 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)

Request

In [ ]:
input_config = {"gcs_source": {"input_uris": [IMPORT_FILE]}}

print(
    MessageToJson(
        automl.ImportDataRequest(name=dataset_id, input_config=input_config).__dict__[
            "_pb"
        ]
    )
)

Example output:

{
  "name": "projects/116273516712/locations/us-central1/datasets/TST1994716952680988672",
  "inputConfig": {
    "gcsSource": {
      "inputUris": [
        "gs://migration-ucaip-trainingaip-20210304132912/claritin.csv"
      ]
    }
  }
}

Call

In [ ]:
request = clients["automl"].import_data(name=dataset_id, input_config=input_config)

Response

In [ ]:
result = request.result()

print(MessageToJson(result))

Example output:

{}

Train a model

Request

In [ ]:
model = {
    "display_name": "claritin_" + TIMESTAMP,
    "dataset_id": dataset_short_id,
    "text_sentiment_model_metadata": {},
}

print(
    MessageToJson(automl.CreateModelRequest(parent=PARENT, model=model).__dict__["_pb"])
)

Example output:

{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "model": {
    "displayName": "claritin_20210304132912",
    "datasetId": "TST1994716952680988672",
    "textSentimentModelMetadata": {}
  }
}

Call

In [ ]:
request = clients["automl"].create_model(parent=PARENT, model=model)

Response

In [ ]:
result = request.result()

print(MessageToJson(result.__dict__["_pb"]))

Example output:

{
  "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272"
}
In [ ]:
# The full unique ID for the training pipeline
model_id = result.name
# The short numeric ID for the training pipeline
model_short_id = model_id.split("/")[-1]

print(model_short_id)

Evaluate the model

Call

In [ ]:
request = clients["automl"].list_model_evaluations(parent=model_id, filter="")

Response

In [ ]:
model_evaluations = [json.loads(MessageToJson(me.__dict__["_pb"])) for me in request]
# The evaluation slice
evaluation_slice = request.model_evaluation[0].name

print(json.dumps(model_evaluations, indent=2))

Example output:

[
  {
    "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272/modelEvaluations/54870628009945864",
    "annotationSpecId": "8301667931964571648",
    "createTime": "2021-03-04T17:15:51.851420Z",
    "textSentimentEvaluationMetrics": {
      "precision": 0.33333334,
      "recall": 0.16666667,
      "f1Score": 0.22222222
    },
    "displayName": "4"
  },
  {
    "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272/modelEvaluations/1597159550285093673",
    "annotationSpecId": "1384138904323489792",
    "createTime": "2021-03-04T17:15:51.851420Z",
    "textSentimentEvaluationMetrics": {
      "precision": 0.5,
      "recall": 0.296875,
      "f1Score": 0.37254903
    },
    "displayName": "1"
  },
  {
    "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272/modelEvaluations/3521790980763365687",
    "createTime": "2021-03-04T17:15:51.851420Z",
    "evaluatedExampleCount": 452,
    "textSentimentEvaluationMetrics": {
      "precision": 0.6238938,
      "recall": 0.6238938,
      "f1Score": 0.6238938,
      "meanAbsoluteError": 0.47566372,
      "meanSquaredError": 0.69690263,
      "linearKappa": 0.41007927,
      "quadraticKappa": 0.45938763,
      "confusionMatrix": {
        "annotationSpecId": [
          "7148746427357724672",
          "1384138904323489792",
          "5995824922750877696",
          "3689981913537183744",
          "8301667931964571648"
        ],
        "row": [
          {
            "exampleCount": [
              2,
              4,
              1,
              1,
              1
            ]
          },
          {
            "exampleCount": [
              3,
              19,
              14,
              28,
              0
            ]
          },
          {
            "exampleCount": [
              0,
              7,
              67,
              63,
              1
            ]
          },
          {
            "exampleCount": [
              1,
              8,
              19,
              191,
              4
            ]
          },
          {
            "exampleCount": [
              0,
              0,
              0,
              15,
              3
            ]
          }
        ],
        "displayName": [
          "0",
          "1",
          "2",
          "3",
          "4"
        ]
      }
    }
  },
  {
    "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272/modelEvaluations/3727703410992997127",
    "annotationSpecId": "3689981913537183744",
    "createTime": "2021-03-04T17:15:51.851420Z",
    "textSentimentEvaluationMetrics": {
      "precision": 0.6409396,
      "recall": 0.85650223,
      "f1Score": 0.7332054
    },
    "displayName": "3"
  },
  {
    "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272/modelEvaluations/4692810493650008310",
    "annotationSpecId": "7148746427357724672",
    "createTime": "2021-03-04T17:15:51.851420Z",
    "textSentimentEvaluationMetrics": {
      "precision": 0.33333334,
      "recall": 0.22222222,
      "f1Score": 0.26666668
    },
    "displayName": "0"
  },
  {
    "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272/modelEvaluations/8390011688796741170",
    "annotationSpecId": "5995824922750877696",
    "createTime": "2021-03-04T17:15:51.851420Z",
    "textSentimentEvaluationMetrics": {
      "precision": 0.6633663,
      "recall": 0.48550725,
      "f1Score": 0.5606694
    },
    "displayName": "2"
  }
]

Call

In [ ]:
request = clients["automl"].get_model_evaluation(name=evaluation_slice)

Response

In [ ]:
print(MessageToJson(request.__dict__["_pb"]))

Example output:

{
  "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272/modelEvaluations/54870628009945864",
  "annotationSpecId": "8301667931964571648",
  "createTime": "2021-03-04T17:15:51.851420Z",
  "textSentimentEvaluationMetrics": {
    "precision": 0.33333334,
    "recall": 0.16666667,
    "f1Score": 0.22222222
  },
  "displayName": "4"
}

Make batch predictions

Make the batch input file

To request a batch of predictions from AutoML Video, create a CSV file that lists the Cloud Storage paths to the videos that you want to annotate. You can also specify a start and end time to tell AutoML Video to only annotate a segment (segment-level) of the video. The start time must be zero or greater and must be before the end time. The end time must be greater than the start time and less than or equal to the duration of the video. You can also use inf to indicate the end of a video.

In [ ]:
import tensorflow as tf

gcs_input_uri = "gs://" + BUCKET_NAME + "/test.csv"
with tf.io.gfile.GFile(gcs_input_uri, "w") as f:
    item_1 = "gs://cloud-samples-data/language/sentiment-positive.txt"
    ! gsutil cp $item_1 gs://$BUCKET_NAME
    f.write("gs://" + BUCKET_NAME + "/sentiment-positive.txt" + "\n")

    item_2 = "gs://cloud-samples-data/language/sentiment-negative.txt"
    ! gsutil cp $item_2 gs://$BUCKET_NAME
    f.write("gs://" + BUCKET_NAME + "/sentiment-negative.txt")

! gsutil cat $gcs_input_uri

Example output:

gs://migration-ucaip-trainingaip-20210304132912/sentiment-positive.txt
gs://migration-ucaip-trainingaip-20210304132912/sentiment-negative.txt

Request

In [ ]:
input_config = {"gcs_source": {"input_uris": [gcs_input_uri]}}

output_config = {
    "gcs_destination": {"output_uri_prefix": "gs://" + f"{BUCKET_NAME}/batch_output/"}
}

print(
    MessageToJson(
        automl.BatchPredictRequest(
            name=model_id, input_config=input_config, output_config=output_config
        ).__dict__["_pb"]
    )
)

Example output:

{
  "name": "projects/116273516712/locations/us-central1/models/TST4078882474816438272",
  "inputConfig": {
    "gcsSource": {
      "inputUris": [
        "gs://migration-ucaip-trainingaip-20210304132912/test.csv"
      ]
    }
  },
  "outputConfig": {
    "gcsDestination": {
      "outputUriPrefix": "gs://migration-ucaip-trainingaip-20210304132912/batch_output/"
    }
  }
}

Call

In [ ]:
request = clients["predictions"].batch_predict(
    name=model_id, input_config=input_config, output_config=output_config
)

Response

In [ ]:
result = request.result()

print(MessageToJson(result.__dict__["_pb"]))

Example output:

{}

Make online predictions

Prepare data item for online prediction

In [ ]:
test_data = ! gsutil cat $IMPORT_FILE | head -n1

test_item = str(test_data[0]).split(",")[0]
test_label = str(test_data[0]).split(",")[1]

print((test_item, test_label))

Example output:

('@freewrytin God is way too good for Claritin', '2')

Call

In [ ]:
request = clients["automl"].deploy_model(name=model_id)

Response

Warning:
Output truncated. This notebook contains too many cells to display efficiently.