エンジニア

なんくるないさ

「このブログはアフィリエイト広告を利用しています」

webから機械学習用(python)のプログラムを呼び出す方法(python編)


webで入力された情報をpythonに渡すことって結構ありますよね?

例えば
webブラウザでユーザが入力した情報をpythonで深層学習、機械学習したモデルになげて、推論)


本記事ではローカルブラウザで入力したデータをpythonに渡し、推測させる方法を記述しています。




ブラウザでpythonにデータを渡したい人はぜひ見ていってください



Flask という Python の小規模なフレームワークを利用します

app.py

import json
from flask import request
from flask import Flask, render_template

#推測するpyプログラム
import my_csv5

#initalize our flask app
app = Flask(__name__)

@app.route('/')
def index():
    with open("index.html", "rb") as f:
        return render_template('index.html')

@app.route('/predict/',methods=['GET','POST'])
def predict():
    csvdata = (request.get_data()).decode('utf-8')
    label,percent = my_csv5.check_genre(csvdata)
    return json.dumps({
        "label":label,
        "percent":percent+"%"
    })
if __name__ == "__main__":
    app.run(debug=True,port=8085)
    print("http://localhost:" + str(port))


これがローカルにホストを作るプログラムです。

まずは 必要なモジュールimportします。


次に

#initalize our flask app
app = Flask(__name__)
これによって Flask クラスのインスタンスを作って、 app という変数に代入しています。

__name__ というのは、自動的に定義される変数で、現在のファイルのモジュール名が入ります。 ファイルをスクリプトとして直接実行した場合、 __name__ は __main__ になります。

__________________________________________________________

@app.route('/')

@app.route('/') という行は、 app に対して / というURLに対応するアクションを登録しています。
つまり
@app.route('/')
def index():
with open("index.html", "rb") as f:
return render_template('index.html')
これで
/indexにアクセスが来たらtemplates内のindex.htmlが開きます

ここでtemplatesフォルダを作っておきましょう
フォルダは下のように整理しないとエラーで動きません。

python flask
├── app.py
└── my_csv.py
└── templates
└── index.html

__________________________________________________________

@app.route('/predict/',methods=['GET','POST'])

次に/predict にアクセスした場合
@app.route('/predict/',methods=['GET','POST'])
def predict():
csvdata = (request.get_data()).decode('utf-8')
label,percent = my_csv5.check_genre(csvdata)
return json.dumps({
"label":label,
"percent":percent+"%"
})

methodsにPOSTをつけると、、、
request.get_data()でhtmlでのデータを受け取ることができます。
このときutf-8でdecodeするのを忘れずに。
それをcsvdataという変数に代入。
その変数を推測用のmy_csv5内の関数check_genreの引数に代入。
結果をlabel,perecentに代入して、
json形式でreturnします。

__________________________________________________________

if __name__ == "__main__":

if __name__ == "__main__":
app.run(debug=True,port=8085)
print("http://localhost:" + str(port))

この説明は
以下のURLが参考になります

http://blog.pyq.jp/entry/Python_kaiketsu_180207



そんで推測用のプログラムです

my_csv5.py

import json

#Cnn

from nnabla.utils.data_iterator import data_iterator_csv_dataset 
import pandas as pd
import numpy as np
import csv

#配列を受け取り、その配列をcsvファイルに保存、
#その配列の名前を一列目、2列目にラベルをつけてcsvファイル(評価ファイル)にする)

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF


def network(x, y, test=False):
    # Input:x -> 30,2
    # Reshape -> 1,10,6
    h = F.reshape(x, (x.shape[0],1,10,6))
    # Convolution -> 16,9,9
    h = PF.convolution(h, 16, (2,2), (0,2), name='Convolution')
    # ReLU
    h = F.relu(h, True)
    # MaxPooling -> 16,9,17
    h = F.max_pooling(h, (1,1), (1,1), True, (0,4))
    # PReLU
    h = PF.prelu(h, 1, False, name='PReLU')
    # Convolution_2 -> 15,7,15
    h = PF.convolution(h, 15, (3,3), (0,0), name='Convolution_2')
    # MaxPooling_2 -> 15,3,7
    h = F.max_pooling(h, (2,2), (2,2))
    # Tanh_2
    h = F.tanh(h)
    # Dropout
    if not test:
        h = F.dropout(h)
    # Affine -> 150
    h = PF.affine(h, (150,), name='Affine')
    # ReLU_2
    h = F.relu(h, True)
    # Affine_2 -> 5
    h = PF.affine(h, (5,), name='Affine_2')
    # Softmax
    h = F.softmax(h)
    # CategoricalCrossEntropy -> 1
    #h = F.categorical_cross_entropy(h, y)
    return h



        #ネットワークの構築
nn.clear_parameters()
        # Prepare input variable
x = nn.Variable((1,30,2))
t = nn.Variable((1,1))
        # Build network for inference
y = network(x, t)
        # load parameters
nn.load_parameters(r'\parameters.h5')
# print("load model")
# print(arr)
def check_genre(arr):
    arr = arr.split()
    arr = [e.rstrip(',')for e in arr]
    
    arr =[row.split(',')for row in arr]
    
    with open('data.csv', 'w') as file:
        writer = csv.writer(file, lineterminator='\n')
        writer.writerows(arr)
   # print("made csvfile from array")
    
    f = pd.DataFrame(columns=["x:data","y:data"])
    xdata = 'data.csv'
    ydata = 0
    new_name = pd.Series([xdata,ydata],index=f.columns)
    f = f.append(new_name, ignore_index=True)
    f.to_csv('valu.csv',index=False,header = True )
 #   print("made valu.csv")
    
    test_data = data_iterator_csv_dataset(r".\valu.csv",1,shuffle=False,normalize=False)   
    
    for i in range(test_data.size):
        x.d, t.d = test_data.next()
        y.forward()
        print(y.d[0])
        label = 2 #初期化
        percent = 1 #初期化


        if y.d[0][0]>y.d[0][1] and y.d[0][0]>y.d[0][2] and y.d[0][0]>y.d[0][3] and y.d[0][0]>y.d[0][4]:
            label = 0
            percent = y.d[0][0]
            #label = random.randint(0,2)
        if y.d[0][1]>y.d[0][0] and y.d[0][1]>y.d[0][2] and y.d[0][1]>y.d[0][3] and y.d[0][1]>y.d[0][4]:
            label = 1
            percent = y.d[0][1]
        if y.d[0][2]>y.d[0][1] and y.d[0][2]>y.d[0][0] and y.d[0][2]>y.d[0][3] and y.d[0][2]>y.d[0][4]:
            label = 2
            percent = y.d[0][2]          
        if y.d[0][3]>y.d[0][0] and y.d[0][3]>y.d[0][1] and y.d[0][3]>y.d[0][2] and y.d[0][3]>y.d[0][4]:
            label = 3
            percent = y.d[0][3]
        if y.d[0][4]>y.d[0][1] and y.d[0][4]>y.d[0][0] and y.d[0][4]>y.d[0][2] and y.d[0][4]>y.d[0][3]:
            label = 4
            percent = y.d[0][4]            
        result = str(label)
        percent1 = percent*100           
        percent1 =str(percent1)
        print (percent1+"%")
 

    return label,percent


if __name__== '__main__':
    with open('some.csv') as fp:
    lst = list(csv.reader(fp))
    check_genre(lst)
def network(x, y, test=False):

この関数では機械学習のモデルを構築しています。
機械学習については下のサイトを参考にしてください

jump1268.hatenablog.com



def check_genre(arr):

これはhtmlでpostされてきたデータを引数としています。
送られてくるデータは
jump1268.hatenablog.com
このようにあまり理想的なデータ構造をしていません。
value,value2,\nの連続

仕方なく下の処理をしていますが、ここは改善しなければいけないところです。

HTML側で改善すべきですね。

def check_genre(arr):
arr = arr.split()
arr = [e.rstrip(',')for e in arr]

arr =[row.split(',')for row in arr]

with open('data.csv', 'w') as file:
writer = csv.writer(file, lineterminator='\n')
writer.writerows(arr)



最後までありがとうございます。


AI セミナー 人工知能 セミナー 機械学習 セミナー ディープラーニング セミナー Python 初級
このサイトでAIとpythonを学ぶとより良いと思います
今なら無料で相談できるそうなのでぜひ




ブラウザ編はこちらです
jump1268.hatenablog.com



あとこのサイトがマジでお勧めです。今なら登録してスカイプで無料体験するだけで1000円もらえます。