github:
https://github.com/wilsonsujames/ML_on_web
資料集:
https://www.kaggle.com/shwetabh123/mall-customers
這次是用機器學習中的kmeans演算法作範例,如何將AI執行出來預測的結果視覺化。
首先是模型的訓練 kmean_train.py :
#load 進資料集
dataset = pd.read_csv('./Mall_Customers.csv')
#可以切分訓練集
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')
在dashboard.html的部分,放置了圖片及圖片來源:
<div class="container">
<img src="{{url_for('plot_png')}}" alt="my plot">
</div>
在server.py的部分,由plot_png這個function來提供圖片:
@app.route('/plot')
def plot_png():
dataset = pd.read_csv('./Mall_Customers.csv')
# X= dataset.iloc[151:202, [3,4]].values
X= dataset.iloc[:, [3,4]].values
kmean_clf = load('kmean.joblib')
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")
使用joblib來load進模型物件,預測給定的pandas資料,將預測的5群及群心分別上不同顏色,將圖片結果呈現在網頁中。
結果呈現:
flask中使用matplotlib影片版本
kmeans介紹影片版本: