Home > Articles

This chapter is from the book

Cloud NLP and Sentiment Analysis

All three of the dominant cloud providers—AWS, GCP, and Azure—have solid NLP engines that can be called via an API. In this section, NLP examples on all three clouds will be explored. Additionally, a real-world production AI pipeline for NLP pipeline will be created on AWS using serverless technology.

NLP on Azure

Microsoft Cognitive Services have a Text Analytics API that has language detection, key phrase extraction, and sentiment analysis. In Figure 11.2, the endpoint is created so API calls can be made. This example will take a negative collection of movie reviews from the Cornell Computer Science Data Set on Movie Reviews (http://www.cs.cornell.edu/people/pabo/movie-review-data/) and use it to walk through the API.

Figure 11.2

Figure 11.2 Microsoft Azure Cognitive Services API

First, imports are done in this first block in Jupyter Notebook.

In [1]: import requests
   ...: import os
   ...: import pandas as pd
   ...: import seaborn as sns
   ...: import matplotlib as plt
   ...:

Next, an API key is taken from the environment. This API key was fetched from the console shown in Figure 11.2 under the section keys and was exported as an environmental variable, so it isn’t hard-coded into code. Additionally, the text API URL that will be used later is assigned to a variable.

In [4]: subscription_key=os.environ.get("AZURE_API_KEY")
In [5]: text_analytics_base_url =   ...: https://eastus.api.cognitive.microsoft.com/        text/analytics/v2.0/

Next, one of the negative reviews is formatted in the way the API expects.

In [9]: documents = {"documents":[]}
   ...: path = "../data/review_polarity/        txt_sentoken/neg/cv000_29416.txt"
   ...: doc1 = open(path, "r")
   ...: output = doc1.readlines()
   ...: count = 0
   ...: for line in output:
   ...:     count +=1
   ...:     record = {"id": count, "language": "en", "text": line}
   ...:     documents["documents"].append(record)
   ...:
   ...: #print it out
   ...: documents

The data structure with the following shape is created.

Out[9]:
{'documents': [{'id': 1,
   'language': 'en',
   'text': 'plot : two teen couples go to a         church party , drink and then drive . \n'},
  {'id': 2, 'language': 'en',
 'text': 'they get into an accident . \n'},
  {'id': 3,
   'language': 'en',
   'text': 'one of the guys dies , but his girlfriend continues to see him in her life, and has nightmares . \n'},
  {'id': 4, 'language': 'en', 'text': "what's the deal ? \n"},
  {'id': 5,
   'language': 'en',

Finally, the sentiment analysis API is used to score the individual documents.

{'documents': [{'id': '1', 'score': 0.5},
  {'id': '2', 'score': 0.13049307465553284},
  {'id': '3', 'score': 0.09667149186134338},
  {'id': '4', 'score': 0.8442018032073975},
  {'id': '5', 'score': 0.808459997177124

At this point, the return scores can be converted into a Pandas DataFrame to do some EDA. It isn’t a surprise that the median value of the sentiments for a negative review are 0.23 on a scale of 0 to 1, where 1 is extremely positive and 0 is extremely negative.

In [11]: df = pd.DataFrame(sentiments['documents'])

In [12]: df.describe()
Out[12]:
           score
count  35.000000
mean    0.439081
std     0.316936
min     0.037574
25%     0.159229
50%     0.233703
75%     0.803651
max     0.948562

This is further explained by doing a density plot. Figure 11.3 shows a majority of highly negative sentiments.

Figure 11.3

Figure 11.3 Density Plot of Sentiment Scores

NLP on GCP

There is a lot to like about the Google Cloud Natural Language API (https://cloud.google.com/natural-language/docs/how-to). One of the convenient features of the API is that you can use it in two different ways: analyzing sentiment in a string, and also analyzing sentiment from Google Cloud Storage. Google Cloud also has a tremendously powerful command-line tool that makes it easy to explore their API. Finally, it has some fascinating AI APIs, some of which will be explored in this chapter: analyzing sentiment, analyzing entities, analyzing syntax, analyzing entity sentiment, and classifying content.

Exploring the Entity API

Using the command-line gcloud API is a great way to explore what one of the APIs does. In the example, a phrase is sent via the command line about LeBron James and the Cleveland Cavaliers.

→  gcloud ml language analyze-entities --content="LeBron James plays for the Cleveland Cavaliers."
{
  "entities": [
    {
      "mentions": [
        {
          "text": {
            "beginOffset": 0,
            "content": "LeBron James"
          },
          "type": "PROPER"
        }
      ],
      "metadata": {
        "mid": "/m/01jz6d",
        "wikipedia_url": "https://en.wikipedia.org/wiki/LeBron_James"
      },
      "name": "LeBron James",
      "salience": 0.8991045,
      "type": "PERSON"
    },
    {
      "mentions": [
        {
          "text": {
            "beginOffset": 27,
            "content": "Cleveland Cavaliers"
          },
          "type": "PROPER"
        }
      ],
      "metadata": {
        "mid": "/m/0jm7n",
        "wikipedia_url": "https://en.wikipedia.org/wiki/Cleveland_Cavaliers"
      },
      "name": "Cleveland Cavaliers",
      "salience": 0.100895494,
      "type": "ORGANIZATION"
    }
  ],
  "language": "en"
}

A second way to explore the API is to use Python. To get an API key and authenticate, you need to follow the instructions (https://cloud.google.com/docs/authentication/getting-started). Then, launch the Jupyter Notebook in the same shell as the GOOGLE_APPLICATION_CREDENTIALS variable is exported:

→  ✗ export GOOGLE_APPLICATION_CREDENTIALS=        /Users/noahgift/cloudai-65b4e3299be1.json
→  ✗ jupyter notebook

Once this authentication process is complete, the rest is straightforward. First, the python language api must be imported (This can be installed via pip if it isn’t already: pip install --upgrade google-cloud-language.)

In [1]: # Imports the Google Cloud client library
   ...: from google.cloud import language
   ...: from google.cloud.language import enums
   ...: from google.cloud.language import types

Next, a phrase is sent to the API and entity metadata is returned with an analysis.

In [2]: text = "LeBron James plays for the Cleveland Cavaliers."
   ...: client = language.LanguageServiceClient()
   ...: document = types.Document(
   ...:         content=text,
   ...:         type=enums.Document.Type.PLAIN_TEXT)
   ...: entities = client.analyze_entities(document).entities
   ...:

The output has a similar look and feel to the command-line version, but it comes back as a Python list.

[name: "LeBron James"
type: PERSON
metadata {
  key: "mid"
  value: "/m/01jz6d"
}
metadata {
  key: "wikipedia_url"
  value: "https://en.wikipedia.org/wiki/LeBron_James"
}
salience: 0.8991044759750366
mentions {
  text {
    content: "LeBron James"
    begin_offset: -1
  }
  type: PROPER
}
, name: "Cleveland Cavaliers"
type: ORGANIZATION
metadata {
  key: "mid"
  value: "/m/0jm7n"
}
metadata {
  key: "wikipedia_url"
  value: "https://en.wikipedia.org/wiki/Cleveland_Cavaliers"
}
salience: 0.10089549422264099
mentions {
  text {
    content: "Cleveland Cavaliers"
    begin_offset: -1
  }
  type: PROPER
}
]

A few of the takeaways are that this API could be easily merged with some of the other explorations done in Chapter 6, “Predicting Social-Media Influence in the NBA.” It wouldn’t be hard to imagine creating an AI application that found extensive information about social influencers by using these NLP APIs as a starting point. Another takeaway is that the command line given to you by the GCP Cognitive APIs is quite powerful.

Production Serverless AI Pipeline for NLP on AWS

One thing AWS does well, perhaps better than any of the “big three” clouds, is make it easy to create production applications that are easy to write and manage. One of their “game changer” innovations is AWS Lambda. It is available to both orchestrate pipelines and serve our HTTP endpoints, like in the case of chalice. In Figure 11.4, a real-world production pipeline is described for creating an NLP pipeline.

Figure 11.4

Figure 11.4 Production Serverless NLP Pipeline on AWS

To get started with AWS sentiment analysis, some libraries need to be imported.

In [1]: import pandas as pd
   ...: import boto3
   ...: import json

Next, a simple test is created.

In [5]: comprehend = boto3.client(service_name='comprehend')
   ...: text = "It is raining today in Seattle"
   ...: print('Calling DetectSentiment')
   ...: print(json.dumps(comprehend.detect_sentiment(Text=text, LanguageCode='en'), sort_keys=True, indent=4))
   ...:
   ...: print('End of DetectSentiment\n')
   ...:

The output shows a “SentimentScore.”

Calling DetectSentiment
{
    "ResponseMetadata": {
        "HTTPHeaders": {
            "connection": "keep-alive",
            "content-length": "164",
            "content-type": "application/x-amz-json-1.1",
            "date": "Mon, 05 Mar 2018 05:38:53 GMT",
            "x-amzn-requestid": "7d532149-2037-11e8-b422-3534e4f7cfa2"
        },
        "HTTPStatusCode": 200,
        "RequestId": "7d532149-2037-11e8-b422-3534e4f7cfa2",
        "RetryAttempts": 0
    },
    "Sentiment": "NEUTRAL",
    "SentimentScore": {
        "Mixed": 0.002063251566141844,
        "Negative": 0.013271247036755085,
        "Neutral": 0.9274052977561951,
        "Positive": 0.057260122150182724
    }
}
End of DetectSentiment

Now, in a more realistic example, we’ll use the previous “negative movie reviews document” from the Azure example. The document is read in.

In [6]: path = "/Users/noahgift/Desktop/review_polarity/txt_sentoken/neg/cv000_29416.txt"
   ...: doc1 = open(path, "r")
   ...: output = doc1.readlines()
   ...:

Next, one of the “documents” (rember each line is a document according to NLP APIs) is scored.

In [7]: print(json.dumps(comprehend.detect_sentiment(Text=output[2], LanguageCode='en'), sort_keys=True, inden
   ...: t=4))

{
    "ResponseMetadata": {
        "HTTPHeaders": {
            "connection": "keep-alive",
            "content-length": "158",
            "content-type": "application/x-amz-json-1.1",
            "date": "Mon, 05 Mar 2018 05:43:25 GMT",
            "x-amzn-requestid": "1fa0f6e8-2038-11e8-ae6f-9f137b5a61cb"
        },
        "HTTPStatusCode": 200,
        "RequestId": "1fa0f6e8-2038-11e8-ae6f-9f137b5a61cb",
        "RetryAttempts": 0
    },
    "Sentiment": "NEUTRAL",
    "SentimentScore": {
        "Mixed": 0.1490383893251419,
        "Negative": 0.3341641128063202,
        "Neutral": 0.468740850687027,
        "Positive": 0.04805663228034973
    }
}

It’s no surprise that that document had a negative sentiment score since it was previously scored this way. Another interesting thing this API can do is to score all of the documents inside as one giant score. Basically, it gives the median sentiment value. Here is what that looks like.

In [8]: whole_doc = ', '.join(map(str, output))

In [9]: print(json.dumps(comprehend.detect_sentiment(Text=whole_doc, LanguageCode='en'), sort_keys=True, inden
   ...: t=4))
{
    "ResponseMetadata": {
        "HTTPHeaders": {
            "connection": "keep-alive",
            "content-length": "158",
            "content-type": "application/x-amz-json-1.1",
            "date": "Mon, 05 Mar 2018 05:46:12 GMT",
            "x-amzn-requestid": "8296fa1a-2038-11e8-a5b9-b5b3e257e796"
        },
    "Sentiment": "MIXED",
    "SentimentScore": {
        "Mixed": 0.48351600766181946,
        "Negative": 0.2868672013282776,
        "Neutral": 0.12633098661899567,
        "Positive": 0.1032857820391655
    }
}='en'), sort_keys=True, inden
   ...: t=4))

An interesting takeaway is that the AWS API has some hidden tricks up its sleeve and has a nuisance that is missing from the Azure API. In the previous Azure example, the Seaborn output showed that, indeed, there was a bimodal distribution with a minority of reviews liking the movie and a majority disliking the movie. The way AWS presents the results as “mixed” sums this up quite nicely.

The only things left to do is to create a simple chalice app that will take the scored inputs that are written to Dynamo and serve them out. Here is what that looks like.

from uuid import uuid4
import logging
import time

from chalice import Chalice
import boto3

from boto3.dynamodb.conditions import Key
from pythonjsonlogger import jsonlogger

#APP ENVIRONMENTAL VARIABLES
REGION = "us-east-1"
APP = "nlp-api"
NLP_TABLE = "nlp-table"

#intialize logging
log = logging.getLogger("nlp-api")
LOGHANDLER = logging.StreamHandler()  
FORMMATTER = jsonlogger.JsonFormatter()
LOGHANDLER.setFormatter(FORMMATTER)
log.addHandler(LOGHANDLER)
log.setLevel(logging.INFO)

app = Chalice(app_name='nlp-api')
app.debug = True

def dynamodb_client():
    """Create Dynamodb Client"""

    extra_msg = {"region_name": REGION, "aws_service": "dynamodb"}
    client = boto3.client('dynamodb', region_name=REGION)
    log.info("dynamodb CLIENT connection initiated", extra=extra_msg)
    return client

def dynamodb_resource():
    """Create Dynamodb Resource"""

    extra_msg = {"region_name": REGION, "aws_service": "dynamodb"}
    resource = boto3.resource('dynamodb', region_name=REGION)
    log.info("dynamodb RESOURCE connection initiated",          extra=extra_msg)
    return resource

def create_nlp_record(score):
    """Creates nlp Table Record

    """

    db = dynamodb_resource()
    pd_table = db.Table(NLP_TABLE)
    guid = str(uuid4())
    res = pd_table.put_item(
        Item={
            'guid': guid,
            'UpdateTime' : time.asctime(),
            'nlp-score': score
        }
    )
    extra_msg = {"region_name": REGION, "aws_service": "dynamodb"}
    log.info(f"Created NLP Record with result{res}", extra=extra_msg)
    return guid

def query_nlp_record():
    """Scans nlp table and retrieves all records"""
    
    db = dynamodb_resource()
    extra_msg = {"region_name": REGION, "aws_service": "dynamodb",
        "nlp_table":NLP_TABLE}
    log.info(f"Table Scan of NLP table", extra=extra_msg)
    pd_table = db.Table(NLP_TABLE)
    res = pd_table.scan()
    records = res['Items']
    return records

@app.route('/')
def index():
    """Default Route"""
    
    return {'hello': 'world'}

@app.route("/nlp/list")
def nlp_list():
    """list nlp scores"""

    extra_msg = {"region_name": REGION,
        "aws_service": "dynamodb",
        "route":"/nlp/list"}
    log.info(f"List NLP Records via route", extra=extra_msg)    
    res = query_nlp_record()
    return res

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020