機械学習で地震に関する文章なのか判断するコード。

20160906

Logging


機械学習で地震に関する文章なのか判断するコード。
機械学習のライブラリに文章を放り込むだけで地震に関するものなのか
判断してくれます。文章が増えれば増えるほど、精度が下がる可能性あり。
何故なら、誤りを学習する機能を付けていない為。
文章をmecabで分離したかったのだけど
XServerはどうもmecabのインストールが出来ないみたいです。
なので、Yahooの日本語形態素解析APIを使用しました。
機械学習のライブラリのインストール等はご自分で調べてみてください。
ちなみにXサーバだと、composerは最初から入っているので
ライブラリのfieg/bayesだけインストールするればOKです。
今回の機械学習は教師ありの機械学習法です。最初に
地震である文章かどうかをある程度、学習させてから出ないと
判別はできません。機械学習の最初の段階は
半手動になります。
ソースは下記より参照してください。
DEMO:http://zip358.com/tool/jishinkita/

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>地震キタ━(゚∀゚)━!くるな</title>
    <meta name="viewport" content="user-scalable=no,initial-scale = 1.0,maximum-scale = 1.0">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="../topcoat/main/fonts/stylesheet.css">
    <link rel="stylesheet" type="text/css" href="../topcoat/css/topcoat-desktop-dark.css">
    <link rel="stylesheet" type="text/css" href="../topcoat/main/css/main.css">
    <link rel="stylesheet" type="text/css" href="../topcoat/main/css/brackets.css"><!--[if lt IE 9]>
    <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
    <script>
$(function () {
    $('#btn').click(function () {
        $.ajax({
            url: 'jishin.php',
            type: 'post',
            dataType: 'json',
            data: {
                texts: $('#texts').val()
            }
        })
        .done(function (obj) {
            var jishin  = floatFormat((obj.jishin * 100),3);
            var not_jishin  = floatFormat((obj.not_jishin) * 100,3);
            $('#jishin').html($('#texts').val() + "<br><br>地震のつぶやきである可能性:" + jishin + "%<br>" + "地震のつぶやきでない可能性:" + not_jishin + "%<br>");
            $('#texts').val("");
        })
        .fail(function () {
            $('#jishin').val('失敗');
        });
    });
});
function floatFormat( number, n ) {
	var _pow = Math.pow( 10 , n ) ;
	return Math.round( number * _pow ) / _pow ;
}
    </script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-71682075-1', 'auto');
  ga('send', 'pageview');
</script>
  </head>
  <body class="dark">
      <div id="wrapper">
          <section class="component">
                <h1>地震キタ━(゚∀゚)━!くるな取り扱い説明書</h1>
                <div>地震に関する文章なのか機械学習を使用して調べます。</div>
                <textarea class="topcoat-textarea" id="texts"rows="6" cols="36" placeholder="日本語を入力してください。"></textarea><br>
                <button class="topcoat-button--large--cta" id="btn">Button</button><br>
                <div id="jishin"></div>
            </section>
      </div>
  </body>
</html>
<?php
require '/vendor/autoload.php';
use Fieg\Bayes\Classifier;
use Fieg\Bayes\Tokenizer\WhitespaceAndPunctuationTokenizer;
$text = $_POST["texts"];
$token =  new WhitespaceAndPunctuationTokenizer();
$Classifier = new Classifier($token);
$ret = sqlpdo("SELECT * FROM xxxxx");
for($i=0;$i<count($ret,0);$i++){
    $Classifier->train($ret[$i]["cate"],$ret[$i]["tango"]);
}
$ans=[];
if($text){
    $tango = nihongo($text);
    $ans = $Classifier->classify($tango);
    if($ans["地震"]>0.6){
        sqlpdo("INSERT INTO `xxxxx`(xxxx,`xxxx`, `xxxx`, `edate`, `xxxx`) VALUES (xxx,'地震','$tango',now(),0)");
    }else{
        sqlpdo("INSERT INTO `xxxxx`(xxxx,`xxxx`, `xxxxx`, `edate`, `xxxx`) VALUES (xxxx,'地震ではない','$tango',now(),0)");
    }
}
$obj["not_jishin"] = $ans["地震ではない"];
$obj["jishin"] = $ans["地震"];
echo json_encode($obj);
function nihongo($word){
//アプリケーションIDのセット
$id = "";
//URLの組み立て
$url = "http://jlp.yahooapis.jp/MAService/V1/parse?appid=" . $id . "&results=ma&sentence=" . urlencode($word);
//戻り値をパースする
$parse = simplexml_load_file($url);
//戻り値(オブジェクト)からループでデータを取得する
foreach($parse->ma_result->word_list->word as $value){
    $str[] = $value->surface;
}
    $tango = implode(" ", $str);
    return $tango;
}
function sqlpdo($sql){
    $user="";
    $pass="";
    $ret= [];
    $i=0;
    try {
        $dbh = new PDO('mysql:host=xserver.jp;dbname=xxxxx', $user, $pass);
        foreach($dbh->query($sql) as $row) {
           $ret[$i++] = $row;
       }
        $dbh = null;
    } catch (PDOException $e) {
        $ret = "エラー!: " . $e->getMessage() . "<br/>";
        die();
    }
        return $ret;
}

タグ

AM,