Amazon ML を触ろう

ガンガン行きます。

というか、Amazon Redshiftって何だ。。。 dataを保存できるのか。

modeling process

モデリングしてる模様

completed

Try real-time prediction

ここで予想します。

うーん、なんとなく流れは分かったようなわからないような。
データセットが用意されていると、単なる作業で頭使わないので駄目ですね。

AWS machine learning

Amazon machine learning モデルの概念図

what is amazon machine learning
amazon ML can be used to make predictions for a variety of purposes. For example, you could build a model in Amazon ML that will predict whether a given customer is likely to respond to a marketing offer. Amazon ML creates models from supervised data sets. This means that the model is based on a set of previous observations. This set of observations consists of features or attributes as well as the target outcome. In the marketing offer example, the features might include the age, profession, and gender of the customer. The target outcome (also called the target variable) would be whether that particular customer responded to the marketing offer or not.

The process of creating a model from a set of known observations is called training. Once you have trained a model in Amazon ML, you can then use the model to predict outcomes from a set of attributes that matches the attributes used to train the model. Amazon ML scales so that you can make thousands of predictions concurrently. This is important, as today machine learning is often used to provide predictions in near real-time. In this lab, you will be using a machine learning model to predict which restaurants a customer is likely to favor based on the results of a search query.

data setをs3のバケットのuploadする。

なるほど、S3はこういう風に使うのね。

machine learningを選択する

流石にまだ翻訳されてないな。

s3

bucketを作成し、upload、permissionをread only everyoneに変更します。

バケットポリシー

{
  "Id": "Policy1535369626475",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1535369623531",
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::mybucket198205/*",
      "Principal": "*"
    }
  ]
}

見れるようになりました♪

versioning: uploadしても古いバージョンを呼び出せる。

これは中々いいですね。

AWS DynamoDB

NoSQLなので、mongoDB、cosmosDBなどと同じで、リレーショナルではなく、JSONデータの保存などに適しています。

tableをcreateします。
primary keyはidのようなものですね。
SQL文を頭にイメージしながら作成していきます。

itemを入れていきます。

更にitemを入れていきます。
php myadmin触っているみたいだ。

う~ん、これは、普通にsql文書いた方が明らかに効率がいいですな。

AWS Lambdaを触ってみよう

runtime -> python3.6
role: lambda-execution-role

pythonは3.6か。roleは何のことかイマイチよくわかりません。

s3のトリガーを追加する。

Diagramが Create-Thumbnail、S3、Amazon S3、 AWS Lambdaがあります。 S3が2つあるが。。ま~気にせずに進みましょう。それと、Cloudwatchlogってなんだ。。

関数コードを入力していきます。

あれ、何これ、S3のimages-123-aws-resizedのbucketにリサイズされが画像が生成されとる!?

Congratulations! You have successfully:
おいおい、肝心のlambdaの関数がblack boxじゃないか。。まあ、画像のリサイズはライブラリ使えば一発なんですがね。

lambdaが何かは少し理解が深まりました♪ OK!
python3.5ではなく、3.6なんですね。

AWS Lambdaでアプリケーション

S3、Lambdaを使います。

A user uploads an object to the source bucket in Amazon S3 (object-created event).
Amazon S3 detects the object-created event.
Amazon S3 publishes the object-created event to AWS Lambda by invoking the Lambda function and passing event data as a function parameter.
AWS Lambda executes the Lambda function.
From the event data it receives, the Lambda function knows the source bucket name and object key name. The Lambda function reads the object and creates a thumbnail using graphics libraries, then saves the thumbnail to the target bucket.

Task 1: Create the Amazon S3 Buckets
コンソールからS3に入ります。

あれ、もうすでにbucketが出来てますね。。。

bucket name を images-123-aws で一つ作成します。
同様の手順で、images-123-aws-resizedのbucketを作成します。now、bucketは4つになりました。

images-123-awsに画像をuploadします。

さあ、いよいよlambdaを使います。

AWS Lambdaとは

Lambdaの読み方がわからない
⇒インスタンスベースの仮想サーバー(EC2、ElastiChache、Redshiftなど)を使わずにアプリケーションを開発するアーキテクチャ

>Lambda を使用すれば、実質どのようなタイプのアプリケーションやバックエンドサービスでも管理を必要とせずに実行できます。コードさえアップロードすれば、高可用性を実現しながらコードを実行およびスケーリングするために必要なことは、すべて Lambda により行われます。コードは、他の AWS サービスから自動的にトリガーするよう設定することも、ウェブやモバイルアプリケーションから直接呼び出すよう設定することもできます。

サーバー管理がないということは、sakuraの共有サーバーのようなものか?
これ、わざわざやる必要あるか?

とりあえず、AWS Lambda 入門を叩いてみましょう。

なんだこれは!? とりあえず、Qwiklabsにjoinしましょか。

By the end of this lab you will be able to:

  • Create an AWS Lambda function
  • Configure an Amazon S3 bucket as a Lambda Event Source
  • Trigger a Lambda function by uploading an object to Amazon S3
  • Monitor AWS Lambda S3 functions through Amazon CloudWatch Log

コンピューティングにlambdaがありますね。

node.jsのコードを実行します。

exports.handler = (event, context, callback) => {
    // 「Hello World!」という文字列で続行
    callback(null, 'Hello world!');
};

ec2でpythonにpost

[ec2-user@ip-xxx-xx-xx-xx app]$ python -V
Python 2.7.14

[ec2-user@ip-xxx-xx-xx-xx app]$ python35
Python 3.5.5 (default, Apr 25 2018, 23:51:32)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

python2系だからか?
usr/binを見ます。

うまくいきませんね。
他の方法を試してみましょうか。。

vagrantでajaxでpythonにpostする

index.php

<!DOCTYPE html>
<html lang="ja">
<head>
  <title>Ajax</title>
</head>

<body>
  <h1>Ajax</h1>
  <form id="form">
    <div><label>送信する数字</label><input type="number" id="number" value="0"></div>
    <div>
      <label>送信するテキスト</label>
      <textarea id="text"></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  <div id="result"></div>

  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $('#form').submit(function(){
        event.preventDefault();
        var $form = $(this);
        $.ajax({
          url:'http://localhost:8000/cgi-bin/index.py',
          type: 'post',
          dataType: 'text',
          data: {
            number: $('#number').val(),
            text: $('#text').val()
          },
        })
        .done(function(response){
          $('#result').html(response);
        })
        .fail(function(){
          $('#result').html('Failed.');
        });
      });
    });
    </script>
  </body>
</html>

index.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cgi, cgitb

cgitb.enable()

form = cgi.FieldStorage()
text = form.getFirst("text")
n = form.getFirst("number")
sequence_list = []

print('Content-type: text/html\nAccess-Control-Allow-Origin: *\n')
print("<p>送信された数字: {}</p>".format("None" if n is None else int(n)))
print("<p>送信されたテキスト: {}</p>".format(text))
python -m http.server --cgi

何故だ? 問題はHTML側ではないと思うので、AWSもしくはsakuraでやってみるか。

index.phpをindex.htmlに変更します。

192.168.35.1 – – [26/Aug/2018 10:19:03] code 403, message CGI script is not executable (‘/cgi-bin/index.py’)
192.168.35.1 – – [26/Aug/2018 10:19:03] “POST /cgi-bin/index.py HTTP/1.1” 403 –

なに?
[vagrant@localhost app]$ cd cgi-bin
[vagrant@localhost cgi-bin]$ chmod 755 index.py

192.168.35.1 – – [26/Aug/2018 10:23:35] “GET / HTTP/1.1” 200 –
192.168.35.1 – – [26/Aug/2018 10:23:43] “POST /cgi-bin/index.py HTTP/1.1” 200 –
: そのようなファイルやディレクトリはありません
192.168.35.1 – – [26/Aug/2018 10:23:43] CGI script exit status 0x7f00

う~ん、なんでだろう。
jsのdocument.titleで取得してphpファイルに送ることもできるが、後々のことを考えるとpythonでやりたいですね。