2012-07-22 2 views
14

私はローカルでsklearnの分類子を訓練しており、その使用方法を示す簡単なWebアプリケーションを作成する必要があります。私は、Webアプリケーション開発の完全なnoobです。私は使用しているモジュールをサポートしていないフレームワークを使用してWebアプリケーションを作成する時間を無駄にしたくありません。scikit-learnを使用しているWebアプリケーション

  1. このタスクにはどのようなアプローチが適していると思いますか?
  2. (もしあれば)どのWebアプリケーション開発フレームワークを使用すべきですか?
  3. Heoku,djangoなどのようなものにダイビングする必要がありますか、シンプルな科学的デモのためのより簡単で迅速なソリューションがありますか?

私の考えは、サーバーからclassifyを実行するために、私は訓練された分類器を取ることと、サーバー上の非ピクルス、それを酸洗いすることでしたが、私は開始する場所がわからないんだけど。

答えて

8

デモ用の場合は、クラシファイアをオフラインでトレーニングし、モデルをピケッとしてからflaskまたはbottleなどの単純なPython Webフレームワークを使用して、サーバの起動時にモデルをアンピクルし、HTTPリクエストでpredict関数を呼び出します。ハンドラ。

djangoはフィーチャーの完全なフレームワークなので、フラスコやボトルよりも学習するのに時間がかかりますが、素晴らしいドキュメントと大きなコミュニティがあります。

herokuはクラウドでアプリケーションをホストするサービスです。 host flask applications on herokuには可能ですが、ここにはsimple template project + instructionsがあります。

"production"の設定では、pickleを使用せず、機械学習モデル用の独自のパーシスタンスレイヤーを作成して、ストアのパラメータを完全に制御し、破損する可能性のあるライブラリのアップグレードに対してより頑強にすることをお勧めします古いモデルのunpickling。

+0

thx私はフラスコ+ herokuにショットを与えます – zenpoy

+0

フラスコとherokuを手にした後、私はskiearnと協力して問題を抱えています。それは英雄にインストールする...任意の考えですか? – zenpoy

+0

確かに私はそれについて考えなかった。どうやら他の人たちがこのように動作するようになっていたようです:http://stackoverflow.com/questions/9819968/running-scipy-on-heroku – ogrisel

2

これは分類子ではありませんが、ボトルフレームワークとscikit-learnを使用して簡単な機械学習Webサービスを実装しました。 .csv形式のデータセットがあれば、主成分分析と線形判別分析テクニックに関する2D視覚化を返します。ここでhttp://mindwriting.org/blog/?p=153

実装です:

詳細と例のデータファイルを見つけることができ upload.html:

<form 
action="/plot" method="post" 
enctype="multipart/form-data" 
> 
Select a file: <input type="file" name="upload" /> 
<input type="submit" value="PCA & LDA" /> 
</form> 

pca_lda_viz。PY(ホスト名とポート番号を変更します):

import matplotlib 
matplotlib.use('Agg') 

import matplotlib.pyplot as plt 
import numpy as np 
from cStringIO import StringIO 

from bottle import route, run, request, static_file 
import csv 
from matplotlib.font_manager import FontProperties 
import colorsys 

from sklearn import datasets 
from sklearn.decomposition import PCA 
from sklearn.lda import LDA 

html = ''' 
<html> 
    <body> 
     <img src="data:image/png;base64,{}" /> 
    </body> 
</html> 
''' 

@route('/') 
def root(): 
    return static_file('upload.html', root='.') 

@route('/plot', method='POST') 
    def plot(): 

     # Get the data 
     upload = request.files.get('upload') 
     mydata = list(csv.reader(upload.file, delimiter=',')) 

     x = [row[0:-1] for row in mydata[1:len(mydata)]] 

     classes = [row[len(row)-1] for row in mydata[1:len(mydata)]] 
     labels = list(set(classes)) 
     labels.sort() 

     classIndices = np.array([labels.index(myclass) for myclass in classes]) 

     X = np.array(x).astype('float') 
     y = classIndices 
     target_names = labels 

     #Apply dimensionality reduction 
     pca = PCA(n_components=2) 
     X_r = pca.fit(X).transform(X) 

     lda = LDA(n_components=2) 
     X_r2 = lda.fit(X, y).transform(X) 

     #Create 2D visualizations 
     fig = plt.figure() 
     ax=fig.add_subplot(1, 2, 1) 
     bx=fig.add_subplot(1, 2, 2) 

     fontP = FontProperties() 
     fontP.set_size('small') 

     colors = np.random.rand(len(labels),3) 

     for c,i, target_name in zip(colors,range(len(labels)), target_names): 
      ax.scatter(X_r[y == i, 0], X_r[y == i, 1], c=c, 
         label=target_name,cmap=plt.cm.coolwarm) 
      ax.legend(loc='upper center', bbox_to_anchor=(1.05, -0.05), 
        fancybox=True,shadow=True, ncol=len(labels),prop=fontP) 
      ax.set_title('PCA') 
      ax.tick_params(axis='both', which='major', labelsize=6) 

     for c,i, target_name in zip(colors,range(len(labels)), target_names): 
      bx.scatter(X_r2[y == i, 0], X_r2[y == i, 1], c=c, 
         label=target_name,cmap=plt.cm.coolwarm) 
      bx.set_title('LDA'); 
      bx.tick_params(axis='both', which='major', labelsize=6) 

     # Encode image to png in base64 
     io = StringIO() 
     fig.savefig(io, format='png') 
     data = io.getvalue().encode('base64') 

     return html.format(data) 

run(host='mindwriting.org', port=8079, debug=True) 
2

あなたはAzureのMLでのごscikit学習モデルを展開し、自動的に生成されたWebサービスを取得するには、以下のチュートリアルに従うことができます。

Build and Deploy a Predictive Web App Using Python and Azure ML

またはyHat + Herokuの組み合わせも、私はpredictpredictproba方法と電子をラップドッカー画像に働いているトリック

+1

[リンクのみの回答](http://meta.stackoverflow.com/tags/link-only-answers/info)はお勧めできませんので、SO回答はソリューションの検索の終点にする必要があります(時間の経過とともに古くなる傾向がある参照の途中降機)。リンクを参考にして、スタンドアロンの概要をここに追加することを検討してください – kleopatra

1

を行うことができますウェブAPIとしてそれらをxpose:https://github.com/hexacta/docker-sklearn-predict-http-api

あなたのモデルを保存する必要があります。

from sklearn.externals import joblib 
joblib.dump(clf, 'iris-svc.pkl') 

Dockerfile作成:

FROM hexacta/sklearn-predict-http-api:latest 
COPY iris-svc.pkl /usr/src/app/model.pkl 

をし、容器実行します。その後、

$ docker build -t iris-svc . 
$ docker run -d -p 4000:8080 iris-svc 

をあなたはリクエストをすることができます:

$ curl -H "Content-Type: application/json" -X POST -d '{"sepal length (cm)":4.4}' http://localhost:4000/predictproba 
    [{"0":0.8284069169,"1":0.1077571623,"2":0.0638359208}] 
$ curl -H "Content-Type: application/json" -X POST -d '[{"sepal length (cm)":4.4}, {"sepal length (cm)":15}]' http://localhost:4000/predict 
    [0, 2] 
関連する問題