Skip to content

Instantly share code, notes, and snippets.

@mnguyenngo
Created August 31, 2018 18:51
Show Gist options
  • Save mnguyenngo/f0a9e3f831f73f3770acf85e71057bc7 to your computer and use it in GitHub Desktop.
Save mnguyenngo/f0a9e3f831f73f3770acf85e71057bc7 to your computer and use it in GitHub Desktop.
Sentiment Classifier as REST API
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
import pickle
import numpy as np
from model import NLPModel
app = Flask(__name__)
api = Api(app)
model = NLPModel()
clf_path = 'lib/models/SentimentClassifier.pkl'
with open(clf_path, 'rb') as f:
model.clf = pickle.load(f)
vec_path = 'lib/models/TFIDFVectorizer.pkl'
with open(vec_path, 'rb') as f:
model.vectorizer = pickle.load(f)
# argument parsing
parser = reqparse.RequestParser()
parser.add_argument('query')
class PredictSentiment(Resource):
def get(self):
# use parser and find the user's query
args = parser.parse_args()
user_query = args['query']
# vectorize the user's query and make a prediction
uq_vectorized = model.vectorizer_transform(np.array([user_query]))
prediction = model.predict(uq_vectorized)
pred_proba = model.predict_proba(uq_vectorized)
# Output either 'Negative' or 'Positive' along with the score
if prediction == 0:
pred_text = 'Negative'
else:
pred_text = 'Positive'
# round the predict proba value and set to new variable
confidence = round(pred_proba[0], 3)
# create JSON object
output = {'prediction': pred_text, 'confidence': confidence}
return output
# Setup the Api resource routing here
# Route the URL to the resource
api.add_resource(PredictSentiment, '/')
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment