1

I am trying to run this code (thanks A.B.)

from flask import Flask, jsonify
import pickle
import pandas as pd
import requests

app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
     json_features = requests.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("C:\\Users\\ryans\\kmeans.pkl", "rb"))
     app.run(port=8080)
     

Here is the Traceback:

Traceback (most recent call last):

  File "<ipython-input-27-175d864bb92b>", line 17, in <module>
    app.run(port=8080)

  File "C:\Users\ryans\Anaconda3\lib\site-packages\flask\app.py", line 990, in run
    run_simple(host, port, self, **options)

  File "C:\Users\ryans\Anaconda3\lib\site-packages\werkzeug\serving.py", line 1052, in run_simple
    inner()

  File "C:\Users\ryans\Anaconda3\lib\site-packages\werkzeug\serving.py", line 1005, in inner
    fd=fd,

  File "C:\Users\ryans\Anaconda3\lib\site-packages\werkzeug\serving.py", line 848, in make_server
    host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd

  File "C:\Users\ryans\Anaconda3\lib\site-packages\werkzeug\serving.py", line 740, in __init__
    HTTPServer.__init__(self, server_address, handler)

  File "C:\Users\ryans\Anaconda3\lib\socketserver.py", line 452, in __init__
    self.server_bind()

  File "C:\Users\ryans\Anaconda3\lib\http\server.py", line 137, in server_bind
    socketserver.TCPServer.server_bind(self)

  File "C:\Users\ryans\Anaconda3\lib\socketserver.py", line 466, in server_bind
    self.socket.bind(self.server_address)

OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Finally, here is the model that I am working with.

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
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)


import pickle
filename = 'C:\\Users\\ryans\\kmeans.pkl'
pickle.dump(km, open(filename, 'wb'))
 

# some time later...
pickle_in = open('C:\\Users\\ryans\\kmeans.pkl','rb')
example_dict = pickle.load(pickle_in)

How can I get the model to hit some kind of API endpoint, make a prediction, and show me the results? Thanks.

ASH
  • 15,523
  • 6
  • 50
  • 116
  • 1
    Are you sure port 8080 isn't in use by another application? Are you getting the error on start up (I assume so) or when you hit the endpoint? – Ian Ash Sep 01 '20 at 16:13
  • Oh, I didn't realize that. Ok, I changed it to port 8000 and entered this into my browser: 'http://localhost:8000/' Now, I get this error: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.' – ASH Sep 01 '20 at 19:11
  • 1
    You need to add the endpoint to your URL, i.e. localhost:8000/predict. Depending on your network config you may need to point your browser at 127.0.0.1:8000/predict, rather than use localhost. Note also that your end point is currently configured to respond only to a POST request, where as your browser is going to issue a GET request. – Ian Ash Sep 01 '20 at 19:48
  • I think what you said makes sense. I tried to do what you suggested and unfortunately, none of it worked. I have to do some more research here. I think I am close now, but again, I can't find what I am looking for. Thanks for the help and guidance!! – ASH Sep 01 '20 at 21:39

0 Answers0