pizzaplanet

[2019 머신러닝 스터디 잼] Entity and Sentiment Analysis with the Natural Language API 본문

AI

[2019 머신러닝 스터디 잼] Entity and Sentiment Analysis with the Natural Language API

scio 2019. 2. 13. 11:55

입문반의 마지막 트랙 Entity and Sentiment Analysis with the Natural Language API




GSP038





Overview


Cloud Natural Language API를 사용하여 텍스트에서 Entity 추출, 감정 및 구문 분석, 텍스트 카테고라이징 등을 할 수 있다.


퀵랩 2 [2019 머신러닝 스터디 잼] Cloud Natural Language API: Qwik Start와 비슷하다.

수행 내용이 더 많고, gcloud CLI 대신 curl을 이용하여 API를 호출한다.




What you'll do


  • Natural Language API 요청 생성 및 curl을 이용한 API 호출
  • NL API를 사용한 텍스트 감정 분석 및 Entity 추출 실행
  • NL API를 사용한 언어 분석(문법, 품사) 실행
  • 영어 이외 언어에 대해 NL API 수행



Create An API Key


[2019 머신러닝 스터디 잼] Google Cloud Speech API: Qwik Start의 Create An API Key 부분을 참고하여 API Key를 생성 및 export 하자




Make an Entity Analysis Request


1. Entity 분석을 위한 json 파일을 생성해주자


1
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ vim entityAnalysisRequest.json
cs


1
2
3
4
5
6
7
{
  "document":{
    "type":"PLAIN_TEXT",
    "content":"Joanne Rowling, who writes under the pen names J. K. Rowling and Robert Galbraith, is a British novelist and screenwriter who wrote the Harry Potter fantasy series."
  },
  "encodingType":"UTF8"
}
cs


document

    • type : 'PLAIN_TEXT' or 'HTML' 방식으로 가능하다.
    • content : 분석 대상이 될 텍스트. 예제에선 문장을 바로 넘겼지만 gcsContenUri를 사용하여 Cloud Storage에 저장된 파일을 보낼 수도 있다.

encodingType : 텍스트 인코딩 유형.




Call the Natural Language API


1. curl을 이용하여 Entity 분석을 수행해보자.


1
2
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ curl "https://language.googleapis.com/v1/documents:analyzeEntities?key=${API_KEY}" \
>   --X POST -"Content-Type: application/json" --data-binary @entityAnalysisRequest.json
cs


  • documents:analyzeEntities : 개체 분석을 하겠다
  • --data-binary @entityAnalysisRequest.json : curl은 POST 시 데이터를 text 취급하므로 binary 데이터가 깨질 수 있다. 제대로 전송하기 위해 --data-binary 옵션을 이용한다.
  • -s : silent mode. 진행 내역이나 메시지 등을 출력하지 않는다. HTTP response code만 가져올 경우 좋다.
  • -X : 기본 값을 POST 형식으로 설정
  • -H : 특정한 HTTP Header를 설정해서 보내야 할 경우(EX: json 등) 사용한다.
  • key=${API_KEY} : 앞서 발급 받았던 API Key를 환경변수에 등록했었다. 그 API Key를 사용하겠다는 뜻.


2. response가 왔다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{
  "entities": [
     {
      "name""Robert Galbraith",
      "type""PERSON",
      "metadata": {
        "mid""/m/042xh",
        "wikipedia_url""https://en.wikipedia.org/wiki/J._K._Rowling"
      },
      "salience"0.7980405,
      "mentions": [
        {
          "text": {
            "content""Joanne Rowling",
            "beginOffset"0
          },
          "type""PROPER"
        },
        {
          "text": {
            "content""Rowling",
            "beginOffset"53
          },
          "type""PROPER"
        },
        {
          "text": {
            "content""novelist",
            "beginOffset"96
          },
          "type""COMMON"
        },
        {
          "text": {
            "content""Robert Galbraith",
            "beginOffset"65
          },
          "type""PROPER"
        }
      ]
    },
 
    ...
  ],
    "language" : "en"
}
cs


퀵랩 2와 동일한 리스폰스 형태를 띄고 있다.

  • entities : 여러 개체에 대한 정보를 담고 있다.
  • language : 탐지한 언어
  • name : 개체 이름(전체 텍스트 중 분석 대상이 된 부분 문자열)
  • type : 개체의 타입. PERSON? LOCATION? EVENT?
  • metadata : 연관된 위키피디아 정보가 있을 시 포함됨
  • salience : 전체 텍스트에서 해당 개체가 중요한 정도(max 1.0)
  • mentions : 전체 텍스트에서 이 개체와 동일한 개체가 발견된 다른 지점(index)에 대한 정보 목록




Sentiment analysis with the Natural Language API


Entity 추출 이외에도 NL API를 사용하여 감정 분석을 수행할 수 있다. 해보자.


1. Sentiment 분석을 위한 json 파일을 생성해주자


1
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ vim sentimentAnalysisRequest.json
cs


1
2
3
4
5
6
7
{
  "document":{
    "type":"PLAIN_TEXT",
    "content":"Harry Potter is the best book. I think everyone should read it."
  },
  "encodingType""UTF8"
}
cs



2. curl을 이용하여 호출해보자


1
2
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ curl "https://language.googleapis.com/v1/documents:analyzeSentiment?key=${API_KEY}" \
>   --X POST -"Content-Type: application/json" --data-binary @sentimentAnalysisRequest.json
cs


  • documents:analyzeSentiment : 감정 분석을 수행하겠다.

3. response가 왔다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
  "documentSentiment": {
    "magnitude"0.8,
    "score"0.4
  },
  "language""en",
  "sentences": [
    {
      "text": {
        "content""Harry Potter is the best book.",
        "beginOffset"0
      },
      "sentiment": {
        "magnitude"0.7,
        "score"0.7
      }
    },
    {
      "text": {
        "content""I think everyone should read it.",
        "beginOffset"31
      },
      "sentiment": {
        "magnitude"0.1,
        "score"0.1
      }
    }
  ]
}
cs


  • score : -1.0 ~ 1.0 의 값을 가진다. -1.0은 최고 부정, 1.0은 최고 긍정, 0은 중립
  • magnitude : 0 ~ 무한대 값. 감정에 대한 가중치를 나타낸다. 





Analyzing entity sentiment


문장 전체에 대한 감정 점수를 얻는 것이 유용하지 않을 때가 있다. 대량의 리뷰에서 사람들이 좋아하는 것, 좋아하지 않는 것을 정확히 알고 싶을 것이다. 예를 들어, "스시는 맛있었지만, 서비스는 최악이었다" 와 같이 한 문장 안에서 부분에 따라 긍정 부정이 나뉘는 경우가 있다. 이를 가능케 해준다.


1. 요청을 위한 json 파일 생성


1
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ vim analyzingEntitySentimentRequest.json
cs


1
2
3
4
5
6
7
{
  "document":{
    "type":"PLAIN_TEXT",
    "content":"I liked the sushi but the service was terrible."
  },
  "encodingType""UTF8"
}
cs



2. 호출 


1
2
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ curl "https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=${API_KEY}" \
>   --X POST -"Content-Type: application/json" --data-binary @analyzingEntitySentimentRequest.json
cs


  • documents:analyzeEntitySentiment : Entity Sentiment 분석 수행


3. response


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
{
  "entities": [
    {
      "name""sushi",
      "type""CONSUMER_GOOD",
      "metadata": {},
      "salience"0.51064336,
      "mentions": [
        {
          "text": {
            "content""sushi",
            "beginOffset"12
          },
          "type""COMMON",
          "sentiment": {
            "magnitude"0.9,
            "score"0.9
          }
        }
      ],
      "sentiment": {
        "magnitude"0.9,
        "score"0.9
      }
    },
    {
      "name""service",
      "type""OTHER",
      "metadata": {},
      "salience"0.48935664,
      "mentions": [
        {
          "text": {
            "content""service",
            "beginOffset"26
          },
          "type""COMMON",
          "sentiment": {
            "magnitude"0.9,
            "score"-0.9
          }
        }
      ],
      "sentiment": {
        "magnitude"0.9,
        "score"-0.9
      }
    }
  ],
  "language""en"
}
cs


  • sushi는 score 0.9(긍정), magnitude 0.9(가중치)를 가지고 있다.
  • service는 score 0.9(부정). magnitude 0.9(가중치)를 가지고 있다.




Analyzing syntax and parts of speech


문장의 각 단어에 대해 품사(명사, 동사, 형용사 등)와 다른 단어와 어떻게 관련되는지 알려줍니다.


1. json 생성


1
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ vim analyzingSyntaxAndPartsOfSpeechRequest.json
cs


1
2
3
4
5
6
7
{
  "document":{
    "type":"PLAIN_TEXT",
    "content""Joanne Rowling is a British novelist, screenwriter and film producer."
  },
  "encodingType""UTF8"
}
cs



2. 호출


1
2
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ curl "https://language.googleapis.com/v1/documents:analyzeSyntax?key=${API_KEY}" \
>   --X POST -"Content-Type: application/json" --data-binary @analyzingSyntaxAndPartsOfSpeechRequest.json
cs


  • documents:analyzeSyntax : Syntax 분석 수행

3. response


아주 긴 response가 올 것이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
      "text": {
        "content""is",
        "beginOffset"15
      },
      "partOfSpeech": {
        "tag""VERB",
        "aspect""ASPECT_UNKNOWN",
        "case""CASE_UNKNOWN",
        "form""FORM_UNKNOWN",
        "gender""GENDER_UNKNOWN",
        "mood""INDICATIVE",
        "number""SINGULAR",
        "person""THIRD",
        "proper""PROPER_UNKNOWN",
        "reciprocity""RECIPROCITY_UNKNOWN",
        "tense""PRESENT",
        "voice""VOICE_UNKNOWN"
      },
      "dependencyEdge": {
        "headTokenIndex"2,
        "label""ROOT"
      },
      "lemma""be"
    },
cs


  • content : 분석 대상의 토큰
  • partOfSpeech
    • tag : 품사 정보
  • dependencyEdge : 의존성 파스 트리(dependency parse tree)를 생성하기 위해 사용될 수 있는 정보. 문장 내 단어가 서로 어떻게 연관되어 있는지 볼 수 있음. https://cloud.google.com/natural-language/ 서비스로 만들어 볼 수 있다. https://cloud.google.com/natural-language/docs/reference/rest/v1/Token#Label ⇒ 레이블 종류 나열 문서
    • headTokenIndex : 이 토큰이 의존성 파스 트리에서 Joanne를 가리키는 인덱스 정보
    • label : 문장에서 해당 토큰의 역할. ROOT는 어근을 의미.
  • lemma : 원형 (is, was, were, am, are의 원형은 be)



< 의존성 파스 트리 구성 예 >




Multilingual natural language processing


영어 이외의 언어도 지원하고 있다. (지원 목록)

일본어를 사용해보자.


1. json 생성


1
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ vim MNLPRequest.json
cs


1
2
3
4
5
6
{
  "document":{
    "type":"PLAIN_TEXT",
    "content":"日本のグーグルのオフィスは、東京の六本木ヒルズにあります"
  }
}
cs



2. 호출


1
2
google2440848_student@cloudshell:~ (qwiklabs-gcp-49f176ca84b2af86)$ curl "https://language.googleapis.com/v1/documents:analyzeEntities?key=${API_KEY}" \
>   --X POST -"Content-Type: application/json" --data-binary MNLPRequest.json
cs


  • documents:analyzeEntities : Entities 분석을 수행

3. response

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{
  "entities": [
    {
      "name""日本",
      "type""LOCATION",
      "metadata": {
        "mid""/m/03_3d",
        "wikipedia_url""https://en.wikipedia.org/wiki/Japan"
      },
      "salience"0.23854347,
      "mentions": [
        {
          "text": {
            "content""日本",
            "beginOffset"0
          },
          "type""PROPER"
        }
      ]
    },
    {
      "name""グーグル",
      "type""ORGANIZATION",
      "metadata": {
        "mid""/m/045c7b",
        "wikipedia_url""https://en.wikipedia.org/wiki/Google"
      },
      "salience"0.21155767,
      "mentions": [
        {
          "text": {
            "content""グーグル",
            "beginOffset"9
          },
          "type""PROPER"
        }
      ]
    },
    ...
  ]
  "language""ja"
}
cs





진행 영상





참고


[구글 머신러닝 스터디잼 가이드라인]

[Entity and Sentiment Analysis with the Natural Language API]












Comments