감정 분석 가이드

대상

이 가이드를 사용하여 Google Cloud Natural Language API를 신속하게 살펴보고 활용하여 애플리케이션 개발을 시작할 수 있습니다. 가이드는 기본적인 프로그래밍에 익숙한 독자를 대상으로 제작되었지만 프로그래밍 관련 지식이 많지 않더라도 진행에는 무리가 없습니다. 이 가이드를 마치면 참조 문서를 사용하여 기본적인 애플리케이션을 만들 수 있습니다.

이 가이드에서는 Python 코드를 사용하여 Natural Language API 애플리케이션을 설명합니다. 이 가이드의 목적은 Python 클라이언트 라이브러리를 설명하는 것이 아니라 Natural Language API를 호출하는 방법을 설명하는 것입니다. 자바 및 Node.js로 작성된 애플리케이션도 원리적으로 비슷합니다. 다른 언어의 샘플에 대해서는 Natural Language API 샘플(이 가이드에 있는 샘플 포함)을 참조하세요.

기본 요건

이 가이드에는 몇 가지 기본 요건이 있습니다.

문서 감정 분석

이 가이드에서는 텍스트의 감정 분석을 수행하는 analyzeSentiment 요청을 사용하여 기본 Natural Language API 애플리케이션을 알아봅니다. 감정 분석은 텍스트 내에서 표현되는 전체적인 태도(긍정적 또는 부정적)를 판단하며 이는 숫자 scoremagnitude 값으로 표현됩니다. 이 개념에 대한 자세한 내용은 자연어 기본사항을 참조하세요.

우선 코드 전체를 보겠습니다. (코드의 간략함을 보여주기 위해 이 코드에서는 대부분의 메모가 삭제되었습니다. 코드를 살펴보는 과정에서 더 많은 메모가 제공됩니다.)

Python용 Google Cloud Natural Language 클라이언트 라이브러리 설치 및 사용에 대한 자세한 내용은 Natural Language API 클라이언트 라이브러리를 참조하세요.
"""Demonstrates how to make a simple call to the Natural Language API."""

import argparse

from google.cloud import language_v1

def print_result(annotations):
    score = annotations.document_sentiment.score
    magnitude = annotations.document_sentiment.magnitude

    for index, sentence in enumerate(annotations.sentences):
        sentence_sentiment = sentence.sentiment.score
        print(f"Sentence {index} has a sentiment score of {sentence_sentiment}")

    print(f"Overall Sentiment: score of {score} with magnitude of {magnitude}")
    return 0

def analyze(movie_review_filename):
    """Run a sentiment analysis request on text within a passed filename."""
    client = language_v1.LanguageServiceClient()

    with open(movie_review_filename) as review_file:
        # Instantiates a plain text document.
        content = review_file.read()

    document = language_v1.Document(
        content=content, type_=language_v1.Document.Type.PLAIN_TEXT
    )
    annotations = client.analyze_sentiment(request={"document": document})

    # Print the results
    print_result(annotations)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        "movie_review_filename",
        help="The filename of the movie review you'd like to analyze.",
    )
    args = parser.parse_args()

    analyze(args.movie_review_filename)

이 간단한 애플리케이션은 다음과 같은 작업을 수행합니다.

  • 애플리케이션을 실행하는 데 필요한 라이브러리 가져오기
  • 텍스트 파일을 받아 main() 함수에 전달하기
  • 텍스트 파일을 읽고 서비스에 요청을 보내기
  • 서비스의 응답을 파싱하여 사용자에게 표시하기

이 단계는 아래에서 자세히 살펴보겠습니다.

라이브러리 가져오기

Python용 Google Cloud Natural Language 클라이언트 라이브러리 설치 및 사용에 대한 자세한 내용은 Natural Language API 클라이언트 라이브러리를 참조하세요.
import argparse

from google.cloud import language_v1

표준 라이브러리인 argparse를 가져와 애플리케이션이 입력 파일 이름을 인수로 받아들일 수 있도록 합니다.

Cloud Natural Language API를 사용하기 위해서는 google-cloud-language 라이브러리에서 language 모듈도 가져오는 것이 좋습니다. types 모듈은 요청을 생성하는 데 필요한 클래스를 포함하고 있습니다.

애플리케이션 실행

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        "movie_review_filename",
        help="The filename of the movie review you'd like to analyze.",
    )
    args = parser.parse_args()

    analyze(args.movie_review_filename)

이제 전달된 인수를 텍스트 파일 이름에 파싱하고 analyze() 함수로 전달합니다.

API 인증

Natural Language API 서비스와 통신하기 전에 이전에 획득한 사용자 인증 정보를 사용하여 서비스를 인증해야 합니다. 애플리케이션 내에서 사용자 인증 정보를 얻는 가장 간단한 방법은 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하는 것입니다. 기본적으로 ADC는 GOOGLE_APPLICATION_CREDENTIALS 환경 파일에서 사용자 인증 정보를 얻으려고 시도합니다. 환경 파일은 서비스 계정의 JSON 키 파일을 가리키도록 설정해야 합니다. 빠른 시작에서 ADC를 사용하려면 서비스 계정 및 환경을 설정한 상태여야 합니다. 자세한 내용은 서비스 계정 설정을 참조하세요.

Python용 Google Cloud 클라이언트 라이브러리에서는 자동으로 애플리케이션 기본 사용자 인증 정보를 사용합니다.

요청 생성

이제 Natural Language API 서비스가 준비되었으니 LanguageServiceClient 인스턴스의 analyze_sentiment 메서드를 호출하여 서비스에 액세스할 수 있습니다.

클라이언트 라이브러리는 API에 대한 요청 및 응답 세부정보를 포함합니다. 이러한 요청의 특정 구조에 대한 자세한 내용은 Natural Language API 참조를 확인하세요.

Python용 Google Cloud Natural Language 클라이언트 라이브러리 설치 및 사용에 대한 자세한 내용은 Natural Language API 클라이언트 라이브러리를 참조하세요.
def analyze(movie_review_filename):
    """Run a sentiment analysis request on text within a passed filename."""
    client = language_v1.LanguageServiceClient()

    with open(movie_review_filename) as review_file:
        # Instantiates a plain text document.
        content = review_file.read()

    document = language_v1.Document(
        content=content, type_=language_v1.Document.Type.PLAIN_TEXT
    )
    annotations = client.analyze_sentiment(request={"document": document})

    # Print the results
    print_result(annotations)

이 코드 스니펫은 다음 작업을 수행합니다.

  1. LanguageServiceClient 인스턴스를 클라이언트로 인스턴스화합니다.
  2. 텍스트 데이터가 들어있는 파일 이름을 변수로 읽습니다.
  3. 파일의 콘텐츠로 Document 객체를 인스턴스화합니다.
  4. 클라이언트의 analyze_sentiment 메서드를 호출합니다.

응답 파싱

def print_result(annotations):
    score = annotations.document_sentiment.score
    magnitude = annotations.document_sentiment.magnitude

    for index, sentence in enumerate(annotations.sentences):
        sentence_sentiment = sentence.sentiment.score
        print(f"Sentence {index} has a sentiment score of {sentence_sentiment}")

    print(f"Overall Sentiment: score of {score} with magnitude of {magnitude}")
    return 0

응답을 검토하여 각 문장에 대한 감정 score 값과 전체 검토에 대한 전반적인 scoremagnitude 값을 추출하여 사용자에게 표시합니다.

샘플 실행

샘플 실행을 위해 영화 'Bladerunner'에 대한 일련의 (가짜) 영화 리뷰를 테스트해 보겠습니다.

  1. Google Cloud Storage에서 샘플을 다운로드합니다.

    gsutil cp gs://cloud-samples-tests/natural-language/sentiment-samples.tgz .
    

    일반적으로 gsutil은 gcloud CLI의 일부로 설치됩니다. 최신 버전의 gcloud CLI를 설치하려면 gcloud CLI 문서를 참조하세요.

  2. 샘플을 압축 해제하면 'reviews' 폴더가 생성됩니다.

    gunzip sentiment-samples.tgz
    tar -xvf sentiment-samples.tar
    
  3. 지정된 파일 중 하나에서 감정 분석을 실행합니다.

    python sentiment_analysis.py reviews/bladerunner-pos.txt
    Sentence 0 has a sentiment score of 0.8
    Sentence 1 has a sentiment score of 0.9
    Sentence 2 has a sentiment score of 0.8
    Sentence 3 has a sentiment score of 0.2
    Sentence 4 has a sentiment score of 0.1
    Sentence 5 has a sentiment score of 0.4
    Sentence 6 has a sentiment score of 0.3
    Sentence 7 has a sentiment score of 0.4
    Sentence 8 has a sentiment score of 0.2
    Sentence 9 has a sentiment score of 0.9
    Overall Sentiment: score of 0.5 with magnitude of 5.5
    

위의 예시에서는 리뷰가 상대적으로 긍정적(0.5점)이고 상대적으로 감정적(5.5)이라는 점을 나타냅니다.

다른 예를 분석하면 아래에 표시된 것과 비슷한 값이 나타납니다.

python sentiment_analysis.py reviews/bladerunner-neg.txt
...
Overall Sentiment: score of -0.6 with magnitude of 3.3

python sentiment_analysis.py reviews/bladerunner-mixed.txt
...
Overall Sentiment: score of 0 with magnitude of 4.7

python sentiment_analysis.py reviews/bladerunner-neutral.txt
...
Overall Sentiment: score of -0.1 with magnitude of 1.8

긍정, 부정과 상관없이 정서적인 감정이 적은 '중립적인' 경우를 제외하고 모든 크기(magnitude)가 서로 비슷하다는 것을 알 수 있습니다. 즉, 정서적으로 의미 있는 감정이 비교적 동일한 양이 나타납니다. 감정 점수 및 크기, 이러한 값을 해석하는 방법에 대한 자세한 내용은 감정 분석 값 해석을 참조하세요.

더 많은 데이터를 통해 감정 분석을 수행하려면 Stanford에서 제공하는 IMDB 영화 리뷰 데이터 세트를 사용하세요. 영화 리뷰를 찾는 방법은 다음과 같습니다.

  1. Large Movie Review 데이터 세트를 다운로드합니다.
  2. 작업 디렉터리에 파일을 압축 해제합니다. 영화 리뷰는 traintest 데이터 디렉터리 안에 posneg 디렉터리로 구분되어 있으며 각 텍스트 파일에는 하나의 영화 리뷰가 포함되어 있습니다.
  3. 영화 리뷰 텍스트 파일에서 sentiment_analysis.py 도구를 실행합니다.

수고하셨습니다. Google Cloud Natural Language API를 사용하여 추론 작업을 처음 수행했습니다.