使用scikit learn的Web应用程序

2024-05-19 02:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在本地训练了一个sklearn分类器,我必须创建一个简单的web应用程序来演示它的用途。我完全不懂网络应用程序的开发,我不想浪费时间在创建一个不支持我正在使用的模块的框架的网络应用程序上。

  1. 你认为什么是完成这项任务的好方法?
  2. 我应该使用什么样的web应用开发框架(如果有的话)?
  3. 我需要深入研究诸如Heokudjango等问题吗?或者对于一个简单的科学演示,是否有更简单、更快的解决方案?

我的想法是使用我训练的分类器,在服务器上对其进行pickle和unpickle,然后从服务器上运行classify,但我不确定从哪里开始。


Tags: 模块django方法程序服务器框架web应用程序
3条回答

虽然这不是一个分类器,但我已经使用bottle框架和scikit learn实现了一个简单的机器学习web服务。给定一个.csv格式的数据集,它返回有关主成分分析和线性判别分析技术的二维可视化。

有关更多信息和示例数据文件,请访问:http://mindwriting.org/blog/?p=153

以下是实现方法: 上传.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)

您可以按照以下教程在Azure ML中部署scikit学习模型并自动生成web服务:

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

或者yHat+Heroku的组合也可以做到

如果这只是一个演示,那么离线训练分类器,pickle模型,然后使用简单的python web框架(如flaskbottle)在服务器启动时取消对模型的ickle,并在HTTP请求处理程序中调用predict函数。

django是一个功能完整的框架,因此比烧瓶或瓶子学习时间更长,但它有一个伟大的文档和一个更大的社区。

heroku是一个在云中托管应用程序的服务。有可能host flask applications on heroku,这里有一个simple template project + instructions这样做。

对于“生产”设置,我建议您不要使用pickle,而是为机器学习模型编写您自己的持久层,以便对存储的参数进行完全控制,并对可能会打破旧模型的取消锁定的库升级更加健壮。

相关问题 更多 >

    热门问题