感情分析のチュートリアル

対象

このチュートリアルは、Google Cloud Natural Language API を使用するアプリケーションの調査と開発をすぐに開始できるように作られています。基本的なプログラミングについて理解されている方を対象としていますが、プログラミングの深い知識がなくても、チュートリアルに沿って学習できるようになっています。このチュートリアルを終了すると、リファレンス ドキュメントを使用して独自の基本的なアプリケーションを作成できるようになります。

このチュートリアルでは、Python コードを使用した Natural Language API アプリケーションを使用します。ここでの目的は、Python クライアント ライブラリについて説明することではなく、Natural Language API を呼び出す方法を説明することです。Java や Node.js のアプリケーションも基本的にはこれと同様です。その他の言語のサンプル(チュートリアル内で使用するこのサンプルを含む)については、Natural Language API のサンプルをご覧ください。

事前準備

このチュートリアルでは次の事前準備が必要です。

ドキュメントの感情分析

このチュートリアルでは、analyzeSentiment リクエストを使用してテキストの感情分析を実行する基本的な Natural Language API アプリケーションについて説明します。感情分析は、全体的な態度(ポジティブかネガティブか)を特定する分析で、分析の結果は scoremagnitude の数値で表されます(これらの概念の詳細については、Natural Language API の基本をご覧ください)。

まずコード全体を示します(このコードのコメントのほとんどは削除されています。これは、コードそのものは単純であることを示すためです。コードについて説明していく中で、コメントを追加で示します)。

Google Cloud Natural Language の Python 用クライアント ライブラリのインストールと使用についての詳細は、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() 関数に渡す
  • テキスト ファイルを読み取り、サービスへのリクエストを作成する
  • サービスからのレスポンスを解析してユーザーに表示する

これらのステップについて、以下で詳しく説明します。

ライブラリのインポート

Google Cloud Natural Language の Python 用クライアント ライブラリのインストールと使用についての詳細は、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 リファレンスをご覧ください。

Google Cloud Natural Language の Python 用クライアント ライブラリのインストールと使用についての詳細は、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 の値を抽出し、それをユーザーに示します。

サンプルの実行

サンプルを実行するために、映画『ブレードランナー』の一連の(架空の)映画レビューでサンプルをテストします。

  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

強度は、ポジティブの場合もネガティブの場合もあまり感情的でないレビューを示す「ニュートラル」ケースを除いて、すべて類似しています(かなり感情的な感想の量が比較的同等であることを示しています)。感情のスコアと強度や、これらの値の解釈方法の詳細については、感情分析の値の解釈をご覧ください。

その他のデータで感情分析を試すには、スタンフォード大学が提供している IMDB 映画レビューのデータセットを使用できます。この映画レビューを取得する手順は次のとおりです。

  1. Large Movie Review データセットをダウンロードします。
  2. ファイルを作業ディレクトリに解凍します。映画レビューが traintest のデータ ディレクトリ内で pos ディレクトリと neg ディレクトリに分けられます。また、各テキスト ファイルには 1 つの映画レビューが含まれています。
  3. いずれかの映画レビューのテキスト ファイルに対して sentiment_analysis.py ツールを実行します。

これで、Google Cloud Natural Language API を使用した最初の推定タスクが完了しました。