1

## 伸縮自如的Flask [day 26] Flask with ML

``````

#可以切分訓練集
X= dataset.iloc[:150, [3,4]].values

#從分2類到分11類來評估最佳分群數
silhouette_avg = []
for i in range(2,11):
try:
kmeans = KMeans(n_clusters= i, init='k-means++').fit(X)
silhouette_avg.append(silhouette_score(X, kmeans.labels_))
except:
pass

indArr,peak_heightsDict=find_peaks(silhouette_avg)

# 在silhouette_avg這個list中，最高點index為三，最佳分群數為5
RowNumCategories=indArr[0]+2

# 模型預測及畫圖
kmeansmodel = KMeans(n_clusters= RowNumCategories, init='k-means++')
y_kmeans= kmeansmodel.fit_predict(X)

# 利用joblib 來將模型儲存
dump(kmeansmodel, 'kmean.joblib')
``````

``````<div class="container">
<img src="{{url_for('plot_png')}}" alt="my plot">
</div>
``````

``````@app.route('/plot')
def plot_png():

# X= dataset.iloc[151:202, [3,4]].values
X= dataset.iloc[:, [3,4]].values
y_kmeans= kmean_clf.fit_predict(X)

Kmeansfig = Figure()
axis = Kmeansfig.add_subplot(1, 1, 1)
axis.grid(color='lightgrey')
axis.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = ' 1')
axis.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = '2')
axis.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = '3')
axis.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = ' 4')
axis.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = '5')
axis.scatter(kmean_clf.cluster_centers_[:, 0],
kmean_clf.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')
axis.set_title("K-means demo")
axis.legend()

output = io.BytesIO()
FigureCanvas(Kmeansfig).print_png(output)

return Response(output.getvalue(), mimetype="image/png")
``````