Watson Natural Language Understandingの感情分析触ってみた

Watson Natural Language Understandingの感情分析触ってみたところ面白そうだったのでメモ。他にもNLUのAPIあるんですけど、あんまり細かくは分からないんですよね。

翻訳

感情抽出に関しては英語にしか対応していませんので、まずはMicrosoft Translator APIで日本語を英語に翻訳しましょう。

Microsoft TranslatorでKey取得しておいて下さい。

こんな感じ。

translate.
<?php

define('AZURE_KEY', 'YOUR_AZURE_KEY');
define('AUTH_URL', 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');

$text = $_GET['text'];
$from = $_GET['from'];
$to = $_GET['to'];

try
{
  $accessToken = GetAccessToken();
  $params = 'text=' . urlencode($text) . '&from=' . $from . '&to=' . $to . '&appId=Bearer+' . $accessToken;;
  $url = 'http://api.microsofttranslator.com/v2/Http.svc/Translate?'  .$params;
  $response = Request( $url );
  echo $response;
} catch(Exception $e) {
    echo $e->getMessage();
}

function GetAccessToken()
{
  $params = json_encode('{body}');
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, AUTH_URL );
  curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($params),
    'Ocp-Apim-Subscription-Key: ' . AZURE_KEY
    )
  );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );

  $response = curl_exec($ch);
  if(curl_errno($ch)){
    throw new Exception( curl_error( $ch ) );
  }
  curl_close( $ch );

  return $response;
}

function Request( $url )
{
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, $url );
  curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: text/xml' ) );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );

  $response = curl_exec($ch);
  if(curl_errno($ch)) {
    throw new Exception(curl_error($ch));
  }
  curl_close( $ch );

  return $response;
}

?>

感情分析

page.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
<title>Watson NLU Test</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
  $("#text").focus();
  $('#text').keypress(function(e) {
    if (e.which == 13) {
      $("#button").click();
    }
  });
  $("#button").click(function(){
    $("#result").html("Understanding...");
    var translated = "";
    $.ajax({
      type: "GET",
      url: "translate.php?from=ja&to=en&text=" + encodeURI($("#text").val()),
      async: false,
      success:function(data){
        console.log("success");
        console.log(data);
        translated = data;
      },
      error:function(){}
    });

    var url = "https://watson-api-explorer.mybluemix.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&features=emotion&text=" + encodeURI(translated);
    console.log(url);
    $.ajax({
      type: "GET",
      url: url,
      success: function( data ){
        console.log("success");
        var emotions = data.emotion.document.emotion;
        console.log(data);
        console.log(emotions);
        $("#result").html("<span style='font-size:" + (20 + 50 * (emotions.anger / 1.0)) +
          "pt'>😡</span><span style='font-size:" + (20 + 50 * (emotions.disgust / 1.0)) +
          "pt'>😵</span><span style='font-size:" + (20 + 50 * (emotions.fear / 1.0)) +
          "pt'>😱</span><span style='font-size:" + (20 + 50 * (emotions.joy / 1.0)) +
          "pt'>😃</span><span style='font-size:" + (20 + 50 * (emotions.sadness / 1.0)) +
          "pt'>😭</span>");
      },
      error: function( XMLHttpRequest, textStatus, errorThrown ){}
    });
  });

});
</script>
</head>
<body>
  <h1>Watson NLU Test</h1>
  <input type="text" id="text">
  <button id="button">Tap Me</button>
  <div id="result"></div>
</body>
</html>

分析してみる




まとめ

翻訳通さずに直接英語渡すとかなり精度出るんですが、翻訳挟むとそうでもないですね。

宣伝

LINE BOTを作ろう! Messaging APIを使ったチャットボットの基礎と利用例

好評発売中!

[紹介元] PHPタグが付けられた新着投稿 – Qiita Watson Natural Language Understandingの感情分析触ってみた

関連記事