正在加载…
未找到任何结果。

在 Google Cloud 控制台中运用您的技能

Managing Machine Learning Projects with Google Cloud

访问 700 多个实验和课程

Sentiment Analysis with Natural Language API

实验 40 分钟 universal_currency_alt 5 积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
访问 700 多个实验和课程

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.

上一步 下一步

准备工作

  1. 实验会创建一个 Google Cloud 项目和一些资源,供您使用限定的一段时间
  2. 实验有时间限制,并且没有暂停功能。如果您中途结束实验,则必须重新开始。
  3. 在屏幕左上角,点击开始实验即可开始

使用无痕浏览模式

  1. 复制系统为实验提供的用户名密码
  2. 在无痕浏览模式下,点击打开控制台

登录控制台

  1. 使用您的实验凭证登录。使用其他凭证可能会导致错误或产生费用。
  2. 接受条款,并跳过恢复资源页面
  3. 除非您已完成此实验或想要重新开始,否则请勿点击结束实验,因为点击后系统会清除您的工作并移除该项目

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

一次一个实验

确认结束所有现有实验并开始此实验

使用无痕浏览模式运行实验

请使用无痕模式或无痕式浏览器窗口运行此实验。这可以避免您的个人账号与学生账号之间发生冲突,这种冲突可能导致您的个人账号产生额外费用。
预览