將tensorflow訓練好的模型部署成sercice服務,並做預測
阿新 • • 發佈:2019-01-07
web框架用的是tornado,模型載入在上一篇部落格已經提到,下面寫了一個service.py檔案:
import tornado.web
import logging
import string
import os
import sys
from predict import predict
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
# 再建立一個handler,用於輸出到控制檯
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# 定義handler的輸出格式
formatter = logging.Formatter('%(asctime)s - %(message)s')
ch.setFormatter(formatter)
# 給logger新增handler
logger.addHandler(ch)
def work(text):
if text isNone:
return0.
else:
return predict(text)
classMainHandler(tornado.web.RequestHandler):
def post(self):
text = self.get_argument('text')
p = work
self.write(p)
classIndexHandler(tornado.web.RequestHandler):
def get(self):
text = self.get_argument('text')
p = work(text)
self.render('index.html',text=text,result='{0}'.format(p))
application=tornado.web.Application(
handlers=[(r"/",MainHandler),
(r'/demo',IndexHandler)],
template_path
)
if __name__=='__main__':
if len(sys.argv)<2:
port=8410
else:
port=string.atoi(sys.argv[1])
application.listen(port)
logger.info('Starting server:port=%d, use <Ctrl-C> to stop'% port)
tornado.ioloop.IOLoop.instance().start()
templates/index.html問價內容:
<!DOCTYPE html>
<html>
<head><title>text abumse server</title></head>
<body>
<form method="get" action="/demo">
<p>text content:<input type="text" name="text" value="{{text}}" style="width: 800px"><input type="submit"></p>
</form>
<p>{{result}}</p>
<p><img src="{{text}}" width="600px"></p>
</body>
</html>
啟動service.py檔案:
/anaconda/bin/python3 /Users/shuubiasahi/Documents/python/credit-tftextclassify-abuse/service.py
2017-10-1315:58:20.625704: W tensorflow/core/platform/cpu_feature_guard.cc:45]TheTensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-10-1315:58:20.625723: W tensorflow/core/platform/cpu_feature_guard.cc:45]TheTensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-10-1315:58:20.625728: W tensorflow/core/platform/cpu_feature_guard.cc:45]TheTensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-10-1315:58:20.625733: W tensorflow/core/platform/cpu_feature_guard.cc:45]TheTensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-10-1315:58:21,732-Starting server:port=8410, use <Ctrl-C> to stop