Giter Club home page Giter Club logo

sklearnflask's Introduction

Flask API for scikit learn

A simple Flask application that can serve predictions from a scikit-learn model. Reads a pickled sklearn model into memory when the Flask app is started and returns predictions through the /predict endpoint. You can also use the /train endpoint to train/retrain the model. Any sklearn model can be used for prediction.

Read more in this blog post.

Dependencies

  • scikit-learn
  • Flask
  • pandas
  • numpy
pip install -r requirements.txt

Running API

python main.py <port>

Endpoints

/predict (POST)

Returns an array of predictions given a JSON object representing independent variables. Here's a sample input:

[
    {"Age": 85, "Sex": "male", "Embarked": "S"},
    {"Age": 24, "Sex": "female", "Embarked": "C"},
    {"Age": 3, "Sex": "male", "Embarked": "C"},
    {"Age": 21, "Sex": "male", "Embarked": "S"}
]

and sample output:

{"prediction": [0, 1, 1, 0]}

/train (GET)

Trains the model. This is currently hard-coded to be a random forest model that is run on a subset of columns of the titanic dataset.

/wipe (GET)

Removes the trained model.

sklearnflask's People

Contributors

amirziai avatar athuldilip avatar hartziai avatar navidre avatar ucsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sklearnflask's Issues

After /wipe (GET), then the /predict (POST) also have a value output

To solve this problem, We should let clf=None, When we call /wipe(GET).
code show as below:
def wipe():
try:
shutil.rmtree('model')
os.makedirs(model_directory)
global clf
clf = None
return 'Model wiped'

except Exception as e:
    print(str(e))
    return 'Could not remove and recreate the model directory'

Thinks for sharing your code, have a good day.

Error converting prediction list to JSON array

Good work Amir, I am trying to run your code but got the following error, I am using python3 and installed all the requirements.
Intial Analysis:
The error is because prediction list contains int64 type values, but jsonifying this list is throwing this error
return jsonify({'prediction': prediction})
Suggested fix
prediction_str = [str(i) for i in prediction] return jsonify({'prediction': prediction_str})
Converting the int64 list to string array solled the error.
Error:
{
"error": "Object of type 'int64' is not JSON serializable",
"trace": "Traceback (most recent call last):\n File "main.py", line 42, in predict\n return jsonify({'prediction': prediction})\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\site-packages\flask\json.py", line 263, in jsonify\n (dumps(data, indent=indent, separators=separators), '\n'),\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\site-packages\flask\json.py", line 123, in dumps\n rv = _json.dumps(obj, **kwargs)\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\json\init.py", line 238, in dumps\n **kw).encode(obj)\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\json\encoder.py", line 201, in encode\n chunks = list(chunks)\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\json\encoder.py", line 430, in _iterencode\n yield from _iterencode_dict(o, _current_indent_level)\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\json\encoder.py", line 404, in _iterencode_dict\n yield from chunks\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\json\encoder.py", line 325, in _iterencode_list\n yield from chunks\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\json\encoder.py", line 437, in _iterencode\n o = _default(o)\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\site-packages\flask\json.py", line 80, in default\n return _json.JSONEncoder.default(self, o)\n File "C:\Users\vinay\Anaconda3\envs\flask-ml\lib\json\encoder.py", line 180, in default\n o.class.name)\nTypeError: Object of type 'int64' is not JSON serializable\n"
}

Add a License?

This is a really cool project, can you add a license to this?

Error predict

Hi thanks for this repository, for some reason I have the following error:

{
"error": "No objects to concatenate",
"trace": "Traceback (most recent call last):\n File "main.py", line 32, in predict\n query = pd.get_dummies(pd.DataFrame(json_))\n File "C:\Users\AlinaK\Desktop\sklearnflask-master\venv\lib\site-packages\pandas\core\reshape.py", line 1071, in get_dummies\n result = concat(with_dummies, axis=1)\n File "C:\Users\AlinaK\Desktop\sklearnflask-master\venv\lib\site-packages\pandas\tools\merge.py", line 812, in concat\n copy=copy)\n File "C:\Users\AlinaK\Desktop\sklearnflask-master\venv\lib\site-packages\pandas\tools\merge.py", line 845, in init\n raise ValueError('No objects to concatenate')\nValueError: No objects to concatenate\n"
}

Do you know what might it be?

Python 3

Have you gotten around to implementing in python 3?

Predict does not work

Train works for me, but going to /predict returns this error page:

Method Not Allowed
The method is not allowed for the requested URL.

How can this be solved?

reindex columns

hey, thoguht to give you a heads up. When you do this operation:

for col in model_columns:
          if col not in query.columns:
               query[col] = 0

you can actually use the reindex method:
query = query.reindex(columns=model_columns, fill_value=0)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.