虽然这不是分类器,但我已经使用瓶子框架和 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)