Loading...
No results found.

Apply your skills in Google Cloud console

Managing Machine Learning Projects with Google Cloud

Get access to 700+ labs and courses

Sentiment Analysis with Natural Language API

Lab 40 minutes universal_currency_alt 5 Credits show_chart Introductory
info This lab may incorporate AI tools to support your learning.
Get access to 700+ labs and courses

Overview

The Cloud Natural Language API lets you extract entities from text, perform sentiment and syntactic analysis, and classify text into categories.

Objectives

In this lab, you learn how to perform the following tasks:

  • Create a Natural Language API request and call the API

  • Run sentiment analysis on sample phrases using the Natural Language API

  • Perform linguistic analysis on text to create dependency parse trees

Setup and requirements

For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.

  1. Sign in to Qwiklabs using an incognito window.

  2. Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
    There is no pause feature. You can restart if needed, but you have to start at the beginning.

  3. When ready, click Start lab.

  4. Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.

  5. Click Open Google Console.

  6. Click Use another account and copy/paste credentials for this lab into the prompts.
    If you use other credentials, you'll receive errors or incur charges.

  7. Accept the terms and skip the recovery resource page.

Task 1. Create an API key

In this task, you generate an API key that will allow you to send, get, or pull requests when using the Natural Language API.

  1. In the Cloud Console, on the Navigation menu (Navigation menu), click APIs & Services > Credentials.

  2. Click Create credentials, and then click API key.

  3. Copy the generated API key, and then click Close.

Click Check my progress to verify the objective.

Create an API Key

Connect to SSH instance

In the next steps, you connect to the instance provisioned for you via SSH.

  1. In the Cloud Console, on the Navigation menu (Navigation menu), click Compute Engine. You should see a provisioned linux instance:

VM instances tabbed page with a linux instance listed

  1. Click on the SSH button. You will be brought to an interactive shell.

  2. In the command line, execute the following command, replacing <YOUR_API_KEY> with the key you just copied:

export API_KEY=<YOUR_API_KEY>

Task 2. Sentiment analysis with the Natural Language API

In this task, you submit a request written in JSON—a specific programming language. The Natural Language API lets you perform sentiment analysis on a block of text.

  1. Open the request.json file by executing the following command:

nano request.json
  1. Replace the code in request.json with the following sentiment:

{ "document":{ "type":"PLAIN_TEXT", "content":"The sweater fits well and I love the material too. I’m buying one for my sister! " }, "encodingType": "UTF8" }
  1. Press CTRL+O, ENTER to save the file, and press CTRL+X to exit nano.

Click Check my progress to verify the objective.

Make an Sentiment Analysis Request Note: You can repeat this lab and use alternative phrases such as:

  • Hard to find simple sweats without writing or stripes etc. Nice casual workout clothes.
  • This is a total scam. The package did not even arrive.
  • Alice was very professional and projected a calm manner throughout the workshop.
  • I was expecting a major shift after the session but nothing of the sort.
  1. Send the request to the API's analyzeSentiment endpoint by executing the following command:

curl "https://language.googleapis.com/v1/documents:analyzeSentiment?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json > result.json
  1. Check the response type by executing the following command:

cat result.json

Your response should look like this:

{ "documentSentiment": { "magnitude": 1.9, "score": 0.9 }, "language": "en", "sentences": [ { "text": { "content": "The sweater fits well and I love the material too.", "beginOffset": 0 }, "sentiment": { "magnitude": 0.9, "score": 0.9 } }, { "text": { "content": "I’m buying one for my sister!", "beginOffset": 51 }, "sentiment": { "magnitude": 0.9, "score": 0.9 } } ] }

Notice that you get two types of sentiment values: sentiment for the document as a whole, and sentiment broken down by sentence. The sentiment method returns two values:

  • score - is a number from -1.0 to 1.0 indicating how positive or negative the statement is.
  • magnitude - is a number ranging from 0 to infinity that represents the weight of sentiment expressed in the statement, regardless of being positive or negative.

Longer blocks of text with heavily weighted statements have higher magnitude values. The score for the first sentence is positive (0.9), whereas the score for the second sentence is also (0.9).

Click Check my progress to verify the objective.

Check the Sentiment Analysis response

Task 3. Analyzing entity sentiment

In this task, you use the Natural Language API to obtain sentiment for each entity in the text. The Natural Language API can not only provide details on the entire text document, but can also break down sentiment by the entities in the text, for example:

I liked the yoga instructor but the room was really dusty.

In this case, getting a sentiment score for the entire sentence as you did above might not be so useful. If this was a yoga class review and there were hundreds of reviews for the same class, you'd want to know exactly which things people liked and didn't like in their reviews. Fortunately, the Natural Language API has a method that lets you get the sentiment for each entity in the text, called analyzeEntitySentiment. Let's see how it works!

  1. Open the request.json file by typing the following command:

nano request.json
  1. Replace the code in request.json with the following sentiment:

{ "document":{ "type":"PLAIN_TEXT", "content":"I liked the yoga instructor but the room was really dusty." }, "encodingType": "UTF8" }
  1. Press CTRL+O, ENTER to save the file, and press CTRL+X to exit nano.

  2. Call the analyzeEntitySentiment endpoint by typing the following command:

curl "https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json

In the response, you receive two entity objects: one for "yoga instructor" and one for "room". See below for the full JSON response:

{ "entities": [ { "name": "yoga instructor", "type": "PERSON", "metadata": {}, "salience": 0.51064336, "mentions": [ { "text": { "content": "yoga instructor", "beginOffset": 12 }, "type": "COMMON", "sentiment": { "magnitude": 0.1, "score": 0.1 } } ], "sentiment": { "magnitude": 0.1, "score": 0.1 } }, { "name": "room", "type": "LOCATION", "metadata": {}, "salience": 0.48935664, "mentions": [ { "text": { "content": "room", "beginOffset": 36 }, "type": "COMMON", "sentiment": { "magnitude": 0, "score": 0 } } ], "sentiment": { "magnitude": 0, "score": 0 } } ], "language": "en" }

You can see that the score returned for "instructor" was 0.1, whereas "room" got a score of 0. Cool! You also may notice that there are two sentiment objects returned for each entity. If either of these terms were mentioned more than once, the API would return a different sentiment score and magnitude for each mention, along with an aggregate sentiment for the entity.

Task 4. Analyzing syntax and parts of speech

In this task, you use syntactic analysis, another of the Natural Language API's method, to dive deeper into the linguistic details of the text. analyzeSyntax extracts linguistic information, breaking up the given text into a series of sentences and tokens (generally, word boundaries), to provide further analysis on those tokens. For each word in the text, the API tells you the word's part of speech (noun, verb, adjective, etc.) and how it relates to other words in the sentence (Is it the root verb? A modifier?).

You can try this out with a simple sentence. This JSON request will be similar to the ones above, with the addition of a features key. This tells the API to perform syntax annotation.

  1. Open the request.json file by typing the following command:

nano request.json
  1. Replace the code in request.json with the following sentiment:

{ "document":{ "type":"PLAIN_TEXT", "content": "Joanne Rowling is a British novelist, screenwriter and film producer." }, "encodingType": "UTF8" }
  1. Press CTRL+O, ENTER to save the file, and press CTRL+X to exit nano.

  2. Call the API's analyzeSyntax method by typing the following command:

curl "https://language.googleapis.com/v1/documents:analyzeSyntax?key=${API_KEY}" \ -s -X POST -H "Content-Type: application/json" --data-binary @request.json

The response should return an object like the one below for each token in the sentence:

{ "text": { "content": "Joanne", "beginOffset": 0 }, "partOfSpeech": { "tag": "NOUN", "aspect": "ASPECT_UNKNOWN", "case": "CASE_UNKNOWN", "form": "FORM_UNKNOWN", "gender": "GENDER_UNKNOWN", "mood": "MOOD_UNKNOWN", "number": "SINGULAR", "person": "PERSON_UNKNOWN", "proper": "PROPER", "reciprocity": "RECIPROCITY_UNKNOWN", "tense": "TENSE_UNKNOWN", "voice": "VOICE_UNKNOWN" }, "dependencyEdge": { "headTokenIndex": 1, "label": "NN" }, "lemma": "Joanne" },

This is how the response breaks down:

  • partOfSpeech tells you that "Joanne" is a noun.
  • dependencyEdge includes data that you can use to create a dependency parse tree of the text. Essentially, this is a diagram showing how words in a sentence relate to each other. A dependency parse tree for the sentence above would look like this:

Dependency parse tree for the sentence: Joanne Rowling is a British novelist, screenwriter and film producer.

Note: You can create your own dependency parse trees in the browser with the Natural Language demo.
  • headTokenIndex is the index of the token that has an arc pointing at "Joanne". Think of each token in the sentence as a word in an array.

  • headTokenIndex of 1 for "Joanne" refers to the word "Rowling", which it is connected to in the tree. The label NN (short for noun compound modifier) describes the word's role in the sentence. "Joanne" modifies "Rowling", the subject of the sentence.

  • lemma is the canonical form of the word. For example, the words run, runs, ran, and running all have a lemma of run. The lemma value is useful for tracking occurrences of a word in a large piece of text over time.

Task 5. Review

In this lab you performed text analysis using the Cloud Natural Language API to analyze sentiment, and perform syntax annotation. You created a Natural Language API request and called the API. You also ran sentiment analysis on sample phrases using the Natural Language API, before finally performing linguistic analysis on text to create dependency parse trees.

End your lab

When you have completed your lab, click End Lab. Qwiklabs removes the resources you’ve used and cleans the account for you.

You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.

The number of stars indicates the following:

  • 1 star = Very dissatisfied
  • 2 stars = Dissatisfied
  • 3 stars = Neutral
  • 4 stars = Satisfied
  • 5 stars = Very satisfied

You can close the dialog box if you don't want to provide feedback.

For feedback, suggestions, or corrections, please use the Support tab.

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Previous Next

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

Use private browsing

  1. Copy the provided Username and Password for the lab
  2. Click Open console in private mode

Sign in to the Console

  1. Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
  2. Accept the terms, and skip the recovery resource page
  3. Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project

This content is not currently available

We will notify you via email when it becomes available

Great!

We will contact you via email if it becomes available

One lab at a time

Confirm to end all existing labs and start this one

Use private browsing to run the lab

Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
Preview