Python-Flask:将数据传递给机器学习python脚本并返回结果 [英] Python-Flask: Pass data to machine learning python script and get results back

查看:124
本文介绍了Python-Flask:将数据传递给机器学习python脚本并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在web框架中的知识很糟糕。我有一个建立在Python的机器学习模型,它需要一组字符串作为输入并返回结果。在网上搜索后,我遇到了 Flask 。但我不知道如何实际创建一个瓶子应用程序来实际采取一个字符串,并允许用户提交并将该字符串传递给我的机器学习python脚本并返回结果。这是我迄今为止所有

pre $ 导入线程
导入子流程
导入os
导入sys
from flask import Flask $ b $ from flask import render_template,abort $ b $ app = Flask(__ name__)
app.debug = True
$ b $ def run_script() :
theproc = subprocess.Popen([sys.executable,ML_script.py])
theproc.communicate()


if __name__ ==__main__ :
app.run()

如果您可以指向一个示例或提供解决方案/框架,这将是太棒了。

解决方案

您可以使用您的机器学习功能,像任何其他Python功能没有必要。设置您的应用程序:

  from flask import Flask 
from flask import render_template,abort,jsonify,request,redirect,json
from my_app.machine_learning导入分析器
app = Flask(__ name__)
app.debug = True

@ app.route('/')
def index():
return render_template('index.html')

@ app.route('/ learning',methods = ['POST'])
def学习():
data = json.loads(request.data)
#data == {userInput:你输入的任何文本}
response = analyzer(data)
返回jsonify(响应)


if __name__ =='__main__':
app.run()
$ b

我为你的机器学习模块使用了一个名字,但是 analyzer()应该是该模块中的一个函数,调用您的计算所需的所有其他函数,并返回一个包含结果的字典。所以这样的事情:

$ $ p $ $ code def analyzer(data):
vocab = build_vocab(training_data)
cl = train_classifier(vocab,trianing_data)
results = cl.predict(data)
results = format_results_to_dict()
返回结果

这个模板非常简单:

 <!DOCTYPE html> 
< html>
< head>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js>< / script>
< script src =../ static / script.js>< / script>
< / script>
< / head>

< body>
< h1>计算< / h1>
< h1>测试页< / h1>
< input id =user-inputplaceholder =要分析的文本>< / input>
< p id =results>结果会放在这里< p>
< button id =submit>提交< / button>
< / body>
< / html>



和$ JS $
$ b $ (函数(事件){
var uInput =($))$ b $($#$) $(#user-input)。val();
$ .ajax({
type:POST,
url:'/ learning',
data: JSON.stringify({userInput:uInput}),
contentType:'application / json',
success:function(response){
$(#results)。text(response。结果);
},
});
});
});


My knowledge in web frameworks are pretty bad. I have a build a machine learning model in python and it takes a set of strings as an input and return results. After searching on the web I came across with Flask. But what I don't know is how to actually create a flask app to actually take a string and allow user to submit and pass that string to my machine learning python script and return results. This is all I have so far

import threading
import subprocess
import os
import sys
from flask import Flask
from flask import render_template, abort
app = Flask(__name__)
app.debug = True

def run_script():
    theproc = subprocess.Popen([sys.executable, "ML_script.py"])
    theproc.communicate()


if __name__ == "__main__":
    app.run()

If you can point to an example or provide a solution /skeleton that would be fantastic.

解决方案

You can use your machine learning functions like any other Python function there is no need for subprocess. Setup your app:

from flask import Flask
from flask import render_template, abort, jsonify, request,redirect, json
from my_app.machine_learning import analyzer
app = Flask(__name__)
app.debug = True

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/learning', methods=['POST'])
def learning():
    data = json.loads(request.data)
    # data == {"userInput": "whatever text you entered"}
    response = analyzer(data)
    return jsonify(response)


if __name__ == '__main__':
    app.run()

I used a stand in name for your machine learning module but analyzer() should be a function in that module that calls all your other functions needed to do your computations and returns a dictionary that has your results in it. So something like this:

def analyzer(data):
    vocab = build_vocab(training_data)
    cl = train_classifier(vocab, trianing_data)
    results = cl.predict(data)
    results = format_results_to_dict()
    return results

The template is pretty straight forward:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../static/script.js"></script>
</script>
</head>

<body>
    <h1>Calculation</h1>
    <h1>Test Page</h1>
    <input id="user-input" placeholder="Text to be analyzed"></input>
    <p id="results">Results will go here<p>
    <button id="submit">Submit</button>
</body>
</html>

And the JS script to tie it all together:

$(document).ready(function(){
    $("#submit").click(function(event){
        var uInput = $("#user-input").val();
        $.ajax({
              type: "POST",
              url: '/learning',
              data: JSON.stringify({userInput: uInput}),
              contentType: 'application/json',
              success: function(response){
                   $("#results").text(response.results);
                },
          });
    });
});

这篇关于Python-Flask:将数据传递给机器学习python脚本并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆