0

I am just starting to get into Flask. I created a super-simple Flask app.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, World!"
    
if __name__ == "__main__":
    app.run(debug=True)

I can run 'python hello-world.py' in my Anaconda prompt, go to 'localhost:5000' and it works as expected. I'm wondering how I can use some ML code to create some kind of API interface, using Flask. This is just a learning exercise for me, so I don't really have a concrete example of what needs to be done. I'm calling this a 'deployment exercise'. Anyway, here is a sample of code that I want to run.

# K-Means
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# %matplotlib inline
from sklearn import datasets#Iris Dataset
iris = datasets.load_iris()
X = iris.data#KMeans
km = KMeans(n_clusters=3)
km.fit(X)
km.predict(X)
labels = km.labels_#Plotting
fig = plt.figure(1, figsize=(7,7))
ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)
ax.scatter(X[:, 3], X[:, 0], X[:, 2],
          c=labels.astype(np.float), edgecolor="k", s=50)
ax.set_xlabel("Petal width")
ax.set_ylabel("Sepal length")
ax.set_zlabel("Petal length")
plt.title("K Means", fontsize=14)

enter image description here

# GMM:
from sklearn.mixture import GaussianMixture
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
#%matplotlib inline
from sklearn import datasets#Iris Dataset
iris = datasets.load_iris()
X = iris.data#Gaussian Mixture Model
gmm = GaussianMixture(n_components=3)
gmm.fit(X)
proba_lists = gmm.predict_proba(X)#Plotting
colored_arrays = np.matrix(proba_lists)
colored_tuples = [tuple(i.tolist()[0]) for i in colored_arrays]
fig = plt.figure(1, figsize=(7,7))
ax = Axes3D(fig, rect=[0, 0, 0.95, 1], elev=48, azim=134)
ax.scatter(X[:, 3], X[:, 0], X[:, 2],
          c=colored_tuples, edgecolor="k", s=50)
ax.set_xlabel("Petal width")
ax.set_ylabel("Sepal length")
ax.set_zlabel("Petal length")
plt.title("Gaussian Mixture Model", fontsize=14)

enter image description here

If my approach is totally wrong, please tell me how to do this the right way. Again, this is simply a learning exercise for myself. I've been using Spyder to do all my ML work for a while, and now I want to try to incorporate some API technology, or Flask technology, into my work.

ASH
  • 20,759
  • 19
  • 87
  • 200

1 Answers1

2

You can save models in most of the libraries, including sckit-learn. For example

import pickle
pickle.dump(kmeans, open("kmean_model.pkl", "wb"))

and load it as

kmeans = pickle.load(open("kmean_model.pkl", "rb"))

You can use Api endpoint to use this loaded model and predict, for example

from flask import Flask, jsonify

import pickle
import pandas as pd
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
     json_features = request.json
     query_df = pd.DataFrame(json_features)
     features = pd.get_dummies(query_df)
    
     prediction = kmeans.predict(features)
     return jsonify({'prediction': list(prediction)})
if __name__ == '__main__':
     kmeans = pickle.load(open("kmean_model.pkl", "rb"))
     app.run(port=8080)

Note: This is overly simplistic example with assumptions, you need to see if you have same features or not and more checks.

A.B
  • 20,110
  • 3
  • 37
  • 71
  • Thanks! I saved the file as 'kmeans.pkl'. Then I ran your code and I got this traceback error: 'Traceback (most recent call last): File "", line 16, in kmeans = pickle.load(open("kmeans.pkl", "rb")) EOFError: Ran out of input' – ASH Sep 01 '20 at 15:01
  • @ASH, you can make a new question for better reach and due to the fact that its a new problem – A.B Sep 01 '20 at 15:08
  • you seem to have empty pickle file, follow this answer https://stackoverflow.com/questions/24791987/why-do-i-get-pickle-eoferror-ran-out-of-input-reading-an-empty-file#:~:text=EOFError%20is%20simply%20raised%2C%20because,just%20meant%20End%20of%20File%20..&text=It%20is%20very%20likely%20that,re%20copying%20and%20pasting%20code.&text=You%20can%20catch%20that%20exception%20and%20return%20whatever%20you%20want%20from%20there. – A.B Sep 01 '20 at 15:10
  • Sure. Thanks for the help here. I up-voted your answer. – ASH Sep 01 '20 at 15:10
  • You are right! The file was empty. I made a few tweaks and it works fine now!! Thanks a lot!! – ASH Sep 01 '20 at 15:27