{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "tags": [ "hide-cell" ] }, "outputs": [], "source": [ "# Install the necessary dependencies\n", "\n", "import sys\n", "import os\n", "!{sys.executable} -m pip install --quiet pandas scikit-learn numpy matplotlib jupyterlab_myst ipython requests flask" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "from flask import Flask, request, render_template\n", "import pickle\n", "import sklearn\n", "import requests\n", "from sklearn.preprocessing import LabelEncoder\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.metrics import accuracy_score, classification_report\n", "from sklearn.linear_model import LogisticRegression" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "remove-cell" ] }, "source": [ "---\n", "license:\n", " code: MIT\n", " content: CC-BY-4.0\n", "github: https://github.com/ocademy-ai/machine-learning\n", "venue: By Ocademy\n", "open_access: true\n", "bibliography:\n", " - https://raw.githubusercontent.com/ocademy-ai/machine-learning/main/open-machine-learning-jupyter-book/references.bib\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Build a web app to use a Machine Learning model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section, you will train an ML model on a data set that's out of this world: _UFO sightings over the past century_, sourced from NUFORC's database.\n", "\n", "You will learn:\n", "\n", "- How to 'pickle' a trained model\n", "- How to use that model in a Flask app\n", "\n", "We will continue our use of notebooks to clean data and train our model, but you can take the process one step further by exploring using a model 'in the wild', so to speak: in a web app.\n", "\n", "To do this, you need to build a web app using Flask." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Building an app\n", "\n", "There are several ways to build web apps to consume machine learning models. Your web architecture may influence the way your model is trained. Imagine that you are working in a business where the data science group has trained a model that they want you to use in an app." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Considerations\n", "\n", "There are many questions you need to ask:\n", "\n", "- **Is it a web app or a mobile app?** If you are building a mobile app or need to use the model in an IoT context, you could use [TensorFlow Lite](https://www.tensorflow.org/lite/) and use the model in an Android or iOS app.\n", "- **Where will the model reside?** In the cloud or locally?\n", "- **Offline support.** Does the app have to work offline?\n", "- **What technology was used to train the model?** The chosen technology may influence the tooling you need to use.\n", " - **Using TensorFlow.** If you are training a model using TensorFlow, for example, that ecosystem provides the ability to convert a TensorFlow model for use in a web app by using [TensorFlow.js](https://www.tensorflow.org/js/).\n", " - **Using PyTorch.** If you are building a model using a library such as [PyTorch](https://pytorch.org/), you have the option to export it in [ONNX](https://onnx.ai/) (Open Neural Network Exchange) format for use in JavaScript web apps that can use the [Onnx Runtime](https://www.onnxruntime.ai/). This option will be explored in a future section for a Scikit-learn-trained model.\n", " - **Using Lobe.ai or Azure Custom Vision.** If you are using an ML SaaS (Software as a Service) system such as [Lobe.ai](https://lobe.ai/) or [Azure Custom Vision](https://azure.microsoft.com/services/cognitive-services/custom-vision-service/?WT.mc_id=academic-77952-leestott) to train a model, this type of software provides ways to export the model for many platforms, including building a bespoke API to be queried in the cloud by your online application.\n", "\n", "You also have the opportunity to build an entire Flask web app that would be able to train the model itself in a web browser. This can also be done using TensorFlow.js in a JavaScript context.\n", "\n", "For our purposes, since we have been working with Python-based notebooks, let's explore the steps you need to take to export a trained model from such a notebook to a format readable by a Python-built web app." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tool\n", "\n", "For this task, you need two tools: Flask and Pickle, both of which run on Python.\n", "\n", "✅ What's [Flask](https://palletsprojects.com/p/flask/)? Defined as a 'micro-framework' by its creators, Flask provides the basic features of web frameworks using Python and a templating engine to build web pages. Take a look at [this Learn module](https://docs.microsoft.com/learn/modules/python-flask-build-ai-web-app?WT.mc_id=academic-77952-leestott) to practice building with Flask.\n", "\n", "✅ What's [Pickle](https://docs.python.org/3/library/pickle.html)? Pickle 🥒 is a Python module that serializes and de-serializes a Python object structure. When you 'pickle' a model, you serialize or flatten its structure for use on the web. Be careful: pickle is not intrinsically secure, so be careful if prompted to 'un-pickle' a file. A pickled file has the suffix `.pkl`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise - clean your data\n", "\n", "In this section, you'll use data from 80,000 UFO sightings, gathered by [NUFORC](https://nuforc.org) (The National UFO Reporting Center). This data has some interesting descriptions of UFO sightings, for example:\n", "\n", "- **Long example description.** \"A man emerges from a beam of light that shines on a grassy field at night and he runs towards the Texas Instruments parking lot\".\n", "- **Short example description.** \"the lights chased us\".\n", "\n", "The `ufos.csv` spreadsheet includes columns about the `city`, `state` and `country` where the sighting occurred, the object's `shape` and its `latitude` and `longitude`.\n", "\n", "Create a blank `notebook` to continue the steps below:\n", "\n", "Import `pandas`, `matplotlib`, and `numpy` as you did in the previous section and import the ufos spreadsheet. You can take a look at a sample data set:\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "tags": [ "output_scroll" ] }, "outputs": [], "source": [ "ufos = pd.read_csv(\n", " \"https://static-1300131294.cos.ap-shanghai.myqcloud.com/data/ufos.csv\"\n", ")\n", "ufos.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Convert the ufos data to a small dataframe with fresh titles. Check the unique values in the `Country` field." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['us', nan, 'gb', 'ca', 'au', 'de'], dtype=object)" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ufos = pd.DataFrame(\n", " {\n", " \"Seconds\": ufos[\"duration (seconds)\"],\n", " \"Country\": ufos[\"country\"],\n", " \"Latitude\": ufos[\"latitude\"],\n", " \"Longitude\": ufos[\"longitude\"],\n", " }\n", ")\n", "\n", "ufos.Country.unique()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, you can reduce the amount of data we need to deal with by dropping any null values and only importing sightings between 1-60 seconds:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Int64Index: 25863 entries, 2 to 80330\n", "Data columns (total 4 columns):\n", " # Column Non-Null Count Dtype \n", "--- ------ -------------- ----- \n", " 0 Seconds 25863 non-null float64\n", " 1 Country 25863 non-null object \n", " 2 Latitude 25863 non-null float64\n", " 3 Longitude 25863 non-null float64\n", "dtypes: float64(3), object(1)\n", "memory usage: 1010.3+ KB\n" ] } ], "source": [ "ufos.dropna(inplace=True)\n", "\n", "ufos = ufos[(ufos[\"Seconds\"] >= 1) & (ufos[\"Seconds\"] <= 60)]\n", "\n", "ufos.info()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use Scikit-learn's `LabelEncoder` library to convert the text values for countries to a number:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
SecondsCountryLatitudeLongitude
220.0353.200000-2.916667
320.0428.978333-96.645833
1430.0435.823889-80.253611
2360.0445.582778-122.352222
243.0351.783333-0.783333
\n", "
" ], "text/plain": [ " Seconds Country Latitude Longitude\n", "2 20.0 3 53.200000 -2.916667\n", "3 20.0 4 28.978333 -96.645833\n", "14 30.0 4 35.823889 -80.253611\n", "23 60.0 4 45.582778 -122.352222\n", "24 3.0 3 51.783333 -0.783333" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ufos[\"Country\"] = LabelEncoder().fit_transform(ufos[\"Country\"])\n", "\n", "ufos.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise - build your model\n", "\n", "Now you can get ready to train a model by dividing the data into the training and testing group.\n", "\n", " Select the three features you want to train on as your X vector, and the y vector will be the `Country`. You want to be able to input `Seconds`, `Latitude` and `Longitude` and get a country id to return." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Selected_features = [\"Seconds\", \"Latitude\", \"Longitude\"]\n", "\n", "X = ufos[Selected_features].values\n", "y = ufos[\"Country\"].values\n", "\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Train your model using logistic regression:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " precision recall f1-score support\n", "\n", " 0 1.00 1.00 1.00 41\n", " 1 0.86 0.31 0.45 250\n", " 2 1.00 1.00 1.00 8\n", " 3 1.00 1.00 1.00 131\n", " 4 0.96 1.00 0.98 4743\n", "\n", " accuracy 0.96 5173\n", " macro avg 0.96 0.86 0.89 5173\n", "weighted avg 0.96 0.96 0.96 5173\n", "\n", "Predicted labels: [4 4 4 ... 3 4 4]\n", "Accuracy: 0.9640440750048328\n" ] } ], "source": [ "model = LogisticRegression(solver=\"sag\", max_iter=10000)\n", "model.fit(X_train, y_train)\n", "predictions = model.predict(X_test)\n", "\n", "print(classification_report(y_test, predictions))\n", "print(\"Predicted labels: \", predictions)\n", "print(\"Accuracy: \", accuracy_score(y_test, predictions))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The accuracy isn't bad **(around 95%)**, unsurprisingly, as `Country` and `Latitude/Longitude` correlate.\n", "\n", "The model you created isn't very revolutionary as you should be able to infer a `Country` from its `Latitude` and `Longitude`, but it's a good exercise to try to train from raw data that you cleaned, exported, and then use this model in a web app." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise - 'pickle' your model\n", "\n", "Now, it's time to _pickle_ your model! You can do that in a few lines of code. Once it's _pickled_, load your pickled model and test it against a sample data array containing values for seconds, latitude and longitude." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3]\n" ] } ], "source": [ "# download .pkl file from the cloud\n", "cloud_url = \"https://static-1300131294.cos.ap-shanghai.myqcloud.com/data/ufo-model.pkl\"\n", "model_filename = \"ufo-model.pkl\"\n", "response = requests.get(cloud_url)\n", "with open(model_filename, \"wb\") as local_file:\n", " local_file.write(response.content)\n", "\n", "pickle.dump(model, open(model_filename, \"wb\"))\n", "\n", "model = pickle.load(open(\"ufo-model.pkl\", \"rb\"))\n", "print(model.predict([[50, 44, -12]]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The model returns **'3'**, which is the country code for the UK. Wild! 👽" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise - build a Flask app\n", "\n", "Now you can build a Flask app to call your model and return similar results but in a more visually pleasing way.\n", "\n", "Start by creating a folder called `/web-app` next to the `notebook.ipynb` file where your `ufo-model.pkl` file resides.\n", "\n", "In that folder create three more folders: `/static`, with a folder `/css` inside it, and `/templates`. You should now have the following files and directories:\n", "\n", ":::output\n", "web-app/\n", " static/\n", " css/\n", " templates/\n", "notebook.ipynb\n", "../\n", " assets/\n", " pickle/\n", " ufo-model.pkl\n", ":::\n", "\n", "✅ Refer to the solution folder for a view of the finished app\n", "\n", "The first file to create in `/web-app` folder is `requirements.txt` file. Like `package.json` in a JavaScript app, this file lists dependencies required by the app. In `requirements.txt` add the lines:\n", "\n", ":::text\n", "scikit-learn\n", "pandas\n", "numpy\n", "flask\n", ":::\n", "\n", "Now, run this file by navigating to `/web-app`:\n", "\n", ":::bash\n", "cd web-app\n", ":::\n", "\n", "In your terminal type `pip install`, to install the libraries listed in `requirements.txt`:\n", "\n", ":::bash\n", "pip install -r requirements.txt\n", ":::\n", "\n", "Now, you're ready to create three more files to finish the app:\n", "\n", "1. Create `app.py` in the root.\n", "2. Create `index.html` in `/templates` directory.\n", "3. Create `styles.css` in `/static/css` directory.\n", "\n", "Build out the _styles.css_ file with a few styles:\n", "\n", ":::css\n", "body {\n", " width: 100%;\n", " height: 100%;\n", " font-family: 'Helvetica';\n", " background: black;\n", " color: #fff;\n", " text-align: center;\n", " letter-spacing: 1.4px;\n", " font-size: 30px;\n", "}\n", "\n", "input {\n", " min-width: 150px;\n", "}\n", "\n", ".grid {\n", " width: 300px;\n", " border: 1px solid #2d2d2d;\n", " display: grid;\n", " justify-content: center;\n", " margin: 20px auto;\n", "}\n", "\n", ".box {\n", " color: #fff;\n", " background: #2d2d2d;\n", " padding: 12px;\n", " display: inline-block;\n", "}\n", ":::\n", "\n", "Next, build out the _index.html_ file:\n", "\n", ":::html\n", "\n", "\n", " \n", " \n", " 🛸 UFO Appearance Prediction! 👽\n", " \n", " \n", "\n", " \n", "
\n", "\n", "
\n", "\n", "

According to the number of seconds, latitude and longitude, which country is likely to have reported seeing a UFO?

\n", "\n", "
\n", " \n", " \n", " \n", " \n", "
\n", "\n", "

{{ prediction_text }}

\n", "\n", "
\n", "\n", "
\n", "\n", " \n", "\n", ":::" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Take a look at the templating in this file. Notice the 'mustache' syntax around variables that will be provided by the app, like the prediction text: `{{}}`. There's also a form that posts a prediction to the `/predict` route.\n", "\n", "Finally, you're ready to build the python file that drives the consumption of the model and the display of predictions:\n", "\n", "In `app.py` add:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ":::\n", "app = Flask(__name__)\n", "\n", "model = pickle.load(\n", " open(\n", " \"ufo-model.pkl\",\n", " \"rb\",\n", " )\n", ")\n", "\n", "\n", "@app.route(\"/\")\n", "def home():\n", " return render_template(\"index.html\")\n", "\n", "\n", "@app.route(\"/predict\", methods=[\"POST\"])\n", "def predict():\n", " int_features = [int(x) for x in request.form.values()]\n", " final_features = [np.array(int_features)]\n", " prediction = model.predict(final_features)\n", "\n", " output = prediction[0]\n", "\n", " countries = [\"Australia\", \"Canada\", \"Germany\", \"UK\", \"US\"]\n", "\n", " return render_template(\n", " \"index.html\", prediction_text=\"Likely country: {}\".format(countries[output])\n", " )\n", "\n", "\n", "if __name__ == \"__main__\":\n", " app.run(debug=False)\n", ":::" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "when you add [`debug=True`](https://www.askpython.com/python-modules/flask/flask-debug-mode) while running the web app using Flask, any changes you make to your application will be reflected immediately without the need to restart the server. Beware! Don't enable this mode in a production app." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you run `python app.py` or `python3 app.py` - your web server starts up, locally, and you can fill out a short form to get an answer to your burning question about where UFOs have been sighted!\n", "\n", "Before doing that, take a look at the parts of `app.py`:\n", "\n", "1. First, dependencies are loaded and the app starts.\n", "2. Then, the model is imported.\n", "3. Then, index.html is rendered on the home route.\n", "\n", "On the `/predict` route, several things happen when the form is posted:\n", "\n", "1. The form variables are gathered and converted to a NumPy array. They are then sent to the model and a prediction is returned.\n", "2. The Countries that we want to be displayed are re-rendered as readable text from their predicted country code, and that value is sent back to index.html to be rendered in the template.\n", "\n", "Using a model this way, with Flask and a pickled model, is relatively straightforward. The hardest thing is to understand what shape the data is that must be sent to the model to get a prediction. That all depends on how the model was trained. This one has three data points to be input in order to get a prediction." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Your turn! 🚀\n", "\n", "[build-ml-web-app-1](../assignments/ml-fundamentals/build-ml-web-app-1.ipynb)\n", "\n", "[build-ml-web-app-2](../assignments/ml-fundamentals/build-ml-web-app-2.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Self study\n", "\n", "There are many ways to build a web app to consume ML models. Make a list of the ways you could use JavaScript or Python to build a web app to leverage machine learning. Consider architecture: should the model stay in the app or live in the cloud? If the latter, how would you access it? Draw out an architectural model for an applied ML web solution." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Acknowledgements\n", "\n", "Thanks to Microsoft for creating the open-source course [ML-For-Beginners](https://github.com/microsoft/ML-For-Beginners). It inspires the majority of the content in this chapter." ] } ], "metadata": { "kernelspec": { "display_name": "myconda1", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.16" } }, "nbformat": 4, "nbformat_minor": 2 }