diff --git a/.gitignore b/.gitignore index b20b5e1..493b576 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -.idea -.ipynb_checkpoints -mlruns +.idea +.ipynb_checkpoints +mlruns diff --git a/LICENSE b/LICENSE index 261eeb9..29f81d8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,201 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 02fd624..012f227 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,54 @@ -# pythonsevilla2019 -TODO +# pythonsevilla2019 +This repo contains notebooks, code and presentation about the meetup [*Introducción a MLFlow y Databricks: acelerando el Machine Learning Lifecycle*](https://www.meetup.com/Python-Sevilla/events/266430587/) in the meetup group of [Python Sevilla Developers](https://www.meetup.com/Python-Sevilla). + +Slides can be found both on [Slideshare](https://www.slideshare.net/fortega86/pythonsevilla2019-mlflow-introduction) and [in this repository](pythonsevilla2019 - Introducción a MLFlow.pdf) + +## Installation and use +1. ``pip install -r requirements.txt`` +2. ``jupyter notebook`` + +## MLFlow Tracking demo +Run ``jupyter notebook`` and execute the notebook ``tracking.ipynb``. + +To execute the last section is necessary to possess an Azure or AWS account with a deployed Databricks resource. + +## MLFlow Projects demo +The first example uses a public project located in the official MLFlow repository (https://github.com/mlflow/) + +``mlflow run https://github.com/mlflow/mlflow-example.git -P alpha=5`` + +The second example uses our own project (./project_example) + +```bash +cd project_example +mlflow run . -P n_estimators=500 +``` + +## MLFLOW Models demo +Execute the notebook ``models.ipynb``. + +The second part of the demo consist on deploying a trained model from the ``mlruns`` folder that MLFlow creates after tracking experiments. + +So, it is necessary to navigate through the corresponding folder and execute the ``mlflow serve`` command. + +```bash +cd mlruns///artifacts/model/ +mlflow models serve -m . -p 1234 +``` + +After some time, a gunicorn + Flask microservice is deployed on port 1234. It is possible to send http post request by means of programs like Postman. The endpoint is: + +``localhost:1234/invocations`` + +And this is an example of valid body for the request: + +```json +{ + "data": [[ 0.52444161, 0.97309661, 0.43247518, 0.38717859, -1.03377319, + -0.73048166, -0.70972218, -0.41044243, -1.00047971, -0.82507126, + -0.08818832, -0.04623819, -0.18209319, -0.0038316 , -1.04758402, + -0.93257644, -0.65865037, -0.69601737, -0.71241416, -0.25530814, + 0.58767599, 1.36061943, 0.48167379, 0.44795641, -0.62887522, + -0.64418546, -0.62375274, -0.23693879, 0.08147618, 0.05512114]] +} +``` \ No newline at end of file diff --git a/models.ipynb b/models.ipynb new file mode 100644 index 0000000..1a1aef1 --- /dev/null +++ b/models.ipynb @@ -0,0 +1,134 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Introducción a MLFlow y Databricks: acelerando el Machine Learning LifeCycle - Python Sevilla 2019" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## MLFlow Models\n", + "In this section, we can see an example of using a trained model from MLFlow experiments." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Load a trained model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import mlflow\n", + "import mlflow.sklearn\n", + "import numpy as np\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "After decide which model will be used, paste here both experiment_id and run_id." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "experiment_id = \"...\"\n", + "run_id = \"...\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "cancer = load_breast_cancer()\n", + "X = np.array(cancer.data)\n", + "y = np.array(cancer.target)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Feature Scaling\n", + "from sklearn.preprocessing import StandardScaler\n", + "x_train, x_test, y_train, y_test = train_test_split(X, y, train_size=426, test_size=143, random_state=0)\n", + "sc = StandardScaler()\n", + "x_train = sc.fit_transform(x_train)\n", + "x_test = sc.transform(x_test)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "sel = np.random.randint(len(X))\n", + "x_sel = x_test[sel]\n", + "y_sel = y_test[sel]\n", + "print(y_sel)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "model = mlflow.sklearn.load_model(f'./mlruns/{experiment_id}/{run_id}/artifacts/model')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "model.predict([x_sel])" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "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.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/project_example/MLProject b/project_example/MLProject new file mode 100644 index 0000000..699328a --- /dev/null +++ b/project_example/MLProject @@ -0,0 +1,11 @@ +name: tutorial + +conda_env: conda.yaml + +entry_points: + main: + parameters: + n_estimators: {type: int, default: 100} + max_depth: {type: int, default: 2} + criterion: {type: str, default: "gini"} + command: "python train.py {n_estimators} {max_depth} {criterion}" \ No newline at end of file diff --git a/project_example/conda.yaml b/project_example/conda.yaml new file mode 100644 index 0000000..f4db638 --- /dev/null +++ b/project_example/conda.yaml @@ -0,0 +1,8 @@ +name: breast-rf +channels: + - defaults +dependencies: + - numpy=1.14.3 + - pip: + - mlflow==1.3.0 + - scikit-learn==0.22 \ No newline at end of file diff --git a/project_example/train.py b/project_example/train.py new file mode 100644 index 0000000..e7e4e5f --- /dev/null +++ b/project_example/train.py @@ -0,0 +1,58 @@ +import mlflow +import mlflow.sklearn +import numpy as np +from sklearn.datasets import load_breast_cancer +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import StandardScaler +import sys +import warnings +warnings.filterwarnings('ignore') + +# Function to validate a model +def validate_model(model, x_test, y_test): + y_pred = model.predict(x_test) + y_pred = (y_pred > 0.5) + from sklearn.metrics import confusion_matrix + tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel() + precision = tp / (tp + fp) + recall = tp / (tp + fn) + accuracy = (tp + tn) / (tp + fp + tn + fn) + + return precision, recall, accuracy + + +def breast_cancer_rf(n_estimators=100, max_depth=2, criterion="gini"): + from sklearn.ensemble import RandomForestClassifier + import mlflow.sklearn + with mlflow.start_run() as run: + clf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, criterion=criterion) + mlflow.log_param("n_estimators", n_estimators) + mlflow.log_param("max_depth", max_depth) + mlflow.log_param("criterion", criterion) + mlflow.set_tag("model type", "sklearn - RandomForest") + clf.fit(x_train, y_train) + precision, recall, accuracy = validate_model(clf, x_test, y_test) + mlflow.log_metric("precision", precision) + mlflow.log_metric("recall", recall) + mlflow.log_metric("accuracy", accuracy) + mlflow.sklearn.log_model(clf, "model") + print("Model saved in run %s" % mlflow.active_run().info.run_uuid) + + +if __name__ == "__main__": + args = sys.argv[1:] + n_estimators = int(args[0]) + max_depth = int(args[1]) + criterion = args[2] + + cancer = load_breast_cancer() + X = np.array(cancer.data) + y = np.array(cancer.target) + + #Feature Scaling + x_train, x_test, y_train, y_test = train_test_split(X, y, train_size=426, test_size=143, random_state=0) + sc = StandardScaler() + x_train = sc.fit_transform(x_train) + x_test = sc.transform(x_test) + + breast_cancer_rf(n_estimators=n_estimators, max_depth=max_depth, criterion=criterion) \ No newline at end of file diff --git "a/pythonsevilla2019 - Introducci\303\263n a MLFlow.pdf" "b/pythonsevilla2019 - Introducci\303\263n a MLFlow.pdf" new file mode 100644 index 0000000..7e3f277 Binary files /dev/null and "b/pythonsevilla2019 - Introducci\303\263n a MLFlow.pdf" differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..216f652 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +Keras==2.3.1 +mlflow==1.4.0 +numpy==1.17.4 +pandas==0.25.3 +scikit-learn==0.22 +tensorflow==2.0.0 diff --git a/tracking.ipynb b/tracking.ipynb index b6737a6..e06eff5 100644 --- a/tracking.ipynb +++ b/tracking.ipynb @@ -15,19 +15,23 @@ } }, "source": [ - "## MLFlow Tracking" + "## MLFlow Tracking\n", + "This notebook shows some examples of using mlflow library to track useful information about machine learning experiments.\n", + "\n", + "It is necessary to install mlflow (``pip install mlflow``) in the working environment or directly over a simple Python installation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### Basic example" + "### Basic example\n", + "This example show a basic use of mlflow to start an experiment, track parameters and track metrics." ] }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "metadata": { "pycharm": { "is_executing": false, @@ -41,7 +45,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": null, "metadata": { "pycharm": { "is_executing": false, @@ -54,19 +58,25 @@ "mlflow.set_tracking_uri(tracking_uri)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In general, it is not necessary to explicitly call ```mlflow.create_experiment('name')``` before setting it. We can just set the experiment and mlflow will create it if not existed before." + ] + }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "# test_experiment = mlflow.create_experiment('test_1')\n", "mlflow.set_experiment('test_1')" ] }, { "cell_type": "code", - "execution_count": 4, + "execution_count": null, "metadata": { "pycharm": { "is_executing": false, @@ -75,13 +85,24 @@ }, "outputs": [], "source": [ - "run = mlflow.start_run()\n", - "# with mlflow.start_run() as run: -> another alternative" + "run = mlflow.start_run()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another alternative is:\n", + "```python\n", + "with mlflow.start_run() as run:\n", + " ...\n", + "```\n", + "This way prevents calling ``mlflow.end_run()`` to finish the run." ] }, { "cell_type": "code", - "execution_count": 5, + "execution_count": null, "metadata": { "pycharm": { "is_executing": false, @@ -96,7 +117,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": null, "metadata": { "pycharm": { "is_executing": false, @@ -111,7 +132,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": null, "metadata": { "pycharm": { "is_executing": false, @@ -131,38 +152,24 @@ } }, "source": [ - "### Breast cancer: Scikit-learn" + "### Breast cancer: Scikit-learn\n", + "Now, some models will be trained on breast cancer dataset.\n", + "\n", + "So, again, a new experiment is necessary for that." ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": null, "metadata": {}, "outputs": [], - "source": [ - "# experiment = mlflow.create_experiment('breast_cancer')" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "INFO: 'breast_cancer' does not exist. Creating a new experiment\n" - ] - } - ], "source": [ "mlflow.set_experiment('breast_cancer')" ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -176,20 +183,9 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "cancer = load_breast_cancer()\n", "cancer.keys()" @@ -197,37 +193,18 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "sklearn.utils.Bunch" - ] - }, - "execution_count": 26, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "type(cancer)" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "X: (569, 30), y: (569,)\n" - ] - } - ], + "outputs": [], "source": [ "X = np.array(cancer.data)\n", "y = np.array(cancer.target)\n", @@ -236,33 +213,45 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x_train, x_test, y_train, y_test = train_test_split(X, y, train_size=426, test_size=143, random_state=0)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "After splitting the dataset, it is necessary to apply a feature scaling to improve the model's results." + ] + }, { "cell_type": "code", - "execution_count": 14, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "#Feature Scaling\n", "from sklearn.preprocessing import StandardScaler\n", "sc = StandardScaler()\n", "x_train = sc.fit_transform(x_train)\n", "x_test = sc.transform(x_test)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Next function computes three of the most used measures in machine learning." + ] + }, { "cell_type": "code", - "execution_count": 15, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "# Function to validate a model \n", "def validate_model(model, x_test, y_test): \n", " y_pred = model.predict(x_test)\n", " y_pred = (y_pred > 0.5)\n", @@ -275,9 +264,16 @@ " return precision, recall, accuracy" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "First model relies on a Logistic Regression, which is the most used model as baseline for binary classification." + ] + }, { "cell_type": "code", - "execution_count": 16, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -295,34 +291,54 @@ " mlflow.log_metric(\"precision\", precision)\n", " mlflow.log_metric(\"recall\", recall)\n", " mlflow.log_metric(\"accuracy\", accuracy)\n", - " mlflow.sklearn.log_model(lr, \"models\")\n", + " mlflow.sklearn.log_model(lr, \"model\")\n", " print(\"Model saved in run %s\" % mlflow.active_run().info.run_uuid)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And, for example, we can train it three times with different parameters to compare results." + ] + }, { "cell_type": "code", - "execution_count": 17, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Model saved in run 9bafba7ad7e8443098496ebb1ccaa885\n", - "Model saved in run 58be448c055148b0a78c16b431c9785b\n", - "Model saved in run 3d7f599649ae496294a5b8454a29013d\n" - ] - } - ], + "outputs": [], + "source": [ + "breast_cancer_lr()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "breast_cancer_lr(solver=\"liblinear\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ - "breast_cancer_lr()\n", - "breast_cancer_lr(solver=\"liblinear\")\n", "breast_cancer_lr(solver=\"liblinear\", C=0.5)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The second model relies on Random Forest, which is another example of widely used machine learning model for both regression and classification." + ] + }, { "cell_type": "code", - "execution_count": 18, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -341,34 +357,58 @@ " mlflow.log_metric(\"precision\", precision)\n", " mlflow.log_metric(\"recall\", recall)\n", " mlflow.log_metric(\"accuracy\", accuracy)\n", - " mlflow.sklearn.log_model(clf, \"models\")\n", + " mlflow.sklearn.log_model(clf, \"model\")\n", " print(\"Model saved in run %s\" % mlflow.active_run().info.run_uuid)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Again, it is a good idea to train it three times with different parameters." + ] + }, { "cell_type": "code", - "execution_count": 19, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Model saved in run d86c6c4faa58461d9a7014596bfca5ff\n", - "Model saved in run 8ad398b6f51d4e719be0f08ad5c1f808\n", - "Model saved in run 8a72d22516034c5faf8d137f5d2b69e4\n" - ] - } - ], + "outputs": [], + "source": [ + "breast_cancer_rf()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "breast_cancer_rf(max_depth=5)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ - "breast_cancer_rf()\n", - "breast_cancer_rf(max_depth=5)\n", "breast_cancer_rf(n_estimators=500, criterion=\"entropy\")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, we're going to change the kind of model to show an interesting feature of MLFlow Tracking: tracking step.\n", + "\n", + "A tracking step is a log that contains information about a specific iteration during the training process. For instance, in forward backward propagation algorithm to train neural network, several iterations (or epochs) of the same algorithm are execute in order to optimise the neural network weights step by step. The goal is to optimise the loss function to obtain the best effectiveness in the corresponding problem.\n", + "\n", + "In this case, a MultiLayer Perceptron with a unique neuron as output is used. The class ``LossHistory`` is a callback class that defines the behaviour during the epochs of the training process. In this case, we are going to track loss, validation accuracy, and the so-called measures over the test set: precision, recall and accuracy." + ] + }, { "cell_type": "code", - "execution_count": 24, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -414,61 +454,21 @@ " model.fit(x_train, y_train, batch_size=100, nb_epoch=nb_epoch, callbacks=[history])\n", " mlflow.log_param(\"optimizer\", optimizer)\n", " mlflow.log_param(\"dropout\", dropout)\n", - " mlflow.keras.log_model(model, \"models\")" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Epoch 1/20\n", - "426/426 [==============================] - 0s 562us/step - loss: 0.6926 - accuracy: 0.6761\n", - "Epoch 2/20\n", - "426/426 [==============================] - 0s 67us/step - loss: 0.6910 - accuracy: 0.6690\n", - "Epoch 3/20\n", - "426/426 [==============================] - 0s 35us/step - loss: 0.6885 - accuracy: 0.7582\n", - "Epoch 4/20\n", - "426/426 [==============================] - 0s 34us/step - loss: 0.6850 - accuracy: 0.8615\n", - "Epoch 5/20\n", - "426/426 [==============================] - 0s 42us/step - loss: 0.6793 - accuracy: 0.9061\n", - "Epoch 6/20\n", - "426/426 [==============================] - 0s 36us/step - loss: 0.6715 - accuracy: 0.9272\n", - "Epoch 7/20\n", - "426/426 [==============================] - 0s 33us/step - loss: 0.6600 - accuracy: 0.9366\n", - "Epoch 8/20\n", - "426/426 [==============================] - 0s 34us/step - loss: 0.6449 - accuracy: 0.9507\n", - "Epoch 9/20\n", - "426/426 [==============================] - 0s 33us/step - loss: 0.6246 - accuracy: 0.9531\n", - "Epoch 10/20\n", - "426/426 [==============================] - 0s 35us/step - loss: 0.5994 - accuracy: 0.9531\n", - "Epoch 11/20\n", - "426/426 [==============================] - 0s 40us/step - loss: 0.5693 - accuracy: 0.9577\n", - "Epoch 12/20\n", - "426/426 [==============================] - 0s 48us/step - loss: 0.5349 - accuracy: 0.9577\n", - "Epoch 13/20\n", - "426/426 [==============================] - 0s 76us/step - loss: 0.4984 - accuracy: 0.9577\n", - "Epoch 14/20\n", - "426/426 [==============================] - 0s 64us/step - loss: 0.4599 - accuracy: 0.9577\n", - "Epoch 15/20\n", - "426/426 [==============================] - 0s 91us/step - loss: 0.4216 - accuracy: 0.9648\n", - "Epoch 16/20\n", - "426/426 [==============================] - 0s 44us/step - loss: 0.3843 - accuracy: 0.9648\n", - "Epoch 17/20\n", - "426/426 [==============================] - 0s 57us/step - loss: 0.3487 - accuracy: 0.9648\n", - "Epoch 18/20\n", - "426/426 [==============================] - 0s 60us/step - loss: 0.3151 - accuracy: 0.9624\n", - "Epoch 19/20\n", - "426/426 [==============================] - 0s 63us/step - loss: 0.2848 - accuracy: 0.9624\n", - "Epoch 20/20\n", - "426/426 [==============================] - 0s 32us/step - loss: 0.2565 - accuracy: 0.9671\n" - ] - } - ], + " mlflow.keras.log_model(model, \"model\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As before, the model is trained three times with different parameters" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "breast_cancer_keras()" ] @@ -488,12 +488,21 @@ "metadata": {}, "outputs": [], "source": [ - "breast_cancer_keras(dropout=0.25, nb_epoch=100)" + "breast_cancer_keras(optimizer='sgd', dropout=0.4, nb_epoch=100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, the \"model\" is a little bit different: it is a custom code to compute the model output. In this case, we defined a random strategy to predict the output value, just to compare with the previous models.\n", + "\n", + "This model must be defined as a method ``predict`` inside a class that inherits from ``mlflow.pyfunc.PythonModel``. PyFunc is the MLFlow API for custom models" ] }, { "cell_type": "code", - "execution_count": 35, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -506,9 +515,16 @@ " return np.random.randint(2, size=len(model_input))" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Furthermore, we want now to save the dataset that was used to train the models, so we create with this method temporary files in numpy format." + ] + }, { "cell_type": "code", - "execution_count": 39, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -519,9 +535,16 @@ " return outfile" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This model doesn't have a train execution so, we can directly log its results, the model, and the dataset's files." + ] + }, { "cell_type": "code", - "execution_count": 41, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -535,7 +558,7 @@ " mlflow.log_metric(\"accuracy\", accuracy)\n", " mlflow.log_metric(\"f1\", (2 * precision * recall / (precision + recall))) # new metric for this model\n", " # Log custom model by means of pyfunc api\n", - " mlflow.pyfunc.log_model(\"models\", python_model=ccl)\n", + " mlflow.pyfunc.log_model(\"model\", python_model=ccl)\n", " # Log dataset and splits used to train/test\n", " x_train_file = save_numpy_array(x_train)\n", " x_test_file = save_numpy_array(x_test)\n", @@ -547,12 +570,73 @@ " mlflow.log_artifact(y_test_file.name, \"dataset/y_test\")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Remote tracking to Databricks\n", + "Previous models were tracked on localhost, but we can track them on a remote location like Databricks.\n", + "\n", + "It is necessary to define three environment variables: ``MLFLOW_TRACKING_URI``, ``DATABRICKS_HOST`` and ``DATABRICKS_TOKEN``.\n", + "\n", + "An Azure or AWS account is mandatory to execute this notebook's section. It is possible to create a free Azure account with 200$ of credits through this link: https://azure.microsoft.com/en-us/free/search/" + ] + }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "import os\n", + "\n", + "# Configure MLflow to communicate with a Databricks-hosted tracking server\n", + "os.environ[\"MLFLOW_TRACKING_URI\"] = \"databricks\"\n", + "# Specify the workspace hostname and token\n", + "os.environ[\"DATABRICKS_HOST\"] = \"https://.azuredatabricks.net/\"\n", + "os.environ[\"DATABRICKS_TOKEN\"] = \"\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "mlflow.set_tracking_uri(\"databricks\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The experiment is usually created below the active user's space" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "mlflow.set_experiment('/Users//breast_cancer')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "breast_cancer_lr(solver=\"liblinear\", C=0.5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, you can check whether the run was properly created on Databricks or not." + ] } ], "metadata": {