mirror of
https://github.com/Azure/MachineLearningNotebooks.git
synced 2025-12-20 01:27:06 -05:00
Compare commits
499 Commits
release_up
...
cody/add-n
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4aad830f1c | ||
|
|
c1b125025a | ||
|
|
9f364f7638 | ||
|
|
4beb749a76 | ||
|
|
04fe8c4580 | ||
|
|
498018451a | ||
|
|
04305e33f0 | ||
|
|
d22e76d5e0 | ||
|
|
d71c482f75 | ||
|
|
5775f8a78f | ||
|
|
aae823ecd8 | ||
|
|
f1126e07f9 | ||
|
|
0e4b27a233 | ||
|
|
0a3d5f68a1 | ||
|
|
a6fe2affcb | ||
|
|
ce469ddf6a | ||
|
|
9fe459be79 | ||
|
|
89c35c8ed6 | ||
|
|
33168c7f5d | ||
|
|
1d0766bd46 | ||
|
|
9903e56882 | ||
|
|
a039166b90 | ||
|
|
4e4bf48013 | ||
|
|
0a2408300a | ||
|
|
d99c3f5470 | ||
|
|
3f62fe7d47 | ||
|
|
6059c1dc0c | ||
|
|
8e2032fcde | ||
|
|
824d844cd7 | ||
|
|
bb1c7db690 | ||
|
|
8dad09a42f | ||
|
|
db2bf8ae93 | ||
|
|
820c09734f | ||
|
|
a2a33c70a6 | ||
|
|
2ff791968a | ||
|
|
7186127804 | ||
|
|
b01c52bfd6 | ||
|
|
28be7bcf58 | ||
|
|
37a9350fde | ||
|
|
5080053a35 | ||
|
|
3c02102691 | ||
|
|
07e1676762 | ||
|
|
919a3c078f | ||
|
|
9b53c924ed | ||
|
|
04ad58056f | ||
|
|
576bf386b5 | ||
|
|
7e62d1cfd6 | ||
|
|
ec67a569af | ||
|
|
6d1e80bcef | ||
|
|
db00d9ad3c | ||
|
|
d33c75abc3 | ||
|
|
d0dc4836ae | ||
|
|
982f8fcc1d | ||
|
|
79739b5e1b | ||
|
|
aac4fa1fb9 | ||
|
|
5b684070e1 | ||
|
|
0ab8b141ee | ||
|
|
b9ef23ad4b | ||
|
|
7e2c1ca152 | ||
|
|
d096535e48 | ||
|
|
f80512a6db | ||
|
|
b54111620e | ||
|
|
8dd52ee2df | ||
|
|
6c629f1eda | ||
|
|
9c32ca9db5 | ||
|
|
053efde8c9 | ||
|
|
5189691f06 | ||
|
|
745b4f0624 | ||
|
|
fb900916e3 | ||
|
|
738347f3da | ||
|
|
34a67c1f8b | ||
|
|
34898828be | ||
|
|
a7c3a0fdb8 | ||
|
|
6d11cdfa0a | ||
|
|
11e8ed2bab | ||
|
|
12c06a4168 | ||
|
|
1f75dc9725 | ||
|
|
1a1a42d525 | ||
|
|
879a272a8d | ||
|
|
bc65bde097 | ||
|
|
690bdfbdbe | ||
|
|
3c02bd8782 | ||
|
|
5c14610a1c | ||
|
|
4e3afae6fb | ||
|
|
a2144aa083 | ||
|
|
0e6334178f | ||
|
|
4ec9178d22 | ||
|
|
2aa7c53b0c | ||
|
|
553fa43e17 | ||
|
|
e98131729e | ||
|
|
fd2b09e2c2 | ||
|
|
7970209069 | ||
|
|
24f8651bb5 | ||
|
|
b881f78e46 | ||
|
|
057e22b253 | ||
|
|
119fd0a8f6 | ||
|
|
c520bd1d41 | ||
|
|
d3f1212440 | ||
|
|
b95a65eef4 | ||
|
|
2218af619f | ||
|
|
0401128638 | ||
|
|
59fcb54998 | ||
|
|
e0ea99a6bb | ||
|
|
b06f5ce269 | ||
|
|
ed0ce9e895 | ||
|
|
71053d705b | ||
|
|
77f98bf75f | ||
|
|
e443fd1342 | ||
|
|
2165cf308e | ||
|
|
d4a486827d | ||
|
|
3d6caa10a3 | ||
|
|
4df079db1c | ||
|
|
67d0b02ef9 | ||
|
|
4e7b3784d5 | ||
|
|
ed91e39d7e | ||
|
|
a09a1a16a7 | ||
|
|
9662505517 | ||
|
|
8e103c02ff | ||
|
|
ecb5157add | ||
|
|
d7d23d5e7c | ||
|
|
83a21ba53a | ||
|
|
3c9cb89c1a | ||
|
|
cca7c2e26f | ||
|
|
e895d7c2bf | ||
|
|
3588eb9665 | ||
|
|
a09e726f31 | ||
|
|
4fb1d9ee5b | ||
|
|
b05ff80e9d | ||
|
|
512630472b | ||
|
|
ae1337fe70 | ||
|
|
c95f970dc8 | ||
|
|
9b9d112719 | ||
|
|
fe8fcd4b48 | ||
|
|
296ae01587 | ||
|
|
8f4efe15eb | ||
|
|
d179080467 | ||
|
|
0040644e7a | ||
|
|
8aa04307fb | ||
|
|
a525da4488 | ||
|
|
e149565a8a | ||
|
|
75610ec31c | ||
|
|
0c2c450b6b | ||
|
|
0d548eabff | ||
|
|
e4029801e6 | ||
|
|
156974ee7b | ||
|
|
1f05157d24 | ||
|
|
2214ea8616 | ||
|
|
b54b2566de | ||
|
|
57b0f701f8 | ||
|
|
d658c85208 | ||
|
|
a5f627a9b6 | ||
|
|
a8b08bdff0 | ||
|
|
0dc3f34b86 | ||
|
|
9ba7d5e5bb | ||
|
|
c6ad2f8ec0 | ||
|
|
33d6def8c3 | ||
|
|
69d4344dff | ||
|
|
34aeec1439 | ||
|
|
a9b9ebbf7d | ||
|
|
41fa508d53 | ||
|
|
e1bfa98844 | ||
|
|
2bcee9aa20 | ||
|
|
37541b1071 | ||
|
|
4aff1310a7 | ||
|
|
51ecb7c54f | ||
|
|
4e7fc7c82c | ||
|
|
4ed3f0767a | ||
|
|
46ec74f8df | ||
|
|
8d2e362a10 | ||
|
|
86c1b3d760 | ||
|
|
41dc05952f | ||
|
|
df2e08e4a3 | ||
|
|
828a976907 | ||
|
|
1a373f11a0 | ||
|
|
60de701207 | ||
|
|
5841fa4a42 | ||
|
|
659fb7abc3 | ||
|
|
2e404cfc3a | ||
|
|
5fcf4887bc | ||
|
|
1e7f3117ae | ||
|
|
bbb3f85da9 | ||
|
|
c816dfb479 | ||
|
|
8c128640b1 | ||
|
|
4d2b937846 | ||
|
|
5492f52faf | ||
|
|
735db9ebe7 | ||
|
|
573030b990 | ||
|
|
392a059000 | ||
|
|
3580e54fbb | ||
|
|
2017bcd716 | ||
|
|
4a3f8e7025 | ||
|
|
45880114db | ||
|
|
314bad72a4 | ||
|
|
f252308005 | ||
|
|
6622a6c5f2 | ||
|
|
6b19e2f263 | ||
|
|
42fd4598cb | ||
|
|
476d945439 | ||
|
|
e96bb9bef2 | ||
|
|
2be4a5e54d | ||
|
|
247a25f280 | ||
|
|
5d9d8eade6 | ||
|
|
dba978e42a | ||
|
|
7f4101c33e | ||
|
|
62b0d5df69 | ||
|
|
f10b55a1bc | ||
|
|
da9e86635e | ||
|
|
9ca6388996 | ||
|
|
3ce779063b | ||
|
|
ce635ce4fe | ||
|
|
f08e68c8e9 | ||
|
|
93a1d232db | ||
|
|
923483528c | ||
|
|
cbeacb2ab2 | ||
|
|
c928c50707 | ||
|
|
efb42bacf9 | ||
|
|
d8f349a1ae | ||
|
|
96a61fdc78 | ||
|
|
ff8128f023 | ||
|
|
8260302a68 | ||
|
|
fbd7f4a55b | ||
|
|
d4e4206179 | ||
|
|
a98b918feb | ||
|
|
890490ec70 | ||
|
|
c068c9b979 | ||
|
|
f334a3516f | ||
|
|
96248d8dff | ||
|
|
c42e865700 | ||
|
|
9233ce089a | ||
|
|
6bb1e2a3e3 | ||
|
|
e1724c8a89 | ||
|
|
446e0768cc | ||
|
|
8a2f114a16 | ||
|
|
80c0d4d30f | ||
|
|
e8f4708a5a | ||
|
|
fbaeb84204 | ||
|
|
da1fab0a77 | ||
|
|
94d2890bb5 | ||
|
|
4d1ec4f7d4 | ||
|
|
ace3153831 | ||
|
|
58bbfe57b2 | ||
|
|
11ea00b1d9 | ||
|
|
b81efca3e5 | ||
|
|
d7ceb9bca2 | ||
|
|
17730dc69a | ||
|
|
3a029d48a2 | ||
|
|
06d43956f3 | ||
|
|
a1cb9b33a5 | ||
|
|
fdc3fe2a53 | ||
|
|
628b35912c | ||
|
|
3f4cc22e94 | ||
|
|
18d7afb707 | ||
|
|
cd35ca30d4 | ||
|
|
30eae0b46c | ||
|
|
f16951387f | ||
|
|
0d8de29147 | ||
|
|
836354640c | ||
|
|
6162e80972 | ||
|
|
fe9fe3392d | ||
|
|
5ec6d8861b | ||
|
|
ae188f324e | ||
|
|
4c30c2bdb9 | ||
|
|
b891440e2d | ||
|
|
784827cdd2 | ||
|
|
0957af04ca | ||
|
|
a3bdd193d1 | ||
|
|
dff09970ac | ||
|
|
abc7d21711 | ||
|
|
ec12ef635f | ||
|
|
81b3e6f09f | ||
|
|
cc167dceda | ||
|
|
bc52a6d8ee | ||
|
|
5bbbdbe73c | ||
|
|
fd4de05ddd | ||
|
|
9eaab2189d | ||
|
|
12147754b2 | ||
|
|
90ef263823 | ||
|
|
143590cfb4 | ||
|
|
40379014ad | ||
|
|
f7b0e99fa1 | ||
|
|
7a7ac48411 | ||
|
|
50107c5b1e | ||
|
|
e41d7e6819 | ||
|
|
691e038e84 | ||
|
|
426e79d635 | ||
|
|
326677e87f | ||
|
|
44988e30ae | ||
|
|
646ae37384 | ||
|
|
457e29a663 | ||
|
|
2771edfb2c | ||
|
|
f0001ec322 | ||
|
|
d3e02a017d | ||
|
|
a0ebed6876 | ||
|
|
dc0ab6db47 | ||
|
|
ea7900f82c | ||
|
|
0cb3fd180d | ||
|
|
b05c3e46bb | ||
|
|
a1b7d298d3 | ||
|
|
cc5516c3b3 | ||
|
|
4fb6070b89 | ||
|
|
1b926cdf53 | ||
|
|
72fc00fb65 | ||
|
|
ddc6b57253 | ||
|
|
e8b3b98338 | ||
|
|
66325a1405 | ||
|
|
0efbeaf4b8 | ||
|
|
11d487fb28 | ||
|
|
073e319ef9 | ||
|
|
3ed75f28d1 | ||
|
|
bfc0367f54 | ||
|
|
075eeb583f | ||
|
|
b7531d3b9e | ||
|
|
41dc3bd1cf | ||
|
|
b790b385a4 | ||
|
|
8700328fe9 | ||
|
|
adbd2c8200 | ||
|
|
7d552effb0 | ||
|
|
bc81d2a5a7 | ||
|
|
7620de2d91 | ||
|
|
07a43a0444 | ||
|
|
f4d5874e09 | ||
|
|
8a0b4d24bd | ||
|
|
636f19be1f | ||
|
|
0fd7f7d9b2 | ||
|
|
ab6c66534f | ||
|
|
faccf13759 | ||
|
|
4c6a28e4ed | ||
|
|
64ad88e2cb | ||
|
|
969ac90d39 | ||
|
|
fb977c1e95 | ||
|
|
d5ba3916f7 | ||
|
|
f7f1087337 | ||
|
|
47ea2dbc03 | ||
|
|
bd2cf534e5 | ||
|
|
65f1668d69 | ||
|
|
e0fb7df0aa | ||
|
|
7047f76299 | ||
|
|
c39f2d5eb6 | ||
|
|
5fda69a388 | ||
|
|
87ce954eef | ||
|
|
ebbeac413a | ||
|
|
a68bbaaab4 | ||
|
|
8784dc979f | ||
|
|
f8047544fc | ||
|
|
eeb2a05e4f | ||
|
|
6db9d7bd8b | ||
|
|
80e2fde734 | ||
|
|
ae4f5d40ee | ||
|
|
5516edadfd | ||
|
|
475afbf44b | ||
|
|
197eaf1aab | ||
|
|
184680f1d2 | ||
|
|
474f58bd0b | ||
|
|
22c8433897 | ||
|
|
822cdd0f01 | ||
|
|
6e65d42986 | ||
|
|
4c0cbac834 | ||
|
|
44a7481ed1 | ||
|
|
8f418b216d | ||
|
|
2d549ecad3 | ||
|
|
4dbb024529 | ||
|
|
142a1a510e | ||
|
|
2522486c26 | ||
|
|
6d5226e47c | ||
|
|
e7676d7cdc | ||
|
|
a84f6636f1 | ||
|
|
41be10d1c1 | ||
|
|
429eb43914 | ||
|
|
c0dae0c645 | ||
|
|
e4d9a2b4c5 | ||
|
|
7648e8f516 | ||
|
|
b5ed94b4eb | ||
|
|
85e487f74f | ||
|
|
c0a5b2de79 | ||
|
|
0a9e076e5f | ||
|
|
e3b974811d | ||
|
|
381d1a6f35 | ||
|
|
adaa55675e | ||
|
|
5e3c592d4b | ||
|
|
9c6f1e2571 | ||
|
|
bd1bedd563 | ||
|
|
9716f3614e | ||
|
|
d2c72ca149 | ||
|
|
4f62f64207 | ||
|
|
16473eb33e | ||
|
|
d10474c249 | ||
|
|
6389cc16f9 | ||
|
|
bc0a8e0152 | ||
|
|
39384aea52 | ||
|
|
5bf4b0bafe | ||
|
|
f22adb7949 | ||
|
|
8409ab7133 | ||
|
|
32acd55774 | ||
|
|
7f65c1a255 | ||
|
|
bc7ccc7ef3 | ||
|
|
1cc79a71e9 | ||
|
|
c0bec5f110 | ||
|
|
77e5664482 | ||
|
|
e2eb64372a | ||
|
|
03cbb6a3a2 | ||
|
|
44d3d998a8 | ||
|
|
c626f37057 | ||
|
|
0175574864 | ||
|
|
f6e8d57da3 | ||
|
|
01cd31ce44 | ||
|
|
eb2024b3e0 | ||
|
|
6bce41b3d7 | ||
|
|
bbdabbb552 | ||
|
|
65343fc263 | ||
|
|
b6b27fded6 | ||
|
|
7e492cbeb6 | ||
|
|
4cc8f4c6af | ||
|
|
9fba46821b | ||
|
|
a45954a58f | ||
|
|
f16dfb0e5b | ||
|
|
edabbf9031 | ||
|
|
63d1d57dfb | ||
|
|
10f7004161 | ||
|
|
86ba4e7406 | ||
|
|
33bda032b8 | ||
|
|
0fd4bfbc56 | ||
|
|
3fe08c944e | ||
|
|
d587ea5676 | ||
|
|
edd8562102 | ||
|
|
5ac2c63336 | ||
|
|
1f4e4cdda2 | ||
|
|
2e245c1691 | ||
|
|
e1b09f71fa | ||
|
|
8e2220d397 | ||
|
|
f74ccf5048 | ||
|
|
97a6d9ca43 | ||
|
|
a0ff1c6b64 | ||
|
|
08f15ef4cf | ||
|
|
7160416c0b | ||
|
|
218fed3d65 | ||
|
|
b8499dfb98 | ||
|
|
6bfd472cc2 | ||
|
|
ecefb229e9 | ||
|
|
883ad806ba | ||
|
|
848b5bc302 | ||
|
|
58087b53a0 | ||
|
|
ff4d5450a7 | ||
|
|
e2b2b89842 | ||
|
|
390be2ba24 | ||
|
|
cd1258f81d | ||
|
|
8a0b48ea48 | ||
|
|
b0dc904189 | ||
|
|
82bede239a | ||
|
|
774517e173 | ||
|
|
c3ce2bc7fe | ||
|
|
5dd09a1f7c | ||
|
|
ee1da0ee19 | ||
|
|
ddfce6b24c | ||
|
|
31dfc3dc55 | ||
|
|
168c45b188 | ||
|
|
159948db67 | ||
|
|
d842731a3b | ||
|
|
7822fd4c13 | ||
|
|
d9fbe4cd87 | ||
|
|
a64f4d331a | ||
|
|
c41f449208 | ||
|
|
4fe8c1702d | ||
|
|
18cd152591 | ||
|
|
4170a394ed | ||
|
|
475ea36106 | ||
|
|
9e0fc4f0e7 | ||
|
|
b025816c92 | ||
|
|
c75e820107 | ||
|
|
e97e4742ba | ||
|
|
14ecfb0bf3 | ||
|
|
61b396be4f | ||
|
|
3d2552174d | ||
|
|
cd3c980a6e | ||
|
|
249bcac3c7 | ||
|
|
7db93bcb1d | ||
|
|
fcbe925640 | ||
|
|
bedfbd649e | ||
|
|
fb760f648d | ||
|
|
a9a0713d2f | ||
|
|
c9d018b52c | ||
|
|
53dbd0afcf | ||
|
|
e3a64b1f16 | ||
|
|
732eecfc7c | ||
|
|
6995c086ff | ||
|
|
80bba4c7ae | ||
|
|
3c581b533f | ||
|
|
cc688caa4e | ||
|
|
da225e116e | ||
|
|
73c5d02880 | ||
|
|
e472b54f1b | ||
|
|
716c6d8bb1 | ||
|
|
23189c6f40 | ||
|
|
361b57ed29 | ||
|
|
3f531fd211 | ||
|
|
111f5e8d73 | ||
|
|
96c59d5c2b | ||
|
|
ce3214b7c6 | ||
|
|
53199d17de | ||
|
|
54c883412c |
36
README.md
36
README.md
@@ -1,12 +1,11 @@
|
|||||||
# Azure Machine Learning service example notebooks
|
# Azure Machine Learning service example notebooks
|
||||||
|
|
||||||
|
> a community-driven repository of examples using mlflow for tracking can be found at https://github.com/Azure/azureml-examples
|
||||||
|
|
||||||
This repository contains example notebooks demonstrating the [Azure Machine Learning](https://azure.microsoft.com/en-us/services/machine-learning-service/) Python SDK which allows you to build, train, deploy and manage machine learning solutions using Azure. The AML SDK allows you the choice of using local or cloud compute resources, while managing and maintaining the complete data science workflow from the cloud.
|
This repository contains example notebooks demonstrating the [Azure Machine Learning](https://azure.microsoft.com/en-us/services/machine-learning-service/) Python SDK which allows you to build, train, deploy and manage machine learning solutions using Azure. The AML SDK allows you the choice of using local or cloud compute resources, while managing and maintaining the complete data science workflow from the cloud.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## News
|
|
||||||
|
|
||||||
* [Try Azure Machine Learning with MLflow](./how-to-use-azureml/using-mlflow)
|
|
||||||
|
|
||||||
## Quick installation
|
## Quick installation
|
||||||
```sh
|
```sh
|
||||||
@@ -16,16 +15,16 @@ Read more detailed instructions on [how to set up your environment](./NBSETUP.md
|
|||||||
|
|
||||||
## How to navigate and use the example notebooks?
|
## How to navigate and use the example notebooks?
|
||||||
If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, you should always run the [Configuration](./configuration.ipynb) notebook first when setting up a notebook library on a new machine or in a new environment. It configures your notebook library to connect to an Azure Machine Learning workspace, and sets up your workspace and compute to be used by many of the other examples.
|
If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, you should always run the [Configuration](./configuration.ipynb) notebook first when setting up a notebook library on a new machine or in a new environment. It configures your notebook library to connect to an Azure Machine Learning workspace, and sets up your workspace and compute to be used by many of the other examples.
|
||||||
|
This [index](./index.md) should assist in navigating the Azure Machine Learning notebook samples and encourage efficient retrieval of topics and content.
|
||||||
|
|
||||||
If you want to...
|
If you want to...
|
||||||
|
|
||||||
* ...try out and explore Azure ML, start with image classification tutorials: [Part 1 (Training)](./tutorials/img-classification-part1-training.ipynb) and [Part 2 (Deployment)](./tutorials/img-classification-part2-deploy.ipynb).
|
* ...try out and explore Azure ML, start with image classification tutorials: [Part 1 (Training)](./tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb) and [Part 2 (Deployment)](./tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb).
|
||||||
* ...prepare your data and do automated machine learning, start with regression tutorials: [Part 1 (Data Prep)](./tutorials/regression-part1-data-prep.ipynb) and [Part 2 (Automated ML)](./tutorials/regression-part2-automated-ml.ipynb).
|
* ...learn about experimentation and tracking run history, try [training on remote VM](./how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb).
|
||||||
* ...learn about experimentation and tracking run history, first [train within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then try [training on remote VM](./how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb) and [using logging APIs](./how-to-use-azureml/training/logging-api/logging-api.ipynb).
|
* ...train deep learning models at scale, learn about [Machine Learning Compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb)
|
||||||
* ...train deep learning models at scale, first learn about [Machine Learning Compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and then try [distributed hyperparameter tuning](./how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb) and [distributed training](./how-to-use-azureml/training-with-deep-learning/distributed-pytorch-with-horovod/distributed-pytorch-with-horovod.ipynb).
|
* ...deploy models as a realtime scoring service, first learn the basics by [training within Notebook and deploying to Azure Container Instance](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then learn how to [production deploy models on Azure Kubernetes Cluster](./how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb).
|
||||||
* ...deploy models as a realtime scoring service, first learn the basics by [training within Notebook and deploying to Azure Container Instance](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then learn how to [register and manage models, and create Docker images](./how-to-use-azureml/deployment/register-model-create-image-deploy-service/register-model-create-image-deploy-service.ipynb), and [production deploy models on Azure Kubernetes Cluster](./how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb).
|
* ...deploy models as a batch scoring service, [create Machine Learning Compute for scoring compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and [use Machine Learning Pipelines to deploy your model](https://aka.ms/pl-batch-scoring).
|
||||||
* ...deploy models as a batch scoring service, first [train a model within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), learn how to [register and manage models](./how-to-use-azureml/deployment/register-model-create-image-deploy-service/register-model-create-image-deploy-service.ipynb), then [create Machine Learning Compute for scoring compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and [use Machine Learning Pipelines to deploy your model](https://aka.ms/pl-batch-scoring).
|
* ...monitor your deployed models, learn about using [App Insights](./how-to-use-azureml/deployment/enable-app-insights-in-production-service/enable-app-insights-in-production-service.ipynb).
|
||||||
* ...monitor your deployed models, learn about using [App Insights](./how-to-use-azureml/deployment/enable-app-insights-in-production-service/enable-app-insights-in-production-service.ipynb) and [model data collection](./how-to-use-azureml/deployment/enable-data-collection-for-models-in-aks/enable-data-collection-for-models-in-aks.ipynb).
|
|
||||||
|
|
||||||
## Tutorials
|
## Tutorials
|
||||||
|
|
||||||
@@ -36,12 +35,12 @@ The [Tutorials](./tutorials) folder contains notebooks for the tutorials describ
|
|||||||
The [How to use Azure ML](./how-to-use-azureml) folder contains specific examples demonstrating the features of the Azure Machine Learning SDK
|
The [How to use Azure ML](./how-to-use-azureml) folder contains specific examples demonstrating the features of the Azure Machine Learning SDK
|
||||||
|
|
||||||
- [Training](./how-to-use-azureml/training) - Examples of how to build models using Azure ML's logging and execution capabilities on local and remote compute targets
|
- [Training](./how-to-use-azureml/training) - Examples of how to build models using Azure ML's logging and execution capabilities on local and remote compute targets
|
||||||
- [Training with Deep Learning](./how-to-use-azureml/training-with-deep-learning) - Examples demonstrating how to build deep learning models using estimators and parameter sweeps
|
|
||||||
- [Manage Azure ML Service](./how-to-use-azureml/manage-azureml-service) - Examples how to perform tasks, such as authenticate against Azure ML service in different ways.
|
- [Manage Azure ML Service](./how-to-use-azureml/manage-azureml-service) - Examples how to perform tasks, such as authenticate against Azure ML service in different ways.
|
||||||
- [Automated Machine Learning](./how-to-use-azureml/automated-machine-learning) - Examples using Automated Machine Learning to automatically generate optimal machine learning pipelines and models
|
- [Automated Machine Learning](./how-to-use-azureml/automated-machine-learning) - Examples using Automated Machine Learning to automatically generate optimal machine learning pipelines and models
|
||||||
- [Machine Learning Pipelines](./how-to-use-azureml/machine-learning-pipelines) - Examples showing how to create and use reusable pipelines for training and batch scoring
|
- [Machine Learning Pipelines](./how-to-use-azureml/machine-learning-pipelines) - Examples showing how to create and use reusable pipelines for training and batch scoring
|
||||||
- [Deployment](./how-to-use-azureml/deployment) - Examples showing how to deploy and manage machine learning models and solutions
|
- [Deployment](./how-to-use-azureml/deployment) - Examples showing how to deploy and manage machine learning models and solutions
|
||||||
- [Azure Databricks](./how-to-use-azureml/azure-databricks) - Examples showing how to use Azure ML with Azure Databricks
|
- [Azure Databricks](./how-to-use-azureml/azure-databricks) - Examples showing how to use Azure ML with Azure Databricks
|
||||||
|
- [Reinforcement Learning](./how-to-use-azureml/reinforcement-learning) - Examples showing how to train reinforcement learning agents
|
||||||
|
|
||||||
---
|
---
|
||||||
## Documentation
|
## Documentation
|
||||||
@@ -52,16 +51,21 @@ The [How to use Azure ML](./how-to-use-azureml) folder contains specific example
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
|
## Community Repository
|
||||||
|
Visit this [community repository](https://github.com/microsoft/MLOps/tree/master/examples) to find useful end-to-end sample notebooks. Also, please follow these [contribution guidelines](https://github.com/microsoft/MLOps/blob/master/contributing.md) when contributing to this repository.
|
||||||
|
|
||||||
## Projects using Azure Machine Learning
|
## Projects using Azure Machine Learning
|
||||||
|
|
||||||
Visit following repos to see projects contributed by Azure ML users:
|
Visit following repos to see projects contributed by Azure ML users:
|
||||||
|
- [AML Examples](https://github.com/Azure/azureml-examples)
|
||||||
- [AMLSamples](https://github.com/Azure/AMLSamples) Number of end-to-end examples, including face recognition, predictive maintenance, customer churn and sentiment analysis.
|
- [Learn about Natural Language Processing best practices using Azure Machine Learning service](https://github.com/microsoft/nlp)
|
||||||
- [Fine tune natural language processing models using Azure Machine Learning service](https://github.com/Microsoft/AzureML-BERT)
|
- [Pre-Train BERT models using Azure Machine Learning service](https://github.com/Microsoft/AzureML-BERT)
|
||||||
- [Fashion MNIST with Azure ML SDK](https://github.com/amynic/azureml-sdk-fashion)
|
- [Fashion MNIST with Azure ML SDK](https://github.com/amynic/azureml-sdk-fashion)
|
||||||
|
- [UMass Amherst Student Samples](https://github.com/katiehouse3/microsoft-azure-ml-notebooks) - A number of end-to-end machine learning notebooks, including machine translation, image classification, and customer churn, created by students in the 696DS course at UMass Amherst.
|
||||||
|
|
||||||
## Data/Telemetry
|
## Data/Telemetry
|
||||||
This repository collects usage data and sends it to Mircosoft to help improve our products and services. Read Microsoft's [privacy statement to learn more](https://privacy.microsoft.com/en-US/privacystatement)
|
This repository collects usage data and sends it to Microsoft to help improve our products and services. Read Microsoft's [privacy statement to learn more](https://privacy.microsoft.com/en-US/privacystatement)
|
||||||
|
|
||||||
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
|
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
|
||||||
|
|
||||||
|
|||||||
@@ -58,7 +58,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"### What is an Azure Machine Learning workspace\n",
|
"### What is an Azure Machine Learning workspace\n",
|
||||||
"\n",
|
"\n",
|
||||||
"An Azure ML Workspace is an Azure resource that organizes and coordinates the actions of many other Azure resources to assist in executing and sharing machine learning workflows. In particular, an Azure ML Workspace coordinates storage, databases, and compute resources providing added functionality for machine learning experimentation, deployment, inferencing, and the monitoring of deployed models."
|
"An Azure ML Workspace is an Azure resource that organizes and coordinates the actions of many other Azure resources to assist in executing and sharing machine learning workflows. In particular, an Azure ML Workspace coordinates storage, databases, and compute resources providing added functionality for machine learning experimentation, deployment, inference, and the monitoring of deployed models."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -103,7 +103,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"This notebook was created using version 1.0.43 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -214,7 +214,10 @@
|
|||||||
"* You do not have permission to create a resource group if it's non-existing.\n",
|
"* You do not have permission to create a resource group if it's non-existing.\n",
|
||||||
"* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription\n",
|
"* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription\n",
|
||||||
"\n",
|
"\n",
|
||||||
"If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources."
|
"If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources.\n",
|
||||||
|
"\n",
|
||||||
|
"**Note**: A Basic workspace is created by default. If you would like to create an Enterprise workspace, please specify sku = 'enterprise'.\n",
|
||||||
|
"Please visit our [pricing page](https://azure.microsoft.com/en-us/pricing/details/machine-learning/) for more details on our Enterprise edition.\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -235,6 +238,7 @@
|
|||||||
" resource_group = resource_group, \n",
|
" resource_group = resource_group, \n",
|
||||||
" location = workspace_region,\n",
|
" location = workspace_region,\n",
|
||||||
" create_resource_group = True,\n",
|
" create_resource_group = True,\n",
|
||||||
|
" sku = 'basic',\n",
|
||||||
" exist_ok = True)\n",
|
" exist_ok = True)\n",
|
||||||
"ws.get_details()\n",
|
"ws.get_details()\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -357,7 +361,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "roastala"
|
"name": "ninhu"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
|
|||||||
4
configuration.yml
Normal file
4
configuration.yml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
name: configuration
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -287,8 +287,6 @@ Notice how the parameters are modified when using the CPU-only mode.
|
|||||||
|
|
||||||
The outputs of the script can be observed in the master notebook as the script is executed
|
The outputs of the script can be observed in the master notebook as the script is executed
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,13 @@
|
|||||||
"Licensed under the MIT License."
|
"Licensed under the MIT License."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -20,7 +27,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"The [RAPIDS](https://www.developer.nvidia.com/rapids) suite of software libraries from NVIDIA enables the execution of end-to-end data science and analytics pipelines entirely on GPUs. In many machine learning projects, a significant portion of the model training time is spent in setting up the data; this stage of the process is known as Extraction, Transformation and Loading, or ETL. By using the DataFrame API for ETLÂ and GPU-capable ML algorithms in RAPIDS, data preparation and training models can be done in GPU-accelerated end-to-end pipelines without incurring serialization costs between the pipeline stages. This notebook demonstrates how to use NVIDIA RAPIDS to prepare data and train model in Azure.\n",
|
"The [RAPIDS](https://www.developer.nvidia.com/rapids) suite of software libraries from NVIDIA enables the execution of end-to-end data science and analytics pipelines entirely on GPUs. In many machine learning projects, a significant portion of the model training time is spent in setting up the data; this stage of the process is known as Extraction, Transformation and Loading, or ETL. By using the DataFrame API for ETL\u00c2\u00a0and GPU-capable ML algorithms in RAPIDS, data preparation and training models can be done in GPU-accelerated end-to-end pipelines without incurring serialization costs between the pipeline stages. This notebook demonstrates how to use NVIDIA RAPIDS to prepare data and train model\u00c3\u201a\u00c2\u00a0in Azure.\n",
|
||||||
" \n",
|
" \n",
|
||||||
"In this notebook, we will do the following:\n",
|
"In this notebook, we will do the following:\n",
|
||||||
" \n",
|
" \n",
|
||||||
@@ -119,8 +126,10 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
"# if a locally-saved configuration file for the workspace is not available, use the following to load workspace\n",
|
"# if a locally-saved configuration file for the workspace is not available, use the following to load workspace\n",
|
||||||
"# ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, workspace_name=workspace_name)\n",
|
"# ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, workspace_name=workspace_name)\n",
|
||||||
|
"\n",
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
"print('Workspace name: ' + ws.name, \n",
|
||||||
" 'Azure region: ' + ws.location, \n",
|
" 'Azure region: ' + ws.location, \n",
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
" 'Subscription id: ' + ws.subscription_id, \n",
|
||||||
@@ -161,7 +170,7 @@
|
|||||||
"if gpu_cluster_name in ws.compute_targets:\n",
|
"if gpu_cluster_name in ws.compute_targets:\n",
|
||||||
" gpu_cluster = ws.compute_targets[gpu_cluster_name]\n",
|
" gpu_cluster = ws.compute_targets[gpu_cluster_name]\n",
|
||||||
" if gpu_cluster and type(gpu_cluster) is AmlCompute:\n",
|
" if gpu_cluster and type(gpu_cluster) is AmlCompute:\n",
|
||||||
" print('found compute target. just use it. ' + gpu_cluster_name)\n",
|
" print('Found compute target. Will use {0} '.format(gpu_cluster_name))\n",
|
||||||
"else:\n",
|
"else:\n",
|
||||||
" print(\"creating new cluster\")\n",
|
" print(\"creating new cluster\")\n",
|
||||||
" # vm_size parameter below could be modified to one of the RAPIDS-supported VM types\n",
|
" # vm_size parameter below could be modified to one of the RAPIDS-supported VM types\n",
|
||||||
@@ -183,7 +192,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"The _process_data.py_ script used in the step below is a slightly modified implementation of [RAPIDS E2E example](https://github.com/rapidsai/notebooks/blob/master/mortgage/E2E.ipynb)."
|
"The _process_data.py_ script used in the step below is a slightly modified implementation of [RAPIDS Mortgage E2E example](https://github.com/rapidsai/notebooks-contrib/blob/master/intermediate_notebooks/E2E/mortgage/mortgage_e2e.ipynb)."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -194,10 +203,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# copy process_data.py into the script folder\n",
|
"# copy process_data.py into the script folder\n",
|
||||||
"import shutil\n",
|
"import shutil\n",
|
||||||
"shutil.copy('./process_data.py', os.path.join(scripts_folder, 'process_data.py'))\n",
|
"shutil.copy('./process_data.py', os.path.join(scripts_folder, 'process_data.py'))"
|
||||||
"\n",
|
|
||||||
"with open(os.path.join(scripts_folder, './process_data.py'), 'r') as process_data_script:\n",
|
|
||||||
" print(process_data_script.read())"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -221,13 +227,6 @@
|
|||||||
"### Downloading Data"
|
"### Downloading Data"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"<font color='red'>Important</font>: Python package progressbar2 is necessary to run the following cell. If it is not available in your environment where this notebook is running, please install it."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
@@ -237,7 +236,6 @@
|
|||||||
"import tarfile\n",
|
"import tarfile\n",
|
||||||
"import hashlib\n",
|
"import hashlib\n",
|
||||||
"from urllib.request import urlretrieve\n",
|
"from urllib.request import urlretrieve\n",
|
||||||
"from progressbar import ProgressBar\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"def validate_downloaded_data(path):\n",
|
"def validate_downloaded_data(path):\n",
|
||||||
" if(os.path.isdir(path) and os.path.exists(path + '//names.csv')) :\n",
|
" if(os.path.isdir(path) and os.path.exists(path + '//names.csv')) :\n",
|
||||||
@@ -267,7 +265,7 @@
|
|||||||
" url_format = 'http://rapidsai-data.s3-website.us-east-2.amazonaws.com/notebook-mortgage-data/{0}.tgz'\n",
|
" url_format = 'http://rapidsai-data.s3-website.us-east-2.amazonaws.com/notebook-mortgage-data/{0}.tgz'\n",
|
||||||
" url = url_format.format(fileroot)\n",
|
" url = url_format.format(fileroot)\n",
|
||||||
" print(\"...Downloading file :{0}\".format(filename))\n",
|
" print(\"...Downloading file :{0}\".format(filename))\n",
|
||||||
" urlretrieve(url, filename,show_progress)\n",
|
" urlretrieve(url, filename)\n",
|
||||||
" pbar.finish()\n",
|
" pbar.finish()\n",
|
||||||
" print(\"...File :{0} finished downloading\".format(filename))\n",
|
" print(\"...File :{0} finished downloading\".format(filename))\n",
|
||||||
" else:\n",
|
" else:\n",
|
||||||
@@ -282,9 +280,7 @@
|
|||||||
" so_far = 0\n",
|
" so_far = 0\n",
|
||||||
" for member_info in members:\n",
|
" for member_info in members:\n",
|
||||||
" tar.extract(member_info,path=path)\n",
|
" tar.extract(member_info,path=path)\n",
|
||||||
" show_progress(so_far, 1, numFiles)\n",
|
|
||||||
" so_far += 1\n",
|
" so_far += 1\n",
|
||||||
" pbar.finish()\n",
|
|
||||||
" print(\"...All {0} files have been decompressed\".format(numFiles))\n",
|
" print(\"...All {0} files have been decompressed\".format(numFiles))\n",
|
||||||
" tar.close()"
|
" tar.close()"
|
||||||
]
|
]
|
||||||
@@ -324,7 +320,9 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"# download and uncompress data in a local directory before uploading to data store\n",
|
"# download and uncompress data in a local directory before uploading to data store\n",
|
||||||
"# directory specified in src_dir parameter below should have the acq, perf directories with data and names.csv file\n",
|
"# directory specified in src_dir parameter below should have the acq, perf directories with data and names.csv file\n",
|
||||||
"ds.upload(src_dir=path, target_path=fileroot, overwrite=True, show_progress=True)\n",
|
"\n",
|
||||||
|
"# ---->>>> UNCOMMENT THE BELOW LINE TO UPLOAD YOUR DATA IF NOT DONE SO ALREADY <<<<----\n",
|
||||||
|
"# ds.upload(src_dir=path, target_path=fileroot, overwrite=True, show_progress=True)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# data already uploaded to the datastore\n",
|
"# data already uploaded to the datastore\n",
|
||||||
"data_ref = DataReference(data_reference_name='data', datastore=ds, path_on_datastore=fileroot)"
|
"data_ref = DataReference(data_reference_name='data', datastore=ds, path_on_datastore=fileroot)"
|
||||||
@@ -360,7 +358,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"The following code shows how to use an existing image from [Docker Hub](https://hub.docker.com/r/rapidsai/rapidsai/) that has a prebuilt conda environment named 'rapids' when creating a RunConfiguration. Note that this conda environment does not include azureml-defaults package that is required for using AML functionality like metrics tracking, model management etc. This package is automatically installed when you use 'Specify package dependencies' option and that is why it is the recommended option to create RunConfiguraiton in AML."
|
"The following code shows how to install RAPIDS using conda. The `rapids.yml` file contains the list of packages necessary to run this tutorial. **NOTE:** Initial build of the image might take up to 20 minutes as the service needs to build and cache the new image; once the image is built the subequent runs use the cached image and the overhead is minimal."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -369,17 +367,13 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"run_config = RunConfiguration()\n",
|
"cd = CondaDependencies(conda_dependencies_file_path='rapids.yml')\n",
|
||||||
|
"run_config = RunConfiguration(conda_dependencies=cd)\n",
|
||||||
"run_config.framework = 'python'\n",
|
"run_config.framework = 'python'\n",
|
||||||
"run_config.environment.python.user_managed_dependencies = True\n",
|
|
||||||
"run_config.environment.python.interpreter_path = '/conda/envs/rapids/bin/python'\n",
|
|
||||||
"run_config.target = gpu_cluster_name\n",
|
"run_config.target = gpu_cluster_name\n",
|
||||||
"run_config.environment.docker.enabled = True\n",
|
"run_config.environment.docker.enabled = True\n",
|
||||||
"run_config.environment.docker.gpu_support = True\n",
|
"run_config.environment.docker.gpu_support = True\n",
|
||||||
"run_config.environment.docker.base_image = \"rapidsai/rapidsai:cuda9.2-runtime-ubuntu18.04\"\n",
|
"run_config.environment.docker.base_image = \"mcr.microsoft.com/azureml/base-gpu:intelmpi2018.3-cuda10.0-cudnn7-ubuntu16.04\"\n",
|
||||||
"# run_config.environment.docker.base_image_registry.address = '<registry_url>' # not required if the base_image is in Docker hub\n",
|
|
||||||
"# run_config.environment.docker.base_image_registry.username = '<user_name>' # needed only for private images\n",
|
|
||||||
"# run_config.environment.docker.base_image_registry.password = '<password>' # needed only for private images\n",
|
|
||||||
"run_config.environment.spark.precache_packages = False\n",
|
"run_config.environment.spark.precache_packages = False\n",
|
||||||
"run_config.data_references={'data':data_ref.to_config()}"
|
"run_config.data_references={'data':data_ref.to_config()}"
|
||||||
]
|
]
|
||||||
@@ -388,14 +382,14 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Specify package dependencies"
|
"#### Using Docker"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"The following code shows how to list package dependencies in a conda environment definition file (rapids.yml) when creating a RunConfiguration"
|
"Alternatively, you can specify RAPIDS Docker image."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -404,16 +398,17 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# cd = CondaDependencies(conda_dependencies_file_path='rapids.yml')\n",
|
"# run_config = RunConfiguration()\n",
|
||||||
"# run_config = RunConfiguration(conda_dependencies=cd)\n",
|
|
||||||
"# run_config.framework = 'python'\n",
|
"# run_config.framework = 'python'\n",
|
||||||
|
"# run_config.environment.python.user_managed_dependencies = True\n",
|
||||||
|
"# run_config.environment.python.interpreter_path = '/conda/envs/rapids/bin/python'\n",
|
||||||
"# run_config.target = gpu_cluster_name\n",
|
"# run_config.target = gpu_cluster_name\n",
|
||||||
"# run_config.environment.docker.enabled = True\n",
|
"# run_config.environment.docker.enabled = True\n",
|
||||||
"# run_config.environment.docker.gpu_support = True\n",
|
"# run_config.environment.docker.gpu_support = True\n",
|
||||||
"# run_config.environment.docker.base_image = \"<image>\"\n",
|
"# run_config.environment.docker.base_image = \"rapidsai/rapidsai:cuda9.2-runtime-ubuntu18.04\"\n",
|
||||||
"# run_config.environment.docker.base_image_registry.address = '<registry_url>' # not required if the base_image is in Docker hub\n",
|
"# # run_config.environment.docker.base_image_registry.address = '<registry_url>' # not required if the base_image is in Docker hub\n",
|
||||||
"# run_config.environment.docker.base_image_registry.username = '<user_name>' # needed only for private images\n",
|
"# # run_config.environment.docker.base_image_registry.username = '<user_name>' # needed only for private images\n",
|
||||||
"# run_config.environment.docker.base_image_registry.password = '<password>' # needed only for private images\n",
|
"# # run_config.environment.docker.base_image_registry.password = '<password>' # needed only for private images\n",
|
||||||
"# run_config.environment.spark.precache_packages = False\n",
|
"# run_config.environment.spark.precache_packages = False\n",
|
||||||
"# run_config.data_references={'data':data_ref.to_config()}"
|
"# run_config.data_references={'data':data_ref.to_config()}"
|
||||||
]
|
]
|
||||||
@@ -551,9 +546,9 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.6"
|
"version": "3.6.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 2
|
"nbformat_minor": 4
|
||||||
}
|
}
|
||||||
@@ -15,21 +15,6 @@ from glob import glob
|
|||||||
import os
|
import os
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
def initialize_rmm_pool():
|
|
||||||
from librmm_cffi import librmm_config as rmm_cfg
|
|
||||||
|
|
||||||
rmm_cfg.use_pool_allocator = True
|
|
||||||
#rmm_cfg.initial_pool_size = 2<<30 # set to 2GiB. Default is 1/2 total GPU memory
|
|
||||||
import cudf
|
|
||||||
return cudf._gdf.rmm_initialize()
|
|
||||||
|
|
||||||
def initialize_rmm_no_pool():
|
|
||||||
from librmm_cffi import librmm_config as rmm_cfg
|
|
||||||
|
|
||||||
rmm_cfg.use_pool_allocator = False
|
|
||||||
import cudf
|
|
||||||
return cudf._gdf.rmm_initialize()
|
|
||||||
|
|
||||||
def run_dask_task(func, **kwargs):
|
def run_dask_task(func, **kwargs):
|
||||||
task = func(**kwargs)
|
task = func(**kwargs)
|
||||||
return task
|
return task
|
||||||
@@ -207,26 +192,26 @@ def gpu_load_names(col_path):
|
|||||||
|
|
||||||
def create_ever_features(gdf, **kwargs):
|
def create_ever_features(gdf, **kwargs):
|
||||||
everdf = gdf[['loan_id', 'current_loan_delinquency_status']]
|
everdf = gdf[['loan_id', 'current_loan_delinquency_status']]
|
||||||
everdf = everdf.groupby('loan_id', method='hash').max()
|
everdf = everdf.groupby('loan_id', method='hash').max().reset_index()
|
||||||
del(gdf)
|
del(gdf)
|
||||||
everdf['ever_30'] = (everdf['max_current_loan_delinquency_status'] >= 1).astype('int8')
|
everdf['ever_30'] = (everdf['current_loan_delinquency_status'] >= 1).astype('int8')
|
||||||
everdf['ever_90'] = (everdf['max_current_loan_delinquency_status'] >= 3).astype('int8')
|
everdf['ever_90'] = (everdf['current_loan_delinquency_status'] >= 3).astype('int8')
|
||||||
everdf['ever_180'] = (everdf['max_current_loan_delinquency_status'] >= 6).astype('int8')
|
everdf['ever_180'] = (everdf['current_loan_delinquency_status'] >= 6).astype('int8')
|
||||||
everdf.drop_column('max_current_loan_delinquency_status')
|
everdf.drop_column('current_loan_delinquency_status')
|
||||||
return everdf
|
return everdf
|
||||||
|
|
||||||
def create_delinq_features(gdf, **kwargs):
|
def create_delinq_features(gdf, **kwargs):
|
||||||
delinq_gdf = gdf[['loan_id', 'monthly_reporting_period', 'current_loan_delinquency_status']]
|
delinq_gdf = gdf[['loan_id', 'monthly_reporting_period', 'current_loan_delinquency_status']]
|
||||||
del(gdf)
|
del(gdf)
|
||||||
delinq_30 = delinq_gdf.query('current_loan_delinquency_status >= 1')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min()
|
delinq_30 = delinq_gdf.query('current_loan_delinquency_status >= 1')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min().reset_index()
|
||||||
delinq_30['delinquency_30'] = delinq_30['min_monthly_reporting_period']
|
delinq_30['delinquency_30'] = delinq_30['monthly_reporting_period']
|
||||||
delinq_30.drop_column('min_monthly_reporting_period')
|
delinq_30.drop_column('monthly_reporting_period')
|
||||||
delinq_90 = delinq_gdf.query('current_loan_delinquency_status >= 3')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min()
|
delinq_90 = delinq_gdf.query('current_loan_delinquency_status >= 3')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min().reset_index()
|
||||||
delinq_90['delinquency_90'] = delinq_90['min_monthly_reporting_period']
|
delinq_90['delinquency_90'] = delinq_90['monthly_reporting_period']
|
||||||
delinq_90.drop_column('min_monthly_reporting_period')
|
delinq_90.drop_column('monthly_reporting_period')
|
||||||
delinq_180 = delinq_gdf.query('current_loan_delinquency_status >= 6')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min()
|
delinq_180 = delinq_gdf.query('current_loan_delinquency_status >= 6')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min().reset_index()
|
||||||
delinq_180['delinquency_180'] = delinq_180['min_monthly_reporting_period']
|
delinq_180['delinquency_180'] = delinq_180['monthly_reporting_period']
|
||||||
delinq_180.drop_column('min_monthly_reporting_period')
|
delinq_180.drop_column('monthly_reporting_period')
|
||||||
del(delinq_gdf)
|
del(delinq_gdf)
|
||||||
delinq_merge = delinq_30.merge(delinq_90, how='left', on=['loan_id'], type='hash')
|
delinq_merge = delinq_30.merge(delinq_90, how='left', on=['loan_id'], type='hash')
|
||||||
delinq_merge['delinquency_90'] = delinq_merge['delinquency_90'].fillna(np.dtype('datetime64[ms]').type('1970-01-01').astype('datetime64[ms]'))
|
delinq_merge['delinquency_90'] = delinq_merge['delinquency_90'].fillna(np.dtype('datetime64[ms]').type('1970-01-01').astype('datetime64[ms]'))
|
||||||
@@ -279,16 +264,15 @@ def create_joined_df(gdf, everdf, **kwargs):
|
|||||||
def create_12_mon_features(joined_df, **kwargs):
|
def create_12_mon_features(joined_df, **kwargs):
|
||||||
testdfs = []
|
testdfs = []
|
||||||
n_months = 12
|
n_months = 12
|
||||||
|
|
||||||
for y in range(1, n_months + 1):
|
for y in range(1, n_months + 1):
|
||||||
tmpdf = joined_df[['loan_id', 'timestamp_year', 'timestamp_month', 'delinquency_12', 'upb_12']]
|
tmpdf = joined_df[['loan_id', 'timestamp_year', 'timestamp_month', 'delinquency_12', 'upb_12']]
|
||||||
tmpdf['josh_months'] = tmpdf['timestamp_year'] * 12 + tmpdf['timestamp_month']
|
tmpdf['josh_months'] = tmpdf['timestamp_year'] * 12 + tmpdf['timestamp_month']
|
||||||
tmpdf['josh_mody_n'] = ((tmpdf['josh_months'].astype('float64') - 24000 - y) / 12).floor()
|
tmpdf['josh_mody_n'] = ((tmpdf['josh_months'].astype('float64') - 24000 - y) / 12).floor()
|
||||||
tmpdf = tmpdf.groupby(['loan_id', 'josh_mody_n'], method='hash').agg({'delinquency_12': 'max','upb_12': 'min'})
|
tmpdf = tmpdf.groupby(['loan_id', 'josh_mody_n'], method='hash').agg({'delinquency_12': 'max','upb_12': 'min'}).reset_index()
|
||||||
tmpdf['delinquency_12'] = (tmpdf['max_delinquency_12']>3).astype('int32')
|
tmpdf['delinquency_12'] = (tmpdf['delinquency_12']>3).astype('int32')
|
||||||
tmpdf['delinquency_12'] +=(tmpdf['min_upb_12']==0).astype('int32')
|
tmpdf['delinquency_12'] +=(tmpdf['upb_12']==0).astype('int32')
|
||||||
tmpdf.drop_column('max_delinquency_12')
|
tmpdf['upb_12'] = tmpdf['upb_12']
|
||||||
tmpdf['upb_12'] = tmpdf['min_upb_12']
|
|
||||||
tmpdf.drop_column('min_upb_12')
|
|
||||||
tmpdf['timestamp_year'] = (((tmpdf['josh_mody_n'] * n_months) + 24000 + (y - 1)) / 12).floor().astype('int16')
|
tmpdf['timestamp_year'] = (((tmpdf['josh_mody_n'] * n_months) + 24000 + (y - 1)) / 12).floor().astype('int16')
|
||||||
tmpdf['timestamp_month'] = np.int8(y)
|
tmpdf['timestamp_month'] = np.int8(y)
|
||||||
tmpdf.drop_column('josh_mody_n')
|
tmpdf.drop_column('josh_mody_n')
|
||||||
@@ -329,6 +313,7 @@ def last_mile_cleaning(df, **kwargs):
|
|||||||
'delinquency_30', 'delinquency_90', 'delinquency_180', 'upb_12',
|
'delinquency_30', 'delinquency_90', 'delinquency_180', 'upb_12',
|
||||||
'zero_balance_effective_date','foreclosed_after', 'disposition_date','timestamp'
|
'zero_balance_effective_date','foreclosed_after', 'disposition_date','timestamp'
|
||||||
]
|
]
|
||||||
|
|
||||||
for column in drop_list:
|
for column in drop_list:
|
||||||
df.drop_column(column)
|
df.drop_column(column)
|
||||||
for col, dtype in df.dtypes.iteritems():
|
for col, dtype in df.dtypes.iteritems():
|
||||||
@@ -342,7 +327,6 @@ def last_mile_cleaning(df, **kwargs):
|
|||||||
return df.to_arrow(preserve_index=False)
|
return df.to_arrow(preserve_index=False)
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
#print('XGBOOST_BUILD_DOC is ' + os.environ['XGBOOST_BUILD_DOC'])
|
|
||||||
parser = argparse.ArgumentParser("rapidssample")
|
parser = argparse.ArgumentParser("rapidssample")
|
||||||
parser.add_argument("--data_dir", type=str, help="location of data")
|
parser.add_argument("--data_dir", type=str, help="location of data")
|
||||||
parser.add_argument("--num_gpu", type=int, help="Number of GPUs to use", default=1)
|
parser.add_argument("--num_gpu", type=int, help="Number of GPUs to use", default=1)
|
||||||
@@ -364,7 +348,6 @@ def main():
|
|||||||
print('data_dir = {0}'.format(data_dir))
|
print('data_dir = {0}'.format(data_dir))
|
||||||
print('num_gpu = {0}'.format(num_gpu))
|
print('num_gpu = {0}'.format(num_gpu))
|
||||||
print('part_count = {0}'.format(part_count))
|
print('part_count = {0}'.format(part_count))
|
||||||
#part_count = part_count + 1 # adding one because the usage below is not inclusive
|
|
||||||
print('end_year = {0}'.format(end_year))
|
print('end_year = {0}'.format(end_year))
|
||||||
print('cpu_predictor = {0}'.format(cpu_predictor))
|
print('cpu_predictor = {0}'.format(cpu_predictor))
|
||||||
|
|
||||||
@@ -380,19 +363,17 @@ def main():
|
|||||||
client
|
client
|
||||||
print(client.ncores())
|
print(client.ncores())
|
||||||
|
|
||||||
# to download data for this notebook, visit https://rapidsai.github.io/demos/datasets/mortgage-data and update the following paths accordingly
|
# to download data for this notebook, visit https://rapidsai.github.io/demos/datasets/mortgage-data and update the following paths accordingly
|
||||||
acq_data_path = "{0}/acq".format(data_dir) #"/rapids/data/mortgage/acq"
|
acq_data_path = "{0}/acq".format(data_dir) #"/rapids/data/mortgage/acq"
|
||||||
perf_data_path = "{0}/perf".format(data_dir) #"/rapids/data/mortgage/perf"
|
perf_data_path = "{0}/perf".format(data_dir) #"/rapids/data/mortgage/perf"
|
||||||
col_names_path = "{0}/names.csv".format(data_dir) # "/rapids/data/mortgage/names.csv"
|
col_names_path = "{0}/names.csv".format(data_dir) # "/rapids/data/mortgage/names.csv"
|
||||||
start_year = 2000
|
start_year = 2000
|
||||||
#end_year = 2000 # end_year is inclusive -- converted to parameter
|
|
||||||
#part_count = 2 # the number of data files to train against -- converted to parameter
|
|
||||||
|
|
||||||
client.run(initialize_rmm_pool)
|
|
||||||
client
|
client
|
||||||
print(client.ncores())
|
print('--->>> Workers used: {0}'.format(client.ncores()))
|
||||||
# NOTE: The ETL calculates additional features which are then dropped before creating the XGBoost DMatrix.
|
|
||||||
# This can be optimized to avoid calculating the dropped features.
|
# NOTE: The ETL calculates additional features which are then dropped before creating the XGBoost DMatrix.
|
||||||
|
# This can be optimized to avoid calculating the dropped features.
|
||||||
print("Reading ...")
|
print("Reading ...")
|
||||||
t1 = datetime.datetime.now()
|
t1 = datetime.datetime.now()
|
||||||
gpu_dfs = []
|
gpu_dfs = []
|
||||||
@@ -414,14 +395,9 @@ def main():
|
|||||||
|
|
||||||
wait(gpu_dfs)
|
wait(gpu_dfs)
|
||||||
t2 = datetime.datetime.now()
|
t2 = datetime.datetime.now()
|
||||||
print("Reading time ...")
|
print("Reading time: {0}".format(str(t2-t1)))
|
||||||
print(t2-t1)
|
print('--->>> Number of data parts: {0}'.format(len(gpu_dfs)))
|
||||||
print('len(gpu_dfs) is {0}'.format(len(gpu_dfs)))
|
|
||||||
|
|
||||||
client.run(cudf._gdf.rmm_finalize)
|
|
||||||
client.run(initialize_rmm_no_pool)
|
|
||||||
client
|
|
||||||
print(client.ncores())
|
|
||||||
dxgb_gpu_params = {
|
dxgb_gpu_params = {
|
||||||
'nround': 100,
|
'nround': 100,
|
||||||
'max_depth': 8,
|
'max_depth': 8,
|
||||||
@@ -438,7 +414,7 @@ def main():
|
|||||||
'n_gpus': 1,
|
'n_gpus': 1,
|
||||||
'distributed_dask': True,
|
'distributed_dask': True,
|
||||||
'loss': 'ls',
|
'loss': 'ls',
|
||||||
'objective': 'gpu:reg:linear',
|
'objective': 'reg:squarederror',
|
||||||
'max_features': 'auto',
|
'max_features': 'auto',
|
||||||
'criterion': 'friedman_mse',
|
'criterion': 'friedman_mse',
|
||||||
'grow_policy': 'lossguide',
|
'grow_policy': 'lossguide',
|
||||||
@@ -446,13 +422,13 @@ def main():
|
|||||||
}
|
}
|
||||||
|
|
||||||
if cpu_predictor:
|
if cpu_predictor:
|
||||||
print('Training using CPUs')
|
print('\n---->>>> Training using CPUs <<<<----\n')
|
||||||
dxgb_gpu_params['predictor'] = 'cpu_predictor'
|
dxgb_gpu_params['predictor'] = 'cpu_predictor'
|
||||||
dxgb_gpu_params['tree_method'] = 'hist'
|
dxgb_gpu_params['tree_method'] = 'hist'
|
||||||
dxgb_gpu_params['objective'] = 'reg:linear'
|
dxgb_gpu_params['objective'] = 'reg:linear'
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print('Training using GPUs')
|
print('\n---->>>> Training using GPUs <<<<----\n')
|
||||||
|
|
||||||
print('Training parameters are {0}'.format(dxgb_gpu_params))
|
print('Training parameters are {0}'.format(dxgb_gpu_params))
|
||||||
|
|
||||||
@@ -482,13 +458,12 @@ def main():
|
|||||||
gc.collect()
|
gc.collect()
|
||||||
wait(gpu_dfs)
|
wait(gpu_dfs)
|
||||||
|
|
||||||
|
# TRAIN THE MODEL
|
||||||
labels = None
|
labels = None
|
||||||
t1 = datetime.datetime.now()
|
t1 = datetime.datetime.now()
|
||||||
bst = dxgb_gpu.train(client, dxgb_gpu_params, gpu_dfs, labels, num_boost_round=dxgb_gpu_params['nround'])
|
bst = dxgb_gpu.train(client, dxgb_gpu_params, gpu_dfs, labels, num_boost_round=dxgb_gpu_params['nround'])
|
||||||
t2 = datetime.datetime.now()
|
t2 = datetime.datetime.now()
|
||||||
print("Training time ...")
|
print('\n---->>>> Training time: {0} <<<<----\n'.format(str(t2-t1)))
|
||||||
print(t2-t1)
|
|
||||||
print('str(bst) is {0}'.format(str(bst)))
|
|
||||||
print('Exiting script')
|
print('Exiting script')
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
name: rapids
|
|
||||||
channels:
|
|
||||||
- nvidia
|
|
||||||
- numba
|
|
||||||
- conda-forge
|
|
||||||
- rapidsai
|
|
||||||
- defaults
|
|
||||||
- pytorch
|
|
||||||
|
|
||||||
dependencies:
|
|
||||||
- arrow-cpp=0.12.0
|
|
||||||
- bokeh
|
|
||||||
- cffi=1.11.5
|
|
||||||
- cmake=3.12
|
|
||||||
- cuda92
|
|
||||||
- cython==0.29
|
|
||||||
- dask=1.1.1
|
|
||||||
- distributed=1.25.3
|
|
||||||
- faiss-gpu=1.5.0
|
|
||||||
- numba=0.42
|
|
||||||
- numpy=1.15.4
|
|
||||||
- nvstrings
|
|
||||||
- pandas=0.23.4
|
|
||||||
- pyarrow=0.12.0
|
|
||||||
- scikit-learn
|
|
||||||
- scipy
|
|
||||||
- cudf
|
|
||||||
- cuml
|
|
||||||
- python=3.6.2
|
|
||||||
- jupyterlab
|
|
||||||
- pip:
|
|
||||||
- file:/rapids/xgboost/python-package/dist/xgboost-0.81-py3-none-any.whl
|
|
||||||
- git+https://github.com/rapidsai/dask-xgboost@dask-cudf
|
|
||||||
- git+https://github.com/rapidsai/dask-cudf@master
|
|
||||||
- git+https://github.com/rapidsai/dask-cuda@master
|
|
||||||
560
contrib/fairness/fairlearn-azureml-mitigation.ipynb
Normal file
560
contrib/fairness/fairlearn-azureml-mitigation.ipynb
Normal file
@@ -0,0 +1,560 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Unfairness Mitigation with Fairlearn and Azure Machine Learning\n",
|
||||||
|
"**This notebook shows how to upload results from Fairlearn's GridSearch mitigation algorithm into a dashboard in Azure Machine Learning Studio**\n",
|
||||||
|
"\n",
|
||||||
|
"## Table of Contents\n",
|
||||||
|
"\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Loading the Data](#LoadingData)\n",
|
||||||
|
"1. [Training an Unmitigated Model](#UnmitigatedModel)\n",
|
||||||
|
"1. [Mitigation with GridSearch](#Mitigation)\n",
|
||||||
|
"1. [Uploading a Fairness Dashboard to Azure](#AzureUpload)\n",
|
||||||
|
" 1. Registering models\n",
|
||||||
|
" 1. Computing Fairness Metrics\n",
|
||||||
|
" 1. Uploading to Azure\n",
|
||||||
|
"1. [Conclusion](#Conclusion)\n",
|
||||||
|
"\n",
|
||||||
|
"<a id=\"Introduction\"></a>\n",
|
||||||
|
"## Introduction\n",
|
||||||
|
"This notebook shows how to use [Fairlearn (an open source fairness assessment and unfairness mitigation package)](http://fairlearn.github.io) and Azure Machine Learning Studio for a binary classification problem. This example uses the well-known adult census dataset. For the purposes of this notebook, we shall treat this as a loan decision problem. We will pretend that the label indicates whether or not each individual repaid a loan in the past. We will use the data to train a predictor to predict whether previously unseen individuals will repay a loan or not. The assumption is that the model predictions are used to decide whether an individual should be offered a loan. Its purpose is purely illustrative of a workflow including a fairness dashboard - in particular, we do **not** include a full discussion of the detailed issues which arise when considering fairness in machine learning. For such discussions, please [refer to the Fairlearn website](http://fairlearn.github.io/).\n",
|
||||||
|
"\n",
|
||||||
|
"We will apply the [grid search algorithm](https://fairlearn.github.io/api_reference/fairlearn.reductions.html#fairlearn.reductions.GridSearch) from the Fairlearn package using a specific notion of fairness called Demographic Parity. This produces a set of models, and we will view these in a dashboard both locally and in the Azure Machine Learning Studio.\n",
|
||||||
|
"\n",
|
||||||
|
"### Setup\n",
|
||||||
|
"\n",
|
||||||
|
"To use this notebook, an Azure Machine Learning workspace is required.\n",
|
||||||
|
"Please see the [configuration notebook](../../configuration.ipynb) for information about creating one, if required.\n",
|
||||||
|
"This notebook also requires the following packages:\n",
|
||||||
|
"* `azureml-contrib-fairness`\n",
|
||||||
|
"* `fairlearn==0.4.6`\n",
|
||||||
|
"* `joblib`\n",
|
||||||
|
"* `shap`\n",
|
||||||
|
"\n",
|
||||||
|
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# !pip install --upgrade scikit-learn>=0.22.1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"LoadingData\"></a>\n",
|
||||||
|
"## Loading the Data\n",
|
||||||
|
"We use the well-known `adult` census dataset, which we load using `shap` (for convenience). We start with a fairly unremarkable set of imports:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from fairlearn.reductions import GridSearch, DemographicParity, ErrorRate\n",
|
||||||
|
"from fairlearn.widget import FairlearnDashboard\n",
|
||||||
|
"from sklearn import svm\n",
|
||||||
|
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
|
||||||
|
"from sklearn.linear_model import LogisticRegression\n",
|
||||||
|
"import pandas as pd"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can now load and inspect the data from the `shap` package:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.datasets import fetch_openml\n",
|
||||||
|
"data = fetch_openml(data_id=1590, as_frame=True)\n",
|
||||||
|
"X_raw = data.data\n",
|
||||||
|
"Y = (data.target == '>50K') * 1\n",
|
||||||
|
"\n",
|
||||||
|
"X_raw[\"race\"].value_counts().to_dict()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We are going to treat the sex of each individual as a protected attribute (where 0 indicates female and 1 indicates male), and in this particular case we are going separate this attribute out and drop it from the main data (this is not always the best option - see the [Fairlearn website](http://fairlearn.github.io/) for further discussion). We also separate out the Race column, but we will not perform any mitigation based on it. Finally, we perform some standard data preprocessing steps to convert the data into a format suitable for the ML algorithms"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"A = X_raw[['sex','race']]\n",
|
||||||
|
"X = X_raw.drop(labels=['sex', 'race'],axis = 1)\n",
|
||||||
|
"X_dummies = pd.get_dummies(X)\n",
|
||||||
|
"\n",
|
||||||
|
"sc = StandardScaler()\n",
|
||||||
|
"X_scaled = sc.fit_transform(X_dummies)\n",
|
||||||
|
"X_scaled = pd.DataFrame(X_scaled, columns=X_dummies.columns)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"le = LabelEncoder()\n",
|
||||||
|
"Y = le.fit_transform(Y)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"With our data prepared, we can make the conventional split in to 'test' and 'train' subsets:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
|
"X_train, X_test, Y_train, Y_test, A_train, A_test = train_test_split(X_scaled, \n",
|
||||||
|
" Y, \n",
|
||||||
|
" A,\n",
|
||||||
|
" test_size = 0.2,\n",
|
||||||
|
" random_state=0,\n",
|
||||||
|
" stratify=Y)\n",
|
||||||
|
"\n",
|
||||||
|
"# Work around indexing issue\n",
|
||||||
|
"X_train = X_train.reset_index(drop=True)\n",
|
||||||
|
"A_train = A_train.reset_index(drop=True)\n",
|
||||||
|
"X_test = X_test.reset_index(drop=True)\n",
|
||||||
|
"A_test = A_test.reset_index(drop=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"UnmitigatedModel\"></a>\n",
|
||||||
|
"## Training an Unmitigated Model\n",
|
||||||
|
"\n",
|
||||||
|
"So we have a point of comparison, we first train a model (specifically, logistic regression from scikit-learn) on the raw data, without applying any mitigation algorithm:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"unmitigated_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n",
|
||||||
|
"\n",
|
||||||
|
"unmitigated_predictor.fit(X_train, Y_train)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can view this model in the fairness dashboard, and see the disparities which appear:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=['Sex', 'Race'],\n",
|
||||||
|
" y_true=Y_test,\n",
|
||||||
|
" y_pred={\"unmitigated\": unmitigated_predictor.predict(X_test)})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Looking at the disparity in accuracy when we select 'Sex' as the sensitive feature, we see that males have an error rate about three times greater than the females. More interesting is the disparity in opportunitiy - males are offered loans at three times the rate of females.\n",
|
||||||
|
"\n",
|
||||||
|
"Despite the fact that we removed the feature from the training data, our predictor still discriminates based on sex. This demonstrates that simply ignoring a protected attribute when fitting a predictor rarely eliminates unfairness. There will generally be enough other features correlated with the removed attribute to lead to disparate impact."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"Mitigation\"></a>\n",
|
||||||
|
"## Mitigation with GridSearch\n",
|
||||||
|
"\n",
|
||||||
|
"The `GridSearch` class in `Fairlearn` implements a simplified version of the exponentiated gradient reduction of [Agarwal et al. 2018](https://arxiv.org/abs/1803.02453). The user supplies a standard ML estimator, which is treated as a blackbox - for this simple example, we shall use the logistic regression estimator from scikit-learn. `GridSearch` works by generating a sequence of relabellings and reweightings, and trains a predictor for each.\n",
|
||||||
|
"\n",
|
||||||
|
"For this example, we specify demographic parity (on the protected attribute of sex) as the fairness metric. Demographic parity requires that individuals are offered the opportunity (a loan in this example) independent of membership in the protected class (i.e., females and males should be offered loans at the same rate). *We are using this metric for the sake of simplicity* in this example; the appropriate fairness metric can only be selected after *careful examination of the broader context* in which the model is to be used."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"sweep = GridSearch(LogisticRegression(solver='liblinear', fit_intercept=True),\n",
|
||||||
|
" constraints=DemographicParity(),\n",
|
||||||
|
" grid_size=71)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"With our estimator created, we can fit it to the data. After `fit()` completes, we extract the full set of predictors from the `GridSearch` object.\n",
|
||||||
|
"\n",
|
||||||
|
"The following cell trains a many copies of the underlying estimator, and may take a minute or two to run:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"sweep.fit(X_train, Y_train,\n",
|
||||||
|
" sensitive_features=A_train.sex)\n",
|
||||||
|
"\n",
|
||||||
|
"predictors = sweep._predictors"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We could load these predictors into the Fairness dashboard now. However, the plot would be somewhat confusing due to their number. In this case, we are going to remove the predictors which are dominated in the error-disparity space by others from the sweep (note that the disparity will only be calculated for the protected attribute; other potentially protected attributes will *not* be mitigated). In general, one might not want to do this, since there may be other considerations beyond the strict optimisation of error and disparity (of the given protected attribute)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"errors, disparities = [], []\n",
|
||||||
|
"for m in predictors:\n",
|
||||||
|
" classifier = lambda X: m.predict(X)\n",
|
||||||
|
" \n",
|
||||||
|
" error = ErrorRate()\n",
|
||||||
|
" error.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.sex)\n",
|
||||||
|
" disparity = DemographicParity()\n",
|
||||||
|
" disparity.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.sex)\n",
|
||||||
|
" \n",
|
||||||
|
" errors.append(error.gamma(classifier)[0])\n",
|
||||||
|
" disparities.append(disparity.gamma(classifier).max())\n",
|
||||||
|
" \n",
|
||||||
|
"all_results = pd.DataFrame( {\"predictor\": predictors, \"error\": errors, \"disparity\": disparities})\n",
|
||||||
|
"\n",
|
||||||
|
"dominant_models_dict = dict()\n",
|
||||||
|
"base_name_format = \"census_gs_model_{0}\"\n",
|
||||||
|
"row_id = 0\n",
|
||||||
|
"for row in all_results.itertuples():\n",
|
||||||
|
" model_name = base_name_format.format(row_id)\n",
|
||||||
|
" errors_for_lower_or_eq_disparity = all_results[\"error\"][all_results[\"disparity\"]<=row.disparity]\n",
|
||||||
|
" if row.error <= errors_for_lower_or_eq_disparity.min():\n",
|
||||||
|
" dominant_models_dict[model_name] = row.predictor\n",
|
||||||
|
" row_id = row_id + 1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can construct predictions for the dominant models (we include the unmitigated predictor as well, for comparison):"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"predictions_dominant = {\"census_unmitigated\": unmitigated_predictor.predict(X_test)}\n",
|
||||||
|
"models_dominant = {\"census_unmitigated\": unmitigated_predictor}\n",
|
||||||
|
"for name, predictor in dominant_models_dict.items():\n",
|
||||||
|
" value = predictor.predict(X_test)\n",
|
||||||
|
" predictions_dominant[name] = value\n",
|
||||||
|
" models_dominant[name] = predictor"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"These predictions may then be viewed in the fairness dashboard. We include the race column from the dataset, as an alternative basis for assessing the models. However, since we have not based our mitigation on it, the variation in the models with respect to race can be large."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"FairlearnDashboard(sensitive_features=A_test, \n",
|
||||||
|
" sensitive_feature_names=['Sex', 'Race'],\n",
|
||||||
|
" y_true=Y_test.tolist(),\n",
|
||||||
|
" y_pred=predictions_dominant)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"When using sex as the sensitive feature, we see a Pareto front forming - the set of predictors which represent optimal tradeoffs between accuracy and disparity in predictions. In the ideal case, we would have a predictor at (1,0) - perfectly accurate and without any unfairness under demographic parity (with respect to the protected attribute \"sex\"). The Pareto front represents the closest we can come to this ideal based on our data and choice of estimator. Note the range of the axes - the disparity axis covers more values than the accuracy, so we can reduce disparity substantially for a small loss in accuracy. Finally, we also see that the unmitigated model is towards the top right of the plot, with high accuracy, but worst disparity.\n",
|
||||||
|
"\n",
|
||||||
|
"By clicking on individual models on the plot, we can inspect their metrics for disparity and accuracy in greater detail. In a real example, we would then pick the model which represented the best trade-off between accuracy and disparity given the relevant business constraints."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"AzureUpload\"></a>\n",
|
||||||
|
"## Uploading a Fairness Dashboard to Azure\n",
|
||||||
|
"\n",
|
||||||
|
"Uploading a fairness dashboard to Azure is a two stage process. The `FairlearnDashboard` invoked in the previous section relies on the underlying Python kernel to compute metrics on demand. This is obviously not available when the fairness dashboard is rendered in AzureML Studio. By default, the dashboard in Azure Machine Learning Studio also requires the models to be registered. The required stages are therefore:\n",
|
||||||
|
"1. Register the dominant models\n",
|
||||||
|
"1. Precompute all the required metrics\n",
|
||||||
|
"1. Upload to Azure\n",
|
||||||
|
"\n",
|
||||||
|
"Before that, we need to connect to Azure Machine Learning Studio:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Workspace, Experiment, Model\n",
|
||||||
|
"\n",
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"ws.get_details()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"RegisterModels\"></a>\n",
|
||||||
|
"### Registering Models\n",
|
||||||
|
"\n",
|
||||||
|
"The fairness dashboard is designed to integrate with registered models, so we need to do this for the models we want in the Studio portal. The assumption is that the names of the models specified in the dashboard dictionary correspond to the `id`s (i.e. `<name>:<version>` pairs) of registered models in the workspace. We register each of the models in the `models_dominant` dictionary into the workspace. For this, we have to save each model to a file, and then register that file:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import joblib\n",
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"os.makedirs('models', exist_ok=True)\n",
|
||||||
|
"def register_model(name, model):\n",
|
||||||
|
" print(\"Registering \", name)\n",
|
||||||
|
" model_path = \"models/{0}.pkl\".format(name)\n",
|
||||||
|
" joblib.dump(value=model, filename=model_path)\n",
|
||||||
|
" registered_model = Model.register(model_path=model_path,\n",
|
||||||
|
" model_name=name,\n",
|
||||||
|
" workspace=ws)\n",
|
||||||
|
" print(\"Registered \", registered_model.id)\n",
|
||||||
|
" return registered_model.id\n",
|
||||||
|
"\n",
|
||||||
|
"model_name_id_mapping = dict()\n",
|
||||||
|
"for name, model in models_dominant.items():\n",
|
||||||
|
" m_id = register_model(name, model)\n",
|
||||||
|
" model_name_id_mapping[name] = m_id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now, produce new predictions dictionaries, with the updated names:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"predictions_dominant_ids = dict()\n",
|
||||||
|
"for name, y_pred in predictions_dominant.items():\n",
|
||||||
|
" predictions_dominant_ids[model_name_id_mapping[name]] = y_pred"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"PrecomputeMetrics\"></a>\n",
|
||||||
|
"### Precomputing Metrics\n",
|
||||||
|
"\n",
|
||||||
|
"We create a _dashboard dictionary_ using Fairlearn's `metrics` package. The `_create_group_metric_set` method has arguments similar to the Dashboard constructor, except that the sensitive features are passed as a dictionary (to ensure that names are available), and we must specify the type of prediction. Note that we use the `predictions_dominant_ids` dictionary we just created:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"sf = { 'sex': A_test.sex, 'race': A_test.race }\n",
|
||||||
|
"\n",
|
||||||
|
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"dash_dict = _create_group_metric_set(y_true=Y_test,\n",
|
||||||
|
" predictions=predictions_dominant_ids,\n",
|
||||||
|
" sensitive_features=sf,\n",
|
||||||
|
" prediction_type='binary_classification')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"DashboardUpload\"></a>\n",
|
||||||
|
"### Uploading the Dashboard\n",
|
||||||
|
"\n",
|
||||||
|
"Now, we import our `contrib` package which contains the routine to perform the upload:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.fairness import upload_dashboard_dictionary, download_dashboard_by_upload_id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we can create an Experiment, then a Run, and upload our dashboard to it:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"exp = Experiment(ws, \"Test_Fairlearn_GridSearch_Census_Demo\")\n",
|
||||||
|
"print(exp)\n",
|
||||||
|
"\n",
|
||||||
|
"run = exp.start_logging()\n",
|
||||||
|
"try:\n",
|
||||||
|
" dashboard_title = \"Dominant Models from GridSearch\"\n",
|
||||||
|
" upload_id = upload_dashboard_dictionary(run,\n",
|
||||||
|
" dash_dict,\n",
|
||||||
|
" dashboard_name=dashboard_title)\n",
|
||||||
|
" print(\"\\nUploaded to id: {0}\\n\".format(upload_id))\n",
|
||||||
|
"\n",
|
||||||
|
" downloaded_dict = download_dashboard_by_upload_id(run, upload_id)\n",
|
||||||
|
"finally:\n",
|
||||||
|
" run.complete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The dashboard can be viewed in the Run Details page.\n",
|
||||||
|
"\n",
|
||||||
|
"Finally, we can verify that the dashboard dictionary which we downloaded matches our upload:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(dash_dict == downloaded_dict)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"Conclusion\"></a>\n",
|
||||||
|
"## Conclusion\n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook we have demonstrated how to use the `GridSearch` algorithm from Fairlearn to generate a collection of models, and then present them in the fairness dashboard in Azure Machine Learning Studio. Please remember that this notebook has not attempted to discuss the many considerations which should be part of any approach to unfairness mitigation. The [Fairlearn website](http://fairlearn.github.io/) provides that discussion"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "riedgar"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
7
contrib/fairness/fairlearn-azureml-mitigation.yml
Normal file
7
contrib/fairness/fairlearn-azureml-mitigation.yml
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
name: fairlearn-azureml-mitigation
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-contrib-fairness
|
||||||
|
- fairlearn==0.4.6
|
||||||
|
- joblib
|
||||||
498
contrib/fairness/upload-fairness-dashboard.ipynb
Normal file
498
contrib/fairness/upload-fairness-dashboard.ipynb
Normal file
@@ -0,0 +1,498 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Upload a Fairness Dashboard to Azure Machine Learning Studio\n",
|
||||||
|
"**This notebook shows how to generate and upload a fairness assessment dashboard from Fairlearn to AzureML Studio**\n",
|
||||||
|
"\n",
|
||||||
|
"## Table of Contents\n",
|
||||||
|
"\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Loading the Data](#LoadingData)\n",
|
||||||
|
"1. [Processing the Data](#ProcessingData)\n",
|
||||||
|
"1. [Training Models](#TrainingModels)\n",
|
||||||
|
"1. [Logging in to AzureML](#LoginAzureML)\n",
|
||||||
|
"1. [Registering the Models](#RegisterModels)\n",
|
||||||
|
"1. [Using the Fairlearn Dashboard](#LocalDashboard)\n",
|
||||||
|
"1. [Uploading a Fairness Dashboard to Azure](#AzureUpload)\n",
|
||||||
|
" 1. Computing Fairness Metrics\n",
|
||||||
|
" 1. Uploading to Azure\n",
|
||||||
|
"1. [Conclusion](#Conclusion)\n",
|
||||||
|
" \n",
|
||||||
|
"\n",
|
||||||
|
"<a id=\"Introduction\"></a>\n",
|
||||||
|
"## Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook, we walk through a simple example of using the `azureml-contrib-fairness` package to upload a collection of fairness statistics for a fairness dashboard. It is an example of integrating the [open source Fairlearn package](https://www.github.com/fairlearn/fairlearn) with Azure Machine Learning. This is not an example of fairness analysis or mitigation - this notebook simply shows how to get a fairness dashboard into the Azure Machine Learning portal. We will load the data and train a couple of simple models. We will then use Fairlearn to generate data for a Fairness dashboard, which we can upload to Azure Machine Learning portal and view there.\n",
|
||||||
|
"\n",
|
||||||
|
"### Setup\n",
|
||||||
|
"\n",
|
||||||
|
"To use this notebook, an Azure Machine Learning workspace is required.\n",
|
||||||
|
"Please see the [configuration notebook](../../configuration.ipynb) for information about creating one, if required.\n",
|
||||||
|
"This notebook also requires the following packages:\n",
|
||||||
|
"* `azureml-contrib-fairness`\n",
|
||||||
|
"* `fairlearn==0.4.6`\n",
|
||||||
|
"* `joblib`\n",
|
||||||
|
"* `shap`\n",
|
||||||
|
"\n",
|
||||||
|
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# !pip install --upgrade scikit-learn>=0.22.1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"LoadingData\"></a>\n",
|
||||||
|
"## Loading the Data\n",
|
||||||
|
"We use the well-known `adult` census dataset, which we load using `shap` (for convenience). We start with a fairly unremarkable set of imports:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn import svm\n",
|
||||||
|
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
|
||||||
|
"from sklearn.linear_model import LogisticRegression\n",
|
||||||
|
"import pandas as pd"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we can load the data:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.datasets import fetch_openml\n",
|
||||||
|
"data = fetch_openml(data_id=1590, as_frame=True)\n",
|
||||||
|
"X_raw = data.data\n",
|
||||||
|
"Y = (data.target == '>50K') * 1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can take a look at some of the data. For example, the next cells shows the counts of the different races identified in the dataset:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(X_raw[\"race\"].value_counts().to_dict())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"ProcessingData\"></a>\n",
|
||||||
|
"## Processing the Data\n",
|
||||||
|
"\n",
|
||||||
|
"With the data loaded, we process it for our needs. First, we extract the sensitive features of interest into `A` (conventionally used in the literature) and put the rest of the feature data into `X`:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"A = X_raw[['sex','race']]\n",
|
||||||
|
"X = X_raw.drop(labels=['sex', 'race'],axis = 1)\n",
|
||||||
|
"X_dummies = pd.get_dummies(X)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Next, we apply a standard set of scalings:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"sc = StandardScaler()\n",
|
||||||
|
"X_scaled = sc.fit_transform(X_dummies)\n",
|
||||||
|
"X_scaled = pd.DataFrame(X_scaled, columns=X_dummies.columns)\n",
|
||||||
|
"\n",
|
||||||
|
"le = LabelEncoder()\n",
|
||||||
|
"Y = le.fit_transform(Y)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Finally, we can then split our data into training and test sets, and also make the labels on our test portion of `A` human-readable:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
|
"X_train, X_test, Y_train, Y_test, A_train, A_test = train_test_split(X_scaled, \n",
|
||||||
|
" Y, \n",
|
||||||
|
" A,\n",
|
||||||
|
" test_size = 0.2,\n",
|
||||||
|
" random_state=0,\n",
|
||||||
|
" stratify=Y)\n",
|
||||||
|
"\n",
|
||||||
|
"# Work around indexing issue\n",
|
||||||
|
"X_train = X_train.reset_index(drop=True)\n",
|
||||||
|
"A_train = A_train.reset_index(drop=True)\n",
|
||||||
|
"X_test = X_test.reset_index(drop=True)\n",
|
||||||
|
"A_test = A_test.reset_index(drop=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"TrainingModels\"></a>\n",
|
||||||
|
"## Training Models\n",
|
||||||
|
"\n",
|
||||||
|
"We now train a couple of different models on our data. The `adult` census dataset is a classification problem - the goal is to predict whether a particular individual exceeds an income threshold. For the purpose of generating a dashboard to upload, it is sufficient to train two basic classifiers. First, a logistic regression classifier:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"lr_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n",
|
||||||
|
"\n",
|
||||||
|
"lr_predictor.fit(X_train, Y_train)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"And for comparison, a support vector classifier:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"svm_predictor = svm.SVC()\n",
|
||||||
|
"\n",
|
||||||
|
"svm_predictor.fit(X_train, Y_train)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"LoginAzureML\"></a>\n",
|
||||||
|
"## Logging in to AzureML\n",
|
||||||
|
"\n",
|
||||||
|
"With our two classifiers trained, we can log into our AzureML workspace:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Workspace, Experiment, Model\n",
|
||||||
|
"\n",
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"ws.get_details()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"RegisterModels\"></a>\n",
|
||||||
|
"## Registering the Models\n",
|
||||||
|
"\n",
|
||||||
|
"Next, we register our models. By default, the subroutine which uploads the models checks that the names provided correspond to registered models in the workspace. We define a utility routine to do the registering:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import joblib\n",
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"os.makedirs('models', exist_ok=True)\n",
|
||||||
|
"def register_model(name, model):\n",
|
||||||
|
" print(\"Registering \", name)\n",
|
||||||
|
" model_path = \"models/{0}.pkl\".format(name)\n",
|
||||||
|
" joblib.dump(value=model, filename=model_path)\n",
|
||||||
|
" registered_model = Model.register(model_path=model_path,\n",
|
||||||
|
" model_name=name,\n",
|
||||||
|
" workspace=ws)\n",
|
||||||
|
" print(\"Registered \", registered_model.id)\n",
|
||||||
|
" return registered_model.id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now, we register the models. For convenience in subsequent method calls, we store the results in a dictionary, which maps the `id` of the registered model (a string in `name:version` format) to the predictor itself:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model_dict = {}\n",
|
||||||
|
"\n",
|
||||||
|
"lr_reg_id = register_model(\"fairness_linear_regression\", lr_predictor)\n",
|
||||||
|
"model_dict[lr_reg_id] = lr_predictor\n",
|
||||||
|
"svm_reg_id = register_model(\"fairness_svm\", svm_predictor)\n",
|
||||||
|
"model_dict[svm_reg_id] = svm_predictor"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"LocalDashboard\"></a>\n",
|
||||||
|
"## Using the Fairlearn Dashboard\n",
|
||||||
|
"\n",
|
||||||
|
"We can now examine the fairness of the two models we have training, both as a function of race and (binary) sex. Before uploading the dashboard to the AzureML portal, we will first instantiate a local instance of the Fairlearn dashboard.\n",
|
||||||
|
"\n",
|
||||||
|
"Regardless of the viewing location, the dashboard is based on three things - the true values, the model predictions and the sensitive feature values. The dashboard can use predictions from multiple models and multiple sensitive features if desired (as we are doing here).\n",
|
||||||
|
"\n",
|
||||||
|
"Our first step is to generate a dictionary mapping the `id` of the registered model to the corresponding array of predictions:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ys_pred = {}\n",
|
||||||
|
"for n, p in model_dict.items():\n",
|
||||||
|
" ys_pred[n] = p.predict(X_test)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can examine these predictions in a locally invoked Fairlearn dashboard. This can be compared to the dashboard uploaded to the portal (in the next section):"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from fairlearn.widget import FairlearnDashboard\n",
|
||||||
|
"\n",
|
||||||
|
"FairlearnDashboard(sensitive_features=A_test, \n",
|
||||||
|
" sensitive_feature_names=['Sex', 'Race'],\n",
|
||||||
|
" y_true=Y_test.tolist(),\n",
|
||||||
|
" y_pred=ys_pred)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"AzureUpload\"></a>\n",
|
||||||
|
"## Uploading a Fairness Dashboard to Azure\n",
|
||||||
|
"\n",
|
||||||
|
"Uploading a fairness dashboard to Azure is a two stage process. The `FairlearnDashboard` invoked in the previous section relies on the underlying Python kernel to compute metrics on demand. This is obviously not available when the fairness dashboard is rendered in AzureML Studio. The required stages are therefore:\n",
|
||||||
|
"1. Precompute all the required metrics\n",
|
||||||
|
"1. Upload to Azure\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"### Computing Fairness Metrics\n",
|
||||||
|
"We use Fairlearn to create a dictionary which contains all the data required to display a dashboard. This includes both the raw data (true values, predicted values and sensitive features), and also the fairness metrics. The API is similar to that used to invoke the Dashboard locally. However, there are a few minor changes to the API, and the type of problem being examined (binary classification, regression etc.) needs to be specified explicitly:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"sf = { 'Race': A_test.race, 'Sex': A_test.sex }\n",
|
||||||
|
"\n",
|
||||||
|
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
|
||||||
|
"\n",
|
||||||
|
"dash_dict = _create_group_metric_set(y_true=Y_test,\n",
|
||||||
|
" predictions=ys_pred,\n",
|
||||||
|
" sensitive_features=sf,\n",
|
||||||
|
" prediction_type='binary_classification')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The `_create_group_metric_set()` method is currently underscored since its exact design is not yet final in Fairlearn."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Uploading to Azure\n",
|
||||||
|
"\n",
|
||||||
|
"We can now import the `azureml.contrib.fairness` package itself. We will round-trip the data, so there are two required subroutines:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.fairness import upload_dashboard_dictionary, download_dashboard_by_upload_id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Finally, we can upload the generated dictionary to AzureML. The upload method requires a run, so we first create an experiment and a run. The uploaded dashboard can be seen on the corresponding Run Details page in AzureML Studio. For completeness, we also download the dashboard dictionary which we uploaded."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"exp = Experiment(ws, \"notebook-01\")\n",
|
||||||
|
"print(exp)\n",
|
||||||
|
"\n",
|
||||||
|
"run = exp.start_logging()\n",
|
||||||
|
"try:\n",
|
||||||
|
" dashboard_title = \"Sample notebook upload\"\n",
|
||||||
|
" upload_id = upload_dashboard_dictionary(run,\n",
|
||||||
|
" dash_dict,\n",
|
||||||
|
" dashboard_name=dashboard_title)\n",
|
||||||
|
" print(\"\\nUploaded to id: {0}\\n\".format(upload_id))\n",
|
||||||
|
"\n",
|
||||||
|
" downloaded_dict = download_dashboard_by_upload_id(run, upload_id)\n",
|
||||||
|
"finally:\n",
|
||||||
|
" run.complete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Finally, we can verify that the dashboard dictionary which we downloaded matches our upload:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(dash_dict == downloaded_dict)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a id=\"Conclusion\"></a>\n",
|
||||||
|
"## Conclusion\n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook we have demonstrated how to generate and upload a fairness dashboard to AzureML Studio. We have not discussed how to analyse the results and apply mitigations. Those topics will be covered elsewhere."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "riedgar"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
7
contrib/fairness/upload-fairness-dashboard.yml
Normal file
7
contrib/fairness/upload-fairness-dashboard.yml
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
name: upload-fairness-dashboard
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-contrib-fairness
|
||||||
|
- fairlearn==0.4.6
|
||||||
|
- joblib
|
||||||
@@ -4,14 +4,11 @@ Learn how to use Azure Machine Learning services for experimentation and model m
|
|||||||
|
|
||||||
As a pre-requisite, run the [configuration Notebook](../configuration.ipynb) notebook first to set up your Azure ML Workspace. Then, run the notebooks in following recommended order.
|
As a pre-requisite, run the [configuration Notebook](../configuration.ipynb) notebook first to set up your Azure ML Workspace. Then, run the notebooks in following recommended order.
|
||||||
|
|
||||||
* [train-within-notebook](./training/train-within-notebook): Train a model hile tracking run history, and learn how to deploy the model as web service to Azure Container Instance.
|
|
||||||
* [train-on-local](./training/train-on-local): Learn how to submit a run to local computer and use Azure ML managed run configuration.
|
* [train-on-local](./training/train-on-local): Learn how to submit a run to local computer and use Azure ML managed run configuration.
|
||||||
* [train-on-amlcompute](./training/train-on-amlcompute): Use a 1-n node Azure ML managed compute cluster for remote runs on Azure CPU or GPU infrastructure.
|
* [train-on-amlcompute](./training/train-on-amlcompute): Use a 1-n node Azure ML managed compute cluster for remote runs on Azure CPU or GPU infrastructure.
|
||||||
* [train-on-remote-vm](./training/train-on-remote-vm): Use Data Science Virtual Machine as a target for remote runs.
|
* [train-on-remote-vm](./training/train-on-remote-vm): Use Data Science Virtual Machine as a target for remote runs.
|
||||||
* [logging-api](./training/logging-api): Learn about the details of logging metrics to run history.
|
* [logging-api](./track-and-monitor-experiments/logging-api): Learn about the details of logging metrics to run history.
|
||||||
* [register-model-create-image-deploy-service](./deployment/register-model-create-image-deploy-service): Learn about the details of model management.
|
|
||||||
* [production-deploy-to-aks](./deployment/production-deploy-to-aks) Deploy a model to production at scale on Azure Kubernetes Service.
|
* [production-deploy-to-aks](./deployment/production-deploy-to-aks) Deploy a model to production at scale on Azure Kubernetes Service.
|
||||||
* [enable-data-collection-for-models-in-aks](./deployment/enable-data-collection-for-models-in-aks) Learn about data collection APIs for deployed model.
|
|
||||||
* [enable-app-insights-in-production-service](./deployment/enable-app-insights-in-production-service) Learn how to use App Insights with production web service.
|
* [enable-app-insights-in-production-service](./deployment/enable-app-insights-in-production-service) Learn how to use App Insights with production web service.
|
||||||
|
|
||||||
Find quickstarts, end-to-end tutorials, and how-tos on the [official documentation site for Azure Machine Learning service](https://docs.microsoft.com/en-us/azure/machine-learning/service/).
|
Find quickstarts, end-to-end tutorials, and how-tos on the [official documentation site for Azure Machine Learning service](https://docs.microsoft.com/en-us/azure/machine-learning/service/).
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Table of Contents
|
# Table of Contents
|
||||||
1. [Automated ML Introduction](#introduction)
|
1. [Automated ML Introduction](#introduction)
|
||||||
1. [Setup using Azure Notebooks](#jupyter)
|
1. [Setup using Compute Instances](#jupyter)
|
||||||
1. [Setup using Azure Databricks](#databricks)
|
|
||||||
1. [Setup using a Local Conda environment](#localconda)
|
1. [Setup using a Local Conda environment](#localconda)
|
||||||
|
1. [Setup using Azure Databricks](#databricks)
|
||||||
1. [Automated ML SDK Sample Notebooks](#samples)
|
1. [Automated ML SDK Sample Notebooks](#samples)
|
||||||
1. [Documentation](#documentation)
|
1. [Documentation](#documentation)
|
||||||
1. [Running using python command](#pythoncommand)
|
1. [Running using python command](#pythoncommand)
|
||||||
@@ -21,22 +21,14 @@ Below are the three execution environments supported by automated ML.
|
|||||||
|
|
||||||
|
|
||||||
<a name="jupyter"></a>
|
<a name="jupyter"></a>
|
||||||
## Setup using Azure Notebooks - Jupyter based notebooks in the Azure cloud
|
## Setup using Compute Instances - Jupyter based notebooks from a Azure Virtual Machine
|
||||||
|
|
||||||
1. [](https://aka.ms/aml-clone-azure-notebooks)
|
1. Open the [ML Azure portal](https://ml.azure.com)
|
||||||
[Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks.
|
1. Select Compute
|
||||||
1. Follow the instructions in the [configuration](../../configuration.ipynb) notebook to create and connect to a workspace.
|
1. Select Compute Instances
|
||||||
1. Open one of the sample notebooks.
|
1. Click New
|
||||||
|
1. Type a Compute Name, select a Virtual Machine type and select a Virtual Machine size
|
||||||
<a name="databricks"></a>
|
1. Click Create
|
||||||
## Setup using Azure Databricks
|
|
||||||
|
|
||||||
**NOTE**: Please create your Azure Databricks cluster as v4.x (high concurrency preferred) with **Python 3** (dropdown).
|
|
||||||
**NOTE**: You should at least have contributor access to your Azure subcription to run the notebook.
|
|
||||||
- Please remove the previous SDK version if there is any and install the latest SDK by installing **azureml-sdk[automl_databricks]** as a PyPi library in Azure Databricks workspace.
|
|
||||||
- You can find the detail Readme instructions at [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks).
|
|
||||||
- Download the sample notebook automl-databricks-local-01.ipynb from [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks) and import into the Azure databricks workspace.
|
|
||||||
- Attach the notebook to the cluster.
|
|
||||||
|
|
||||||
<a name="localconda"></a>
|
<a name="localconda"></a>
|
||||||
## Setup using a Local Conda environment
|
## Setup using a Local Conda environment
|
||||||
@@ -102,82 +94,65 @@ source activate azure_automl
|
|||||||
jupyter notebook
|
jupyter notebook
|
||||||
```
|
```
|
||||||
|
|
||||||
|
<a name="databricks"></a>
|
||||||
|
## Setup using Azure Databricks
|
||||||
|
|
||||||
|
**NOTE**: Please create your Azure Databricks cluster as v6.0 (high concurrency preferred) with **Python 3** (dropdown).
|
||||||
|
**NOTE**: You should at least have contributor access to your Azure subcription to run the notebook.
|
||||||
|
- Please remove the previous SDK version if there is any and install the latest SDK by installing **azureml-sdk[automl]** as a PyPi library in Azure Databricks workspace.
|
||||||
|
- You can find the detail Readme instructions at [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks).
|
||||||
|
- Download the sample notebook automl-databricks-local-01.ipynb from [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks) and import into the Azure databricks workspace.
|
||||||
|
- Attach the notebook to the cluster.
|
||||||
|
|
||||||
<a name="samples"></a>
|
<a name="samples"></a>
|
||||||
# Automated ML SDK Sample Notebooks
|
# Automated ML SDK Sample Notebooks
|
||||||
|
|
||||||
- [auto-ml-classification.ipynb](classification/auto-ml-classification.ipynb)
|
- [auto-ml-classification-credit-card-fraud.ipynb](classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb)
|
||||||
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
|
- Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud)
|
||||||
- Simple example of using automated ML for classification
|
- Simple example of using automated ML for classification to fraudulent credit card transactions
|
||||||
- Uses local compute for training
|
- Uses azure compute for training
|
||||||
|
|
||||||
- [auto-ml-regression.ipynb](regression/auto-ml-regression.ipynb)
|
- [auto-ml-regression.ipynb](regression/auto-ml-regression.ipynb)
|
||||||
- Dataset: scikit learn's [diabetes dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html)
|
- Dataset: Hardware Performance Dataset
|
||||||
- Simple example of using automated ML for regression
|
- Simple example of using automated ML for regression
|
||||||
- Uses local compute for training
|
- Uses azure compute for training
|
||||||
|
|
||||||
- [auto-ml-remote-amlcompute.ipynb](remote-amlcompute/auto-ml-remote-amlcompute.ipynb)
|
- [auto-ml-regression-explanation-featurization.ipynb](regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb)
|
||||||
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
|
- Dataset: Hardware Performance Dataset
|
||||||
- Example of using automated ML for classification using remote AmlCompute for training
|
- Shows featurization and excplanation
|
||||||
- Parallel execution of iterations
|
- Uses azure compute for training
|
||||||
- Async tracking of progress
|
|
||||||
- Cancelling individual iterations or entire run
|
|
||||||
- Retrieving models for any iteration or logged metric
|
|
||||||
- Specify automated ML settings as kwargs
|
|
||||||
|
|
||||||
- [auto-ml-missing-data-blacklist-early-termination.ipynb](missing-data-blacklist-early-termination/auto-ml-missing-data-blacklist-early-termination.ipynb)
|
|
||||||
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
|
|
||||||
- Blacklist certain pipelines
|
|
||||||
- Specify a target metrics to indicate stopping criteria
|
|
||||||
- Handling Missing Data in the input
|
|
||||||
|
|
||||||
- [auto-ml-sparse-data-train-test-split.ipynb](sparse-data-train-test-split/auto-ml-sparse-data-train-test-split.ipynb)
|
|
||||||
- Dataset: Scikit learn's [20newsgroup](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html)
|
|
||||||
- Handle sparse datasets
|
|
||||||
- Specify custom train and validation set
|
|
||||||
|
|
||||||
- [auto-ml-exploring-previous-runs.ipynb](exploring-previous-runs/auto-ml-exploring-previous-runs.ipynb)
|
|
||||||
- List all projects for the workspace
|
|
||||||
- List all automated ML Runs for a given project
|
|
||||||
- Get details for a automated ML Run. (automated ML settings, run widget & all metrics)
|
|
||||||
- Download fitted pipeline for any iteration
|
|
||||||
|
|
||||||
- [auto-ml-classification-with-deployment.ipynb](classification-with-deployment/auto-ml-classification-with-deployment.ipynb)
|
|
||||||
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
|
|
||||||
- Simple example of using automated ML for classification
|
|
||||||
- Registering the model
|
|
||||||
- Creating Image and creating aci service
|
|
||||||
- Testing the aci service
|
|
||||||
|
|
||||||
- [auto-ml-sample-weight.ipynb](sample-weight/auto-ml-sample-weight.ipynb)
|
|
||||||
- How to specifying sample_weight
|
|
||||||
- The difference that it makes to test results
|
|
||||||
|
|
||||||
- [auto-ml-subsampling-local.ipynb](subsampling/auto-ml-subsampling-local.ipynb)
|
|
||||||
- How to enable subsampling
|
|
||||||
|
|
||||||
- [auto-ml-dataprep.ipynb](dataprep/auto-ml-dataprep.ipynb)
|
|
||||||
- Using DataPrep for reading data
|
|
||||||
|
|
||||||
- [auto-ml-dataprep-remote-execution.ipynb](dataprep-remote-execution/auto-ml-dataprep-remote-execution.ipynb)
|
|
||||||
- Using DataPrep for reading data with remote execution
|
|
||||||
|
|
||||||
- [auto-ml-classification-with-whitelisting.ipynb](classification-with-whitelisting/auto-ml-classification-with-whitelisting.ipynb)
|
|
||||||
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
|
|
||||||
- Simple example of using automated ML for classification with whitelisting tensorflow models.
|
|
||||||
- Uses local compute for training
|
|
||||||
|
|
||||||
- [auto-ml-forecasting-energy-demand.ipynb](forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb)
|
- [auto-ml-forecasting-energy-demand.ipynb](forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb)
|
||||||
- Dataset: [NYC energy demand data](forecasting-a/nyc_energy.csv)
|
- Dataset: [NYC energy demand data](forecasting-a/nyc_energy.csv)
|
||||||
- Example of using automated ML for training a forecasting model
|
- Example of using automated ML for training a forecasting model
|
||||||
|
|
||||||
|
- [auto-ml-classification-credit-card-fraud-local.ipynb](local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb)
|
||||||
|
- Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud)
|
||||||
|
- Simple example of using automated ML for classification to fraudulent credit card transactions
|
||||||
|
- Uses local compute for training
|
||||||
|
|
||||||
|
- [auto-ml-classification-bank-marketing-all-features.ipynb](classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb)
|
||||||
|
- Dataset: UCI's [bank marketing dataset](https://www.kaggle.com/janiobachmann/bank-marketing-dataset)
|
||||||
|
- Simple example of using automated ML for classification to predict term deposit subscriptions for a bank
|
||||||
|
- Uses azure compute for training
|
||||||
|
|
||||||
- [auto-ml-forecasting-orange-juice-sales.ipynb](forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb)
|
- [auto-ml-forecasting-orange-juice-sales.ipynb](forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb)
|
||||||
- Dataset: [Dominick's grocery sales of orange juice](forecasting-b/dominicks_OJ.csv)
|
- Dataset: [Dominick's grocery sales of orange juice](forecasting-b/dominicks_OJ.csv)
|
||||||
- Example of training an automated ML forecasting model on multiple time-series
|
- Example of training an automated ML forecasting model on multiple time-series
|
||||||
|
|
||||||
- [auto-ml-classification-with-onnx.ipynb](classification-with-onnx/auto-ml-classification-with-onnx.ipynb)
|
- [auto-ml-forecasting-bike-share.ipynb](forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb)
|
||||||
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
|
- Dataset: forecasting for a bike-sharing
|
||||||
- Simple example of using automated ML for classification with ONNX models
|
- Example of training an automated ML forecasting model on multiple time-series
|
||||||
- Uses local compute for training
|
|
||||||
|
- [auto-ml-forecasting-function.ipynb](forecasting-forecast-function/auto-ml-forecasting-function.ipynb)
|
||||||
|
- Example of training an automated ML forecasting model on multiple time-series
|
||||||
|
|
||||||
|
- [auto-ml-forecasting-beer-remote.ipynb](forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb)
|
||||||
|
- Example of training an automated ML forecasting model on multiple time-series
|
||||||
|
- Beer Production Forecasting
|
||||||
|
|
||||||
|
- [auto-ml-continuous-retraining.ipynb](continuous-retraining/auto-ml-continuous-retraining.ipynb)
|
||||||
|
- Continuous retraining using Pipelines and Time-Series TabularDataset
|
||||||
|
|
||||||
<a name="documentation"></a>
|
<a name="documentation"></a>
|
||||||
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
||||||
@@ -198,7 +173,7 @@ The main code of the file must be indented so that it is under this condition.
|
|||||||
## automl_setup fails
|
## automl_setup fails
|
||||||
1. On Windows, make sure that you are running automl_setup from an Anconda Prompt window rather than a regular cmd window. You can launch the "Anaconda Prompt" window by hitting the Start button and typing "Anaconda Prompt". If you don't see the application "Anaconda Prompt", you might not have conda or mini conda installed. In that case, you can install it [here](https://conda.io/miniconda.html)
|
1. On Windows, make sure that you are running automl_setup from an Anconda Prompt window rather than a regular cmd window. You can launch the "Anaconda Prompt" window by hitting the Start button and typing "Anaconda Prompt". If you don't see the application "Anaconda Prompt", you might not have conda or mini conda installed. In that case, you can install it [here](https://conda.io/miniconda.html)
|
||||||
2. Check that you have conda 64-bit installed rather than 32-bit. You can check this with the command `conda info`. The `platform` should be `win-64` for Windows or `osx-64` for Mac.
|
2. Check that you have conda 64-bit installed rather than 32-bit. You can check this with the command `conda info`. The `platform` should be `win-64` for Windows or `osx-64` for Mac.
|
||||||
3. Check that you have conda 4.4.10 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`.
|
3. Check that you have conda 4.7.8 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`.
|
||||||
4. On Linux, if the error is `gcc: error trying to exec 'cc1plus': execvp: No such file or directory`, install build essentials using the command `sudo apt-get install build-essential`.
|
4. On Linux, if the error is `gcc: error trying to exec 'cc1plus': execvp: No such file or directory`, install build essentials using the command `sudo apt-get install build-essential`.
|
||||||
5. Pass a new name as the first parameter to automl_setup so that it creates a new conda environment. You can view existing conda environments using `conda env list` and remove them with `conda env remove -n <environmentname>`.
|
5. Pass a new name as the first parameter to automl_setup so that it creates a new conda environment. You can view existing conda environments using `conda env list` and remove them with `conda env remove -n <environmentname>`.
|
||||||
|
|
||||||
@@ -216,6 +191,17 @@ If automl_setup_linux.sh fails on Ubuntu Linux with the error: `unable to execut
|
|||||||
4) Check that the region is one of the supported regions: `eastus2`, `eastus`, `westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus`
|
4) Check that the region is one of the supported regions: `eastus2`, `eastus`, `westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus`
|
||||||
5) Check that you have access to the region using the Azure Portal.
|
5) Check that you have access to the region using the Azure Portal.
|
||||||
|
|
||||||
|
## import AutoMLConfig fails after upgrade from before 1.0.76 to 1.0.76 or later
|
||||||
|
There were package changes in automated machine learning version 1.0.76, which require the previous version to be uninstalled before upgrading to the new version.
|
||||||
|
If you have manually upgraded from a version of automated machine learning before 1.0.76 to 1.0.76 or later, you may get the error:
|
||||||
|
`ImportError: cannot import name 'AutoMLConfig'`
|
||||||
|
|
||||||
|
This can be resolved by running:
|
||||||
|
`pip uninstall azureml-train-automl` and then
|
||||||
|
`pip install azureml-train-automl`
|
||||||
|
|
||||||
|
The automl_setup.cmd script does this automatically.
|
||||||
|
|
||||||
## workspace.from_config fails
|
## workspace.from_config fails
|
||||||
If the call `ws = Workspace.from_config()` fails:
|
If the call `ws = Workspace.from_config()` fails:
|
||||||
1) Make sure that you have run the `configuration.ipynb` notebook successfully.
|
1) Make sure that you have run the `configuration.ipynb` notebook successfully.
|
||||||
@@ -238,6 +224,15 @@ You may check the version of tensorflow and uninstall as follows
|
|||||||
2) enter `pip freeze` and look for `tensorflow` , if found, the version listed should be < 1.13
|
2) enter `pip freeze` and look for `tensorflow` , if found, the version listed should be < 1.13
|
||||||
3) If the listed version is a not a supported version, `pip uninstall tensorflow` in the command shell and enter y for confirmation.
|
3) If the listed version is a not a supported version, `pip uninstall tensorflow` in the command shell and enter y for confirmation.
|
||||||
|
|
||||||
|
## KeyError: 'brand' when running AutoML on local compute or Azure Databricks cluster**
|
||||||
|
If a new environment was created after 10 June 2020 using SDK 1.7.0 or lower, training may fail with the above error due to an update in the py-cpuinfo package. (Environments created on or before 10 June 2020 are unaffected, as well as experiments run on remote compute as cached training images are used.) To work around this issue, either of the two following steps can be taken:
|
||||||
|
|
||||||
|
1) Update the SDK version to 1.8.0 or higher (this will also downgrade py-cpuinfo to 5.0.0):
|
||||||
|
`pip install --upgrade azureml-sdk[automl]`
|
||||||
|
|
||||||
|
2) Downgrade the installed version of py-cpuinfo to 5.0.0:
|
||||||
|
`pip install py-cpuinfo==5.0.0`
|
||||||
|
|
||||||
## Remote run: DsvmCompute.create fails
|
## Remote run: DsvmCompute.create fails
|
||||||
There are several reasons why the DsvmCompute.create can fail. The reason is usually in the error message but you have to look at the end of the error message for the detailed reason. Some common reasons are:
|
There are several reasons why the DsvmCompute.create can fail. The reason is usually in the error message but you have to look at the end of the error message for the detailed reason. Some common reasons are:
|
||||||
1) `Compute name is invalid, it should start with a letter, be between 2 and 16 character, and only include letters (a-zA-Z), numbers (0-9) and \'-\'.` Note that underscore is not allowed in the name.
|
1) `Compute name is invalid, it should start with a letter, be between 2 and 16 character, and only include letters (a-zA-Z), numbers (0-9) and \'-\'.` Note that underscore is not allowed in the name.
|
||||||
|
|||||||
@@ -2,20 +2,27 @@ name: azure_automl
|
|||||||
dependencies:
|
dependencies:
|
||||||
# The python interpreter version.
|
# The python interpreter version.
|
||||||
# Currently Azure ML only supports 3.5.2 and later.
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip<=19.3.1
|
||||||
- python>=3.5.2,<3.6.8
|
- python>=3.5.2,<3.6.8
|
||||||
- nb_conda
|
- nb_conda
|
||||||
- matplotlib==2.1.0
|
- matplotlib==2.1.0
|
||||||
- numpy>=1.11.0,<=1.16.2
|
- numpy==1.18.5
|
||||||
- cython
|
- cython
|
||||||
- urllib3<1.24
|
- urllib3<1.24
|
||||||
- scipy>=1.0.0,<=1.1.0
|
- scipy==1.4.1
|
||||||
- scikit-learn>=0.19.0,<=0.20.3
|
- scikit-learn==0.22.1
|
||||||
- pandas>=0.22.0,<=0.23.4
|
- pandas==0.25.1
|
||||||
- py-xgboost<=0.80
|
- py-xgboost<=0.90
|
||||||
|
- conda-forge::fbprophet==0.5
|
||||||
|
- holidays==0.9.11
|
||||||
|
- pytorch::pytorch=1.4.0
|
||||||
|
- cudatoolkit=10.1.243
|
||||||
|
|
||||||
- pip:
|
- pip:
|
||||||
# Required packages for AzureML execution, history, and data preparation.
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
- azureml-sdk[automl,explain]
|
|
||||||
- azureml-widgets
|
- azureml-widgets
|
||||||
- pandas_ml
|
- pytorch-transformers==1.0.0
|
||||||
|
- spacy==2.1.8
|
||||||
|
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
||||||
|
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.16.0/validated_win32_requirements.txt [--no-deps]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
name: azure_automl
|
||||||
|
dependencies:
|
||||||
|
# The python interpreter version.
|
||||||
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip<=19.3.1
|
||||||
|
- python>=3.5.2,<3.6.8
|
||||||
|
- nb_conda
|
||||||
|
- matplotlib==2.1.0
|
||||||
|
- numpy==1.18.5
|
||||||
|
- cython
|
||||||
|
- urllib3<1.24
|
||||||
|
- scipy==1.4.1
|
||||||
|
- scikit-learn==0.22.1
|
||||||
|
- pandas==0.25.1
|
||||||
|
- py-xgboost<=0.90
|
||||||
|
- conda-forge::fbprophet==0.5
|
||||||
|
- holidays==0.9.11
|
||||||
|
- pytorch::pytorch=1.4.0
|
||||||
|
- cudatoolkit=10.1.243
|
||||||
|
|
||||||
|
- pip:
|
||||||
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
|
- azureml-widgets
|
||||||
|
- pytorch-transformers==1.0.0
|
||||||
|
- spacy==2.1.8
|
||||||
|
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
||||||
|
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.16.0/validated_linux_requirements.txt [--no-deps]
|
||||||
|
|
||||||
@@ -2,21 +2,27 @@ name: azure_automl
|
|||||||
dependencies:
|
dependencies:
|
||||||
# The python interpreter version.
|
# The python interpreter version.
|
||||||
# Currently Azure ML only supports 3.5.2 and later.
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip<=19.3.1
|
||||||
- nomkl
|
- nomkl
|
||||||
- python>=3.5.2,<3.6.8
|
- python>=3.5.2,<3.6.8
|
||||||
- nb_conda
|
- nb_conda
|
||||||
- matplotlib==2.1.0
|
- matplotlib==2.1.0
|
||||||
- numpy>=1.11.0,<=1.16.2
|
- numpy==1.18.5
|
||||||
- cython
|
- cython
|
||||||
- urllib3<1.24
|
- urllib3<1.24
|
||||||
- scipy>=1.0.0,<=1.1.0
|
- scipy==1.4.1
|
||||||
- scikit-learn>=0.19.0,<=0.20.3
|
- scikit-learn==0.22.1
|
||||||
- pandas>=0.22.0,<0.23.0
|
- pandas==0.25.1
|
||||||
- py-xgboost<=0.80
|
- py-xgboost<=0.90
|
||||||
|
- conda-forge::fbprophet==0.5
|
||||||
|
- holidays==0.9.11
|
||||||
|
- pytorch::pytorch=1.4.0
|
||||||
|
- cudatoolkit=9.0
|
||||||
|
|
||||||
- pip:
|
- pip:
|
||||||
# Required packages for AzureML execution, history, and data preparation.
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
- azureml-sdk[automl,explain]
|
|
||||||
- azureml-widgets
|
- azureml-widgets
|
||||||
- pandas_ml
|
- pytorch-transformers==1.0.0
|
||||||
|
- spacy==2.1.8
|
||||||
|
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
||||||
|
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.16.0/validated_darwin_requirements.txt [--no-deps]
|
||||||
|
|||||||
@@ -6,14 +6,28 @@ set PIP_NO_WARN_SCRIPT_LOCATION=0
|
|||||||
|
|
||||||
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl"
|
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl"
|
||||||
IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml"
|
IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml"
|
||||||
|
SET check_conda_version_script="check_conda_version.py"
|
||||||
|
|
||||||
IF NOT EXIST %automl_env_file% GOTO YmlMissing
|
IF NOT EXIST %automl_env_file% GOTO YmlMissing
|
||||||
|
|
||||||
|
IF "%CONDA_EXE%"=="" GOTO CondaMissing
|
||||||
|
|
||||||
|
IF NOT EXIST %check_conda_version_script% GOTO VersionCheckMissing
|
||||||
|
|
||||||
|
python "%check_conda_version_script%"
|
||||||
|
IF errorlevel 1 GOTO ErrorExit:
|
||||||
|
|
||||||
|
SET replace_version_script="replace_latest_version.ps1"
|
||||||
|
IF EXIST %replace_version_script% (
|
||||||
|
powershell -file %replace_version_script% %automl_env_file%
|
||||||
|
)
|
||||||
|
|
||||||
call conda activate %conda_env_name% 2>nul:
|
call conda activate %conda_env_name% 2>nul:
|
||||||
|
|
||||||
if not errorlevel 1 (
|
if not errorlevel 1 (
|
||||||
echo Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment %conda_env_name%
|
echo Upgrading existing conda environment %conda_env_name%
|
||||||
call pip install --upgrade azureml-sdk[automl,notebooks,explain]
|
call pip uninstall azureml-train-automl -y -q
|
||||||
|
call conda env update --name %conda_env_name% --file %automl_env_file%
|
||||||
if errorlevel 1 goto ErrorExit
|
if errorlevel 1 goto ErrorExit
|
||||||
) else (
|
) else (
|
||||||
call conda env create -f %automl_env_file% -n %conda_env_name%
|
call conda env create -f %automl_env_file% -n %conda_env_name%
|
||||||
@@ -42,6 +56,19 @@ IF NOT "%options%"=="nolaunch" (
|
|||||||
|
|
||||||
goto End
|
goto End
|
||||||
|
|
||||||
|
:CondaMissing
|
||||||
|
echo Please run this script from an Anaconda Prompt window.
|
||||||
|
echo You can start an Anaconda Prompt window by
|
||||||
|
echo typing Anaconda Prompt on the Start menu.
|
||||||
|
echo If you don't see the Anaconda Prompt app, install Miniconda.
|
||||||
|
echo If you are running an older version of Miniconda or Anaconda,
|
||||||
|
echo you can upgrade using the command: conda update conda
|
||||||
|
goto End
|
||||||
|
|
||||||
|
:VersionCheckMissing
|
||||||
|
echo File %check_conda_version_script% not found.
|
||||||
|
goto End
|
||||||
|
|
||||||
:YmlMissing
|
:YmlMissing
|
||||||
echo File %automl_env_file% not found.
|
echo File %automl_env_file% not found.
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ CONDA_ENV_NAME=$1
|
|||||||
AUTOML_ENV_FILE=$2
|
AUTOML_ENV_FILE=$2
|
||||||
OPTIONS=$3
|
OPTIONS=$3
|
||||||
PIP_NO_WARN_SCRIPT_LOCATION=0
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
CHECK_CONDA_VERSION_SCRIPT="check_conda_version.py"
|
||||||
|
|
||||||
if [ "$CONDA_ENV_NAME" == "" ]
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
then
|
then
|
||||||
@@ -12,7 +13,7 @@ fi
|
|||||||
|
|
||||||
if [ "$AUTOML_ENV_FILE" == "" ]
|
if [ "$AUTOML_ENV_FILE" == "" ]
|
||||||
then
|
then
|
||||||
AUTOML_ENV_FILE="automl_env.yml"
|
AUTOML_ENV_FILE="automl_env_linux.yml"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ ! -f $AUTOML_ENV_FILE ]; then
|
if [ ! -f $AUTOML_ENV_FILE ]; then
|
||||||
@@ -20,10 +21,23 @@ if [ ! -f $AUTOML_ENV_FILE ]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $CHECK_CONDA_VERSION_SCRIPT ]; then
|
||||||
|
echo "File $CHECK_CONDA_VERSION_SCRIPT not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
python "$CHECK_CONDA_VERSION_SCRIPT"
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
sed -i 's/AZUREML-SDK-VERSION/latest/' $AUTOML_ENV_FILE
|
||||||
|
|
||||||
if source activate $CONDA_ENV_NAME 2> /dev/null
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
then
|
then
|
||||||
echo "Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
pip install --upgrade azureml-sdk[automl,notebooks,explain] &&
|
pip uninstall azureml-train-automl -y -q
|
||||||
|
conda env update --name $CONDA_ENV_NAME --file $AUTOML_ENV_FILE &&
|
||||||
jupyter nbextension uninstall --user --py azureml.widgets
|
jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
else
|
else
|
||||||
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ CONDA_ENV_NAME=$1
|
|||||||
AUTOML_ENV_FILE=$2
|
AUTOML_ENV_FILE=$2
|
||||||
OPTIONS=$3
|
OPTIONS=$3
|
||||||
PIP_NO_WARN_SCRIPT_LOCATION=0
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
CHECK_CONDA_VERSION_SCRIPT="check_conda_version.py"
|
||||||
|
|
||||||
if [ "$CONDA_ENV_NAME" == "" ]
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
then
|
then
|
||||||
@@ -20,10 +21,23 @@ if [ ! -f $AUTOML_ENV_FILE ]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $CHECK_CONDA_VERSION_SCRIPT ]; then
|
||||||
|
echo "File $CHECK_CONDA_VERSION_SCRIPT not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
python "$CHECK_CONDA_VERSION_SCRIPT"
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
sed -i '' 's/AZUREML-SDK-VERSION/latest/' $AUTOML_ENV_FILE
|
||||||
|
|
||||||
if source activate $CONDA_ENV_NAME 2> /dev/null
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
then
|
then
|
||||||
echo "Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
pip install --upgrade azureml-sdk[automl,notebooks,explain] &&
|
pip uninstall azureml-train-automl -y -q
|
||||||
|
conda env update --name $CONDA_ENV_NAME --file $AUTOML_ENV_FILE &&
|
||||||
jupyter nbextension uninstall --user --py azureml.widgets
|
jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
else
|
else
|
||||||
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from distutils.version import LooseVersion
|
||||||
|
import platform
|
||||||
|
|
||||||
|
try:
|
||||||
|
import conda
|
||||||
|
except:
|
||||||
|
print('Failed to import conda.')
|
||||||
|
print('This setup is usually run from the base conda environment.')
|
||||||
|
print('You can activate the base environment using the command "conda activate base"')
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
architecture = platform.architecture()[0]
|
||||||
|
|
||||||
|
if architecture != "64bit":
|
||||||
|
print('This setup requires 64bit Anaconda or Miniconda. Found: ' + architecture)
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
minimumVersion = "4.7.8"
|
||||||
|
|
||||||
|
versionInvalid = (LooseVersion(conda.__version__) < LooseVersion(minimumVersion))
|
||||||
|
|
||||||
|
if versionInvalid:
|
||||||
|
print('Setup requires conda version ' + minimumVersion + ' or higher.')
|
||||||
|
print('You can use the command "conda update conda" to upgrade conda.')
|
||||||
|
|
||||||
|
exit(versionInvalid)
|
||||||
@@ -0,0 +1,948 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Classification with Deployment using a Bank Marketing Dataset**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Deploy](#Deploy)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"In this example we use the UCI Bank Marketing dataset to showcase how you can use AutoML for a classification problem and deploy it to an Azure Container Instance (ACI). The classification goal is to predict if the client will subscribe to a term deposit with the bank.\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"Please find the ONNX related documentations [here](https://github.com/onnx/onnx).\n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"1. Create an experiment using an existing workspace.\n",
|
||||||
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"3. Train the model using local compute with ONNX compatible config on.\n",
|
||||||
|
"4. Explore the results, featurization transparency options and save the ONNX model\n",
|
||||||
|
"5. Inference with the ONNX model.\n",
|
||||||
|
"6. Register the model.\n",
|
||||||
|
"7. Create a container image.\n",
|
||||||
|
"8. Create an Azure Container Instance (ACI) service.\n",
|
||||||
|
"9. Test the ACI service.\n",
|
||||||
|
"\n",
|
||||||
|
"In addition this notebook showcases the following features\n",
|
||||||
|
"- **Blocking** certain pipelines\n",
|
||||||
|
"- Specifying **target metrics** to indicate stopping criteria\n",
|
||||||
|
"- Handling **missing data** in the input"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.automl.core.featurization import FeaturizationConfig\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"from azureml.interpret import ExplanationClient"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Accessing the Azure ML workspace requires authentication with Azure.\n",
|
||||||
|
"\n",
|
||||||
|
"The default authentication is interactive authentication using the default tenant. Executing the `ws = Workspace.from_config()` line in the cell below will prompt for authentication the first time that it is run.\n",
|
||||||
|
"\n",
|
||||||
|
"If you have multiple Azure tenants, you can specify the tenant by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n",
|
||||||
|
"\n",
|
||||||
|
"```\n",
|
||||||
|
"from azureml.core.authentication import InteractiveLoginAuthentication\n",
|
||||||
|
"auth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\n",
|
||||||
|
"ws = Workspace.from_config(auth = auth)\n",
|
||||||
|
"```\n",
|
||||||
|
"\n",
|
||||||
|
"If you need to run in an environment where interactive login is not possible, you can use Service Principal authentication by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n",
|
||||||
|
"\n",
|
||||||
|
"```\n",
|
||||||
|
"from azureml.core.authentication import ServicePrincipalAuthentication\n",
|
||||||
|
"auth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\n",
|
||||||
|
"ws = Workspace.from_config(auth = auth)\n",
|
||||||
|
"```\n",
|
||||||
|
"For more details, see [aka.ms/aml-notebook-auth](http://aka.ms/aml-notebook-auth)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a name for experiment\n",
|
||||||
|
"experiment_name = 'automl-classification-bmarketing-all'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment=Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Experiment Name'] = experiment.name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create or Attach existing AmlCompute\n",
|
||||||
|
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read this article on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"cpu_cluster_name = \"cpu-cluster-4\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=6)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"\n",
|
||||||
|
"Leverage azure compute to load the bank marketing dataset as a Tabular Dataset into the dataset variable. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Training Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = pd.read_csv(\"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_train.csv\")\n",
|
||||||
|
"data.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Add missing values in 75% of the lines.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"missing_rate = 0.75\n",
|
||||||
|
"n_missing_samples = int(np.floor(data.shape[0] * missing_rate))\n",
|
||||||
|
"missing_samples = np.hstack((np.zeros(data.shape[0] - n_missing_samples, dtype=np.bool), np.ones(n_missing_samples, dtype=np.bool)))\n",
|
||||||
|
"rng = np.random.RandomState(0)\n",
|
||||||
|
"rng.shuffle(missing_samples)\n",
|
||||||
|
"missing_features = rng.randint(0, data.shape[1], n_missing_samples)\n",
|
||||||
|
"data.values[np.where(missing_samples)[0], missing_features] = np.nan"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if not os.path.isdir('data'):\n",
|
||||||
|
" os.mkdir('data')\n",
|
||||||
|
" \n",
|
||||||
|
"# Save the train data to a csv to be uploaded to the datastore\n",
|
||||||
|
"pd.DataFrame(data).to_csv(\"data/train_data.csv\", index=False)\n",
|
||||||
|
"\n",
|
||||||
|
"ds = ws.get_default_datastore()\n",
|
||||||
|
"ds.upload(src_dir='./data', target_path='bankmarketing', overwrite=True, show_progress=True)\n",
|
||||||
|
"\n",
|
||||||
|
" \n",
|
||||||
|
"\n",
|
||||||
|
"# Upload the training data as a tabular dataset for access during training on remote compute\n",
|
||||||
|
"train_data = Dataset.Tabular.from_delimited_files(path=ds.path('bankmarketing/train_data.csv'))\n",
|
||||||
|
"label = \"y\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Validation Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"validation_data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_validate.csv\"\n",
|
||||||
|
"validation_dataset = Dataset.Tabular.from_delimited_files(validation_data)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Test Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"test_data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_test.csv\"\n",
|
||||||
|
"test_dataset = Dataset.Tabular.from_delimited_files(test_data)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification or regression or forecasting|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
||||||
|
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
||||||
|
"|**blocked_models** | *List* of *strings* indicating machine learning algorithms for AutoML to avoid in this run. <br><br> Allowed values for **Classification**<br><i>LogisticRegression</i><br><i>SGD</i><br><i>MultinomialNaiveBayes</i><br><i>BernoulliNaiveBayes</i><br><i>SVM</i><br><i>LinearSVM</i><br><i>KNN</i><br><i>DecisionTree</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>GradientBoosting</i><br><i>TensorFlowDNN</i><br><i>TensorFlowLinearClassifier</i><br><br>Allowed values for **Regression**<br><i>ElasticNet</i><br><i>GradientBoosting</i><br><i>DecisionTree</i><br><i>KNN</i><br><i>LassoLars</i><br><i>SGD</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>TensorFlowLinearRegressor</i><br><i>TensorFlowDNN</i><br><br>Allowed values for **Forecasting**<br><i>ElasticNet</i><br><i>GradientBoosting</i><br><i>DecisionTree</i><br><i>KNN</i><br><i>LassoLars</i><br><i>SGD</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>TensorFlowLinearRegressor</i><br><i>TensorFlowDNN</i><br><i>Arima</i><br><i>Prophet</i>|\n",
|
||||||
|
"|**allowed_models** | *List* of *strings* indicating machine learning algorithms for AutoML to use in this run. Same values listed above for **blocked_models** allowed for **allowed_models**.|\n",
|
||||||
|
"|**experiment_exit_score**| Value indicating the target for *primary_metric*. <br>Once the target is surpassed the run terminates.|\n",
|
||||||
|
"|**experiment_timeout_hours**| Maximum amount of time in hours that all iterations combined can take before the experiment terminates.|\n",
|
||||||
|
"|**enable_early_stopping**| Flag to enble early termination if the score is not improving in the short term.|\n",
|
||||||
|
"|**featurization**| 'auto' / 'off' Indicator for whether featurization step should be done automatically or not. Note: If the input data is sparse, featurization cannot be turned on.|\n",
|
||||||
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
|
"\n",
|
||||||
|
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"experiment_timeout_hours\" : 0.3,\n",
|
||||||
|
" \"enable_early_stopping\" : True,\n",
|
||||||
|
" \"iteration_timeout_minutes\": 5,\n",
|
||||||
|
" \"max_concurrent_iterations\": 4,\n",
|
||||||
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
|
" #\"n_cross_validations\": 2,\n",
|
||||||
|
" \"primary_metric\": 'AUC_weighted',\n",
|
||||||
|
" \"featurization\": 'auto',\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'classification',\n",
|
||||||
|
" debug_log = 'automl_errors.log',\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" experiment_exit_score = 0.9984,\n",
|
||||||
|
" blocked_models = ['KNN','LinearSVM'],\n",
|
||||||
|
" enable_onnx_compatible_models=True,\n",
|
||||||
|
" training_data = train_data,\n",
|
||||||
|
" label_column_name = label,\n",
|
||||||
|
" validation_data = validation_dataset,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Run the following cell to access previous runs. Uncomment the cell below and update the run_id."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#remote_run = AutoMLRun(experiment=experiment, run_id='<run_ID_goes_here')\n",
|
||||||
|
"#remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Wait for the remote run to complete\n",
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run_customized, fitted_model_customized = remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Transparency\n",
|
||||||
|
"\n",
|
||||||
|
"View updated featurization summary"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"custom_featurizer = fitted_model_customized.named_steps['datatransformer']\n",
|
||||||
|
"df = custom_featurizer.get_featurization_summary()\n",
|
||||||
|
"pd.DataFrame(data=df)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Set `is_user_friendly=False` to get a more detailed summary for the transforms being applied."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"df = custom_featurizer.get_featurization_summary(is_user_friendly=False)\n",
|
||||||
|
"pd.DataFrame(data=df)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"df = custom_featurizer.get_stats_feature_type_summary()\n",
|
||||||
|
"pd.DataFrame(data=df)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.widgets import RunDetails\n",
|
||||||
|
"RunDetails(remote_run).show() "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve the Best Model's explanation\n",
|
||||||
|
"Retrieve the explanation from the best_run which includes explanations for engineered features and raw features. Make sure that the run for generating explanations for the best model is completed."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Wait for the best model explanation run to complete\n",
|
||||||
|
"from azureml.core.run import Run\n",
|
||||||
|
"model_explainability_run_id = remote_run.id + \"_\" + \"ModelExplain\"\n",
|
||||||
|
"print(model_explainability_run_id)\n",
|
||||||
|
"model_explainability_run = Run(experiment=experiment, run_id=model_explainability_run_id)\n",
|
||||||
|
"model_explainability_run.wait_for_completion()\n",
|
||||||
|
"\n",
|
||||||
|
"# Get the best run object\n",
|
||||||
|
"best_run, fitted_model = remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Download engineered feature importance from artifact store\n",
|
||||||
|
"You can use ExplanationClient to download the engineered feature explanations from the artifact store of the best_run."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"client = ExplanationClient.from_run(best_run)\n",
|
||||||
|
"engineered_explanations = client.download_model_explanation(raw=False)\n",
|
||||||
|
"exp_data = engineered_explanations.get_feature_importance_dict()\n",
|
||||||
|
"exp_data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Download raw feature importance from artifact store\n",
|
||||||
|
"You can use ExplanationClient to download the raw feature explanations from the artifact store of the best_run."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"client = ExplanationClient.from_run(best_run)\n",
|
||||||
|
"engineered_explanations = client.download_model_explanation(raw=True)\n",
|
||||||
|
"exp_data = engineered_explanations.get_feature_importance_dict()\n",
|
||||||
|
"exp_data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve the Best ONNX Model\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*.\n",
|
||||||
|
"\n",
|
||||||
|
"Set the parameter return_onnx_model=True to retrieve the best ONNX model, instead of the Python model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, onnx_mdl = remote_run.get_output(return_onnx_model=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Save the best ONNX model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.runtime.onnx_convert import OnnxConverter\n",
|
||||||
|
"onnx_fl_path = \"./best_model.onnx\"\n",
|
||||||
|
"OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Predict with the ONNX model, using onnxruntime package"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import sys\n",
|
||||||
|
"import json\n",
|
||||||
|
"from azureml.automl.core.onnx_convert import OnnxConvertConstants\n",
|
||||||
|
"from azureml.train.automl import constants\n",
|
||||||
|
"\n",
|
||||||
|
"if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n",
|
||||||
|
" python_version_compatible = True\n",
|
||||||
|
"else:\n",
|
||||||
|
" python_version_compatible = False\n",
|
||||||
|
"\n",
|
||||||
|
"import onnxruntime\n",
|
||||||
|
"from azureml.automl.runtime.onnx_convert import OnnxInferenceHelper\n",
|
||||||
|
"\n",
|
||||||
|
"def get_onnx_res(run):\n",
|
||||||
|
" res_path = 'onnx_resource.json'\n",
|
||||||
|
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
|
||||||
|
" with open(res_path) as f:\n",
|
||||||
|
" onnx_res = json.load(f)\n",
|
||||||
|
" return onnx_res\n",
|
||||||
|
"\n",
|
||||||
|
"if python_version_compatible:\n",
|
||||||
|
" test_df = test_dataset.to_pandas_dataframe()\n",
|
||||||
|
" mdl_bytes = onnx_mdl.SerializeToString()\n",
|
||||||
|
" onnx_res = get_onnx_res(best_run)\n",
|
||||||
|
"\n",
|
||||||
|
" onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n",
|
||||||
|
" pred_onnx, pred_prob_onnx = onnxrt_helper.predict(test_df)\n",
|
||||||
|
"\n",
|
||||||
|
" print(pred_onnx)\n",
|
||||||
|
" print(pred_prob_onnx)\n",
|
||||||
|
"else:\n",
|
||||||
|
" print('Please use Python version 3.6 or 3.7 to run the inference helper.')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Deploy\n",
|
||||||
|
"\n",
|
||||||
|
"### Retrieve the Best Model\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Widget for Monitoring Runs\n",
|
||||||
|
"\n",
|
||||||
|
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
||||||
|
"\n",
|
||||||
|
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, fitted_model = remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model_name = best_run.properties['model_name']\n",
|
||||||
|
"\n",
|
||||||
|
"script_file_name = 'inference/score.py'\n",
|
||||||
|
"\n",
|
||||||
|
"best_run.download_file('outputs/scoring_file_v_1_0_0.py', 'inference/score.py')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Register the Fitted Model for Deployment\n",
|
||||||
|
"If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"description = 'AutoML Model trained on bank marketing data to predict if a client will subscribe to a term deposit'\n",
|
||||||
|
"tags = None\n",
|
||||||
|
"model = remote_run.register_model(model_name = model_name, description = description, tags = tags)\n",
|
||||||
|
"\n",
|
||||||
|
"print(remote_run.model_id) # This will be written to the script file later in the notebook."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Deploy the model as a Web Service on Azure Container Instance"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
|
"from azureml.core.webservice import Webservice\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"from azureml.core.environment import Environment\n",
|
||||||
|
"\n",
|
||||||
|
"inference_config = InferenceConfig(entry_script=script_file_name)\n",
|
||||||
|
"\n",
|
||||||
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
||||||
|
" memory_gb = 1, \n",
|
||||||
|
" tags = {'area': \"bmData\", 'type': \"automl_classification\"}, \n",
|
||||||
|
" description = 'sample service for Automl Classification')\n",
|
||||||
|
"\n",
|
||||||
|
"aci_service_name = 'automl-sample-bankmarketing-all'\n",
|
||||||
|
"print(aci_service_name)\n",
|
||||||
|
"aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig)\n",
|
||||||
|
"aci_service.wait_for_deployment(True)\n",
|
||||||
|
"print(aci_service.state)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Get Logs from a Deployed Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Gets logs from a deployed web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#aci_service.get_logs()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Test\n",
|
||||||
|
"\n",
|
||||||
|
"Now that the model is trained, run the test data through the trained model to get the predicted values. This calls the ACI web service to do the prediction.\n",
|
||||||
|
"\n",
|
||||||
|
"Note that the JSON passed to the ACI web service is an array of rows of data. Each row should either be an array of values in the same order that was used for training or a dictionary where the keys are the same as the column names used for training. The example below uses dictionary rows."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Load the bank marketing datasets.\n",
|
||||||
|
"from numpy import array"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_test = test_dataset.drop_columns(columns=['y'])\n",
|
||||||
|
"y_test = test_dataset.keep_columns(columns=['y'], validate=True)\n",
|
||||||
|
"test_dataset.take(5).to_pandas_dataframe()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_test = X_test.to_pandas_dataframe()\n",
|
||||||
|
"y_test = y_test.to_pandas_dataframe()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import json\n",
|
||||||
|
"import requests\n",
|
||||||
|
"\n",
|
||||||
|
"X_test_json = X_test.to_json(orient='records')\n",
|
||||||
|
"data = \"{\\\"data\\\": \" + X_test_json +\"}\"\n",
|
||||||
|
"headers = {'Content-Type': 'application/json'}\n",
|
||||||
|
"\n",
|
||||||
|
"resp = requests.post(aci_service.scoring_uri, data, headers=headers)\n",
|
||||||
|
"\n",
|
||||||
|
"y_pred = json.loads(json.loads(resp.text))['result']"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"actual = array(y_test)\n",
|
||||||
|
"actual = actual[:,0]\n",
|
||||||
|
"print(len(y_pred), \" \", len(actual))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Calculate metrics for the prediction\n",
|
||||||
|
"\n",
|
||||||
|
"Now visualize the data as a confusion matrix that compared the predicted values against the actual values.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib notebook\n",
|
||||||
|
"from sklearn.metrics import confusion_matrix\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import itertools\n",
|
||||||
|
"\n",
|
||||||
|
"cf =confusion_matrix(actual,y_pred)\n",
|
||||||
|
"plt.imshow(cf,cmap=plt.cm.Blues,interpolation='nearest')\n",
|
||||||
|
"plt.colorbar()\n",
|
||||||
|
"plt.title('Confusion Matrix')\n",
|
||||||
|
"plt.xlabel('Predicted')\n",
|
||||||
|
"plt.ylabel('Actual')\n",
|
||||||
|
"class_labels = ['no','yes']\n",
|
||||||
|
"tick_marks = np.arange(len(class_labels))\n",
|
||||||
|
"plt.xticks(tick_marks,class_labels)\n",
|
||||||
|
"plt.yticks([-0.5,0,1,1.5],['','no','yes',''])\n",
|
||||||
|
"# plotting text value inside cells\n",
|
||||||
|
"thresh = cf.max() / 2.\n",
|
||||||
|
"for i,j in itertools.product(range(cf.shape[0]),range(cf.shape[1])):\n",
|
||||||
|
" plt.text(j,i,format(cf[i,j],'d'),horizontalalignment='center',color='white' if cf[i,j] >thresh else 'black')\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Delete a Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Deletes the specified web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"aci_service.delete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Acknowledgements"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This Bank Marketing dataset is made available under the Creative Commons (CCO: Public Domain) License: https://creativecommons.org/publicdomain/zero/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: https://creativecommons.org/publicdomain/zero/1.0/ and is available at: https://www.kaggle.com/janiobachmann/bank-marketing-dataset .\n",
|
||||||
|
"\n",
|
||||||
|
"_**Acknowledgements**_\n",
|
||||||
|
"This data set is originally available within the UCI Machine Learning Database: https://archive.ics.uci.edu/ml/datasets/bank+marketing\n",
|
||||||
|
"\n",
|
||||||
|
"[Moro et al., 2014] S. Moro, P. Cortez and P. Rita. A Data-Driven Approach to Predict the Success of Bank Telemarketing. Decision Support Systems, Elsevier, 62:22-31, June 2014"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "anumamah"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"AML"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"Bankmarketing"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"ACI"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"framework": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"friendly_name": "Automated ML run with basic edition features.",
|
||||||
|
"index_order": 5,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.7"
|
||||||
|
},
|
||||||
|
"tags": [
|
||||||
|
"featurization",
|
||||||
|
"explainability",
|
||||||
|
"remote_run",
|
||||||
|
"AutomatedML"
|
||||||
|
],
|
||||||
|
"task": "Classification"
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-classification-bank-marketing-all-features
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,503 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Classification of credit card fraudulent transactions on remote compute **_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"In this example we use the associated credit card dataset to showcase how you can use AutoML for a simple classification problem. The goal is to predict if a credit card transaction is considered a fraudulent charge.\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook is using remote compute to train the model.\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"1. Create an experiment using an existing workspace.\n",
|
||||||
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"3. Train the model using remote compute.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Test the fitted model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a name for experiment\n",
|
||||||
|
"experiment_name = 'automl-classification-ccard-remote'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment=Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Experiment Name'] = experiment.name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create or Attach existing AmlCompute\n",
|
||||||
|
"A compute target is required to execute the Automated ML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"cpu_cluster_name = \"cpu-cluster-1\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
||||||
|
" max_nodes=6)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"\n",
|
||||||
|
"Load the credit card dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/creditcard.csv\"\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
|
||||||
|
"training_data, validation_data = dataset.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"label_column_name = 'Class'"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification or regression|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
||||||
|
"|**enable_early_stopping**|Stop the run if the metric score is not showing improvement.|\n",
|
||||||
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
|
"\n",
|
||||||
|
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"primary_metric\": 'average_precision_score_weighted',\n",
|
||||||
|
" \"enable_early_stopping\": True,\n",
|
||||||
|
" \"max_concurrent_iterations\": 2, # This is a limit for testing purpose, please increase it as per cluster size\n",
|
||||||
|
" \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ablity to find the best model possible\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'classification',\n",
|
||||||
|
" debug_log = 'automl_errors.log',\n",
|
||||||
|
" compute_target = compute_target,\n",
|
||||||
|
" training_data = training_data,\n",
|
||||||
|
" label_column_name = label_column_name,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Call the `submit` method on the experiment object and pass the run configuration. Depending on the data and the number of iterations this can run for a while. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# If you need to retrieve a run that already started, use the following code\n",
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Widget for Monitoring Runs\n",
|
||||||
|
"\n",
|
||||||
|
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
||||||
|
"\n",
|
||||||
|
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"widget-rundetails-sample"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.widgets import RunDetails\n",
|
||||||
|
"RunDetails(remote_run).show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Explain model\n",
|
||||||
|
"\n",
|
||||||
|
"Automated ML models can be explained and visualized using the SDK Explainability library. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Analyze results\n",
|
||||||
|
"\n",
|
||||||
|
"### Retrieve the Best Model\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
|
"fitted_model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Print the properties of the model\n",
|
||||||
|
"The fitted_model is a python object and you can read the different properties of the object.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Test the fitted model\n",
|
||||||
|
"\n",
|
||||||
|
"Now that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# convert the test data to dataframe\n",
|
||||||
|
"X_test_df = validation_data.drop_columns(columns=[label_column_name]).to_pandas_dataframe()\n",
|
||||||
|
"y_test_df = validation_data.keep_columns(columns=[label_column_name], validate=True).to_pandas_dataframe()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# call the predict functions on the model\n",
|
||||||
|
"y_pred = fitted_model.predict(X_test_df)\n",
|
||||||
|
"y_pred"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Calculate metrics for the prediction\n",
|
||||||
|
"\n",
|
||||||
|
"Now visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values \n",
|
||||||
|
"from the trained model that was returned."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.metrics import confusion_matrix\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import itertools\n",
|
||||||
|
"\n",
|
||||||
|
"cf =confusion_matrix(y_test_df.values,y_pred)\n",
|
||||||
|
"plt.imshow(cf,cmap=plt.cm.Blues,interpolation='nearest')\n",
|
||||||
|
"plt.colorbar()\n",
|
||||||
|
"plt.title('Confusion Matrix')\n",
|
||||||
|
"plt.xlabel('Predicted')\n",
|
||||||
|
"plt.ylabel('Actual')\n",
|
||||||
|
"class_labels = ['False','True']\n",
|
||||||
|
"tick_marks = np.arange(len(class_labels))\n",
|
||||||
|
"plt.xticks(tick_marks,class_labels)\n",
|
||||||
|
"plt.yticks([-0.5,0,1,1.5],['','False','True',''])\n",
|
||||||
|
"# plotting text value inside cells\n",
|
||||||
|
"thresh = cf.max() / 2.\n",
|
||||||
|
"for i,j in itertools.product(range(cf.shape[0]),range(cf.shape[1])):\n",
|
||||||
|
" plt.text(j,i,format(cf[i,j],'d'),horizontalalignment='center',color='white' if cf[i,j] >thresh else 'black')\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Acknowledgements"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This Credit Card fraud Detection dataset is made available under the Open Database License: http://opendatacommons.org/licenses/odbl/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: http://opendatacommons.org/licenses/dbcl/1.0/ and is available at: https://www.kaggle.com/mlg-ulb/creditcardfraud\n",
|
||||||
|
"\n",
|
||||||
|
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u00a9 Libre de Bruxelles) on big data mining and fraud detection.\n",
|
||||||
|
"More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
|
||||||
|
"\n",
|
||||||
|
"Please cite the following works:\n",
|
||||||
|
"\n",
|
||||||
|
"Andrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
|
||||||
|
"\n",
|
||||||
|
"Dal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
|
||||||
|
"\n",
|
||||||
|
"Dal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
|
||||||
|
"\n",
|
||||||
|
"Dal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
|
||||||
|
"\n",
|
||||||
|
"Carcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
|
||||||
|
"\n",
|
||||||
|
"Carcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing\n",
|
||||||
|
"\n",
|
||||||
|
"Bertrand Lebichot, Yann-A\u00c3\u00abl Le Borgne, Liyun He, Frederic Obl\u00c3\u00a9, Gianluca Bontempi Deep-Learning Domain Adaptation Techniques for Credit Cards Fraud Detection, INNSBDDL 2019: Recent Advances in Big Data and Deep Learning, pp 78-88, 2019\n",
|
||||||
|
"\n",
|
||||||
|
"Fabrizio Carcillo, Yann-A\u00c3\u00abl Le Borgne, Olivier Caelen, Frederic Obl\u00c3\u00a9, Gianluca Bontempi Combining Unsupervised and Supervised Learning in Credit Card Fraud Detection Information Sciences, 2019"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "tzvikei"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"AML Compute"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"Creditcard"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"file_extension": ".py",
|
||||||
|
"framework": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"friendly_name": "Classification of credit card fraudulent transactions using Automated ML",
|
||||||
|
"index_order": 5,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.7"
|
||||||
|
},
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"tags": [
|
||||||
|
"remote_run",
|
||||||
|
"AutomatedML"
|
||||||
|
],
|
||||||
|
"task": "Classification",
|
||||||
|
"version": "3.6.7"
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-classification-credit-card-fraud
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -1,510 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Classification with Deployment**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Deploy](#Deploy)\n",
|
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"\n",
|
|
||||||
"In this example we use the scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) to showcase how you can use AutoML for a simple classification problem and deploy it to an Azure Container Instance (ACI).\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an experiment using an existing workspace.\n",
|
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"3. Train the model using local compute.\n",
|
|
||||||
"4. Explore the results.\n",
|
|
||||||
"5. Register the model.\n",
|
|
||||||
"6. Create a container image.\n",
|
|
||||||
"7. Create an Azure Container Instance (ACI) service.\n",
|
|
||||||
"8. Test the ACI service."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import json\n",
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# choose a name for experiment\n",
|
|
||||||
"experiment_name = 'automl-classification-deployment'\n",
|
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-classification-deployment'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment=Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_train = digits.data[10:,:]\n",
|
|
||||||
"y_train = digits.target[10:]\n",
|
|
||||||
"\n",
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" name = experiment_name,\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 20,\n",
|
|
||||||
" iterations = 10,\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Deploy\n",
|
|
||||||
"\n",
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Register the Fitted Model for Deployment\n",
|
|
||||||
"If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"description = 'AutoML Model'\n",
|
|
||||||
"tags = None\n",
|
|
||||||
"model = local_run.register_model(description = description, tags = tags)\n",
|
|
||||||
"\n",
|
|
||||||
"print(local_run.model_id) # This will be written to the script file later in the notebook."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create Scoring Script"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"%%writefile score.py\n",
|
|
||||||
"import pickle\n",
|
|
||||||
"import json\n",
|
|
||||||
"import numpy\n",
|
|
||||||
"import azureml.train.automl\n",
|
|
||||||
"from sklearn.externals import joblib\n",
|
|
||||||
"from azureml.core.model import Model\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"def init():\n",
|
|
||||||
" global model\n",
|
|
||||||
" model_path = Model.get_model_path(model_name = '<<modelid>>') # this name is model.id of model that we want to deploy\n",
|
|
||||||
" # deserialize the model file back into a sklearn model\n",
|
|
||||||
" model = joblib.load(model_path)\n",
|
|
||||||
"\n",
|
|
||||||
"def run(rawdata):\n",
|
|
||||||
" try:\n",
|
|
||||||
" data = json.loads(rawdata)['data']\n",
|
|
||||||
" data = numpy.array(data)\n",
|
|
||||||
" result = model.predict(data)\n",
|
|
||||||
" except Exception as e:\n",
|
|
||||||
" result = str(e)\n",
|
|
||||||
" return json.dumps({\"error\": result})\n",
|
|
||||||
" return json.dumps({\"result\":result.tolist()})"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create a YAML File for the Environment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"To ensure the fit results are consistent with the training results, the SDK dependency versions need to be the same as the environment that trains the model. The following cells create a file, myenv.yml, which specifies the dependencies from the run."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"ml_run = AutoMLRun(experiment = experiment, run_id = local_run.id)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"dependencies = ml_run.get_run_sdk_dependencies(iteration = 7)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n",
|
|
||||||
" print('{}\\t{}'.format(p, dependencies[p]))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"\n",
|
|
||||||
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn','py-xgboost<=0.80'],\n",
|
|
||||||
" pip_packages=['azureml-sdk[automl]'])\n",
|
|
||||||
"\n",
|
|
||||||
"conda_env_file_name = 'myenv.yml'\n",
|
|
||||||
"myenv.save_to_file('.', conda_env_file_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Substitute the actual version number in the environment file.\n",
|
|
||||||
"# This is not strictly needed in this notebook because the model should have been generated using the current SDK version.\n",
|
|
||||||
"# However, we include this in case this code is used on an experiment from a previous SDK version.\n",
|
|
||||||
"\n",
|
|
||||||
"with open(conda_env_file_name, 'r') as cefr:\n",
|
|
||||||
" content = cefr.read()\n",
|
|
||||||
"\n",
|
|
||||||
"with open(conda_env_file_name, 'w') as cefw:\n",
|
|
||||||
" cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n",
|
|
||||||
"\n",
|
|
||||||
"# Substitute the actual model id in the script file.\n",
|
|
||||||
"\n",
|
|
||||||
"script_file_name = 'score.py'\n",
|
|
||||||
"\n",
|
|
||||||
"with open(script_file_name, 'r') as cefr:\n",
|
|
||||||
" content = cefr.read()\n",
|
|
||||||
"\n",
|
|
||||||
"with open(script_file_name, 'w') as cefw:\n",
|
|
||||||
" cefw.write(content.replace('<<modelid>>', local_run.model_id))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create a Container Image"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.image import Image, ContainerImage\n",
|
|
||||||
"\n",
|
|
||||||
"image_config = ContainerImage.image_configuration(runtime= \"python\",\n",
|
|
||||||
" execution_script = script_file_name,\n",
|
|
||||||
" conda_file = conda_env_file_name,\n",
|
|
||||||
" tags = {'area': \"digits\", 'type': \"automl_classification\"},\n",
|
|
||||||
" description = \"Image for automl classification sample\")\n",
|
|
||||||
"\n",
|
|
||||||
"image = Image.create(name = \"automlsampleimage\",\n",
|
|
||||||
" # this is the model object \n",
|
|
||||||
" models = [model],\n",
|
|
||||||
" image_config = image_config, \n",
|
|
||||||
" workspace = ws)\n",
|
|
||||||
"\n",
|
|
||||||
"image.wait_for_creation(show_output = True)\n",
|
|
||||||
"\n",
|
|
||||||
"if image.creation_state == 'Failed':\n",
|
|
||||||
" print(\"Image build log at: \" + image.image_build_log_uri)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Deploy the Image as a Web Service on Azure Container Instance"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.webservice import AciWebservice\n",
|
|
||||||
"\n",
|
|
||||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
|
||||||
" memory_gb = 1, \n",
|
|
||||||
" tags = {'area': \"digits\", 'type': \"automl_classification\"}, \n",
|
|
||||||
" description = 'sample service for Automl Classification')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.webservice import Webservice\n",
|
|
||||||
"\n",
|
|
||||||
"aci_service_name = 'automl-sample-01'\n",
|
|
||||||
"print(aci_service_name)\n",
|
|
||||||
"aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n",
|
|
||||||
" image = image,\n",
|
|
||||||
" name = aci_service_name,\n",
|
|
||||||
" workspace = ws)\n",
|
|
||||||
"aci_service.wait_for_deployment(True)\n",
|
|
||||||
"print(aci_service.state)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Delete a Web Service"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#aci_service.delete()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Get Logs from a Deployed Web Service"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#aci_service.get_logs()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Randomly select digits and test\n",
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_test = digits.data[:10, :]\n",
|
|
||||||
"y_test = digits.target[:10]\n",
|
|
||||||
"images = digits.images[:10]\n",
|
|
||||||
"\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 3, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" test_sample = json.dumps({'data':X_test[index:index + 1].tolist()})\n",
|
|
||||||
" predicted = aci_service.run(input_data = test_sample)\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" predictedDict = json.loads(predicted)\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %s \" % ( label,predictedDict['result'][0])\n",
|
|
||||||
" fig = plt.figure(1, figsize = (3,3))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" plt.show()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1,358 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Classification with Local Compute**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)\n",
|
|
||||||
"\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"\n",
|
|
||||||
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"Please find the ONNX related documentations [here](https://github.com/onnx/onnx).\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"3. Train the model using local compute with ONNX compatible config on.\n",
|
|
||||||
"4. Explore the results and save the ONNX model."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig, constants"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
|
||||||
"experiment_name = 'automl-classification-onnx'\n",
|
|
||||||
"project_folder = './sample_projects/automl-classification-onnx'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data\n",
|
|
||||||
"\n",
|
|
||||||
"This uses scikit-learn's [load_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) method."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iris = datasets.load_iris()\n",
|
|
||||||
"X_train, X_test, y_train, y_test = train_test_split(iris.data, \n",
|
|
||||||
" iris.target, \n",
|
|
||||||
" test_size=0.2, \n",
|
|
||||||
" random_state=0)\n",
|
|
||||||
"\n",
|
|
||||||
"# Convert the X_train and X_test to pandas DataFrame and set column names,\n",
|
|
||||||
"# This is needed for initializing the input variable names of ONNX model, \n",
|
|
||||||
"# and the prediction with the ONNX model using the inference helper.\n",
|
|
||||||
"X_train = pd.DataFrame(X_train, columns=['c1', 'c2', 'c3', 'c4'])\n",
|
|
||||||
"X_test = pd.DataFrame(X_test, columns=['c1', 'c2', 'c3', 'c4'])"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train with enable ONNX compatible models config on\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"Set the parameter enable_onnx_compatible_models=True, if you also want to generate the ONNX compatible models. Please note, the forecasting task and TensorFlow models are not ONNX compatible yet.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**enable_onnx_compatible_models**|Enable the ONNX compatible models in the experiment.|\n",
|
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 60,\n",
|
|
||||||
" iterations = 10,\n",
|
|
||||||
" verbosity = logging.INFO, \n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" preprocess=True,\n",
|
|
||||||
" enable_onnx_compatible_models=True,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(local_run).show() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best ONNX Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*.\n",
|
|
||||||
"\n",
|
|
||||||
"Set the parameter return_onnx_model=True to retrieve the best ONNX model, instead of the Python model."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, onnx_mdl = local_run.get_output(return_onnx_model=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Save the best ONNX model"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.automl.core.onnx_convert import OnnxConverter\n",
|
|
||||||
"onnx_fl_path = \"./best_model.onnx\"\n",
|
|
||||||
"OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Predict with the ONNX model, using onnxruntime package"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import sys\n",
|
|
||||||
"import json\n",
|
|
||||||
"from azureml.automl.core.onnx_convert import OnnxConvertConstants\n",
|
|
||||||
"\n",
|
|
||||||
"if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n",
|
|
||||||
" python_version_compatible = True\n",
|
|
||||||
"else:\n",
|
|
||||||
" python_version_compatible = False\n",
|
|
||||||
"\n",
|
|
||||||
"try:\n",
|
|
||||||
" import onnxruntime\n",
|
|
||||||
" from azureml.automl.core.onnx_convert import OnnxInferenceHelper \n",
|
|
||||||
" onnxrt_present = True\n",
|
|
||||||
"except ImportError:\n",
|
|
||||||
" onnxrt_present = False\n",
|
|
||||||
"\n",
|
|
||||||
"def get_onnx_res(run):\n",
|
|
||||||
" res_path = '_debug_y_trans_converter.json'\n",
|
|
||||||
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
|
|
||||||
" with open(res_path) as f:\n",
|
|
||||||
" onnx_res = json.load(f)\n",
|
|
||||||
" return onnx_res\n",
|
|
||||||
"\n",
|
|
||||||
"if onnxrt_present and python_version_compatible: \n",
|
|
||||||
" mdl_bytes = onnx_mdl.SerializeToString()\n",
|
|
||||||
" onnx_res = get_onnx_res(best_run)\n",
|
|
||||||
"\n",
|
|
||||||
" onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n",
|
|
||||||
" pred_onnx, pred_prob_onnx = onnxrt_helper.predict(X_test)\n",
|
|
||||||
"\n",
|
|
||||||
" print(pred_onnx)\n",
|
|
||||||
" print(pred_prob_onnx)\n",
|
|
||||||
"else:\n",
|
|
||||||
" if not python_version_compatible:\n",
|
|
||||||
" print('Please use Python version 3.6 to run the inference helper.') \n",
|
|
||||||
" if not onnxrt_present:\n",
|
|
||||||
" print('Please install the onnxruntime package to do the prediction with ONNX model.')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": []
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1,399 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Classification using whitelist models**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"\n",
|
|
||||||
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"This notebooks shows how can automl can be trained on a a selected list of models,see the readme.md for the models.\n",
|
|
||||||
"This trains the model exclusively on tensorflow based models.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"3. Train the model on a whilelisted models using local compute. \n",
|
|
||||||
"4. Explore the results.\n",
|
|
||||||
"5. Test the best fitted model."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Note: This notebook will install tensorflow if not already installed in the enviornment..\n",
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"import sys\n",
|
|
||||||
"whitelist_models=[\"LightGBM\"]\n",
|
|
||||||
"if \"3.7\" != sys.version[0:3]:\n",
|
|
||||||
" try:\n",
|
|
||||||
" import tensorflow as tf1\n",
|
|
||||||
" except ImportError:\n",
|
|
||||||
" from pip._internal import main\n",
|
|
||||||
" main(['install', 'tensorflow>=1.10.0,<=1.12.0'])\n",
|
|
||||||
" logging.getLogger().setLevel(logging.ERROR)\n",
|
|
||||||
" whitelist_models=[\"TensorFlowLinearClassifier\", \"TensorFlowDNN\"]\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
|
||||||
"experiment_name = 'automl-local-whitelist'\n",
|
|
||||||
"project_folder = './sample_projects/automl-local-whitelist'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data\n",
|
|
||||||
"\n",
|
|
||||||
"This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"\n",
|
|
||||||
"# Exclude the first 100 rows from training so that they can be used for test.\n",
|
|
||||||
"X_train = digits.data[100:,:]\n",
|
|
||||||
"y_train = digits.target[100:]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>balanced_accuracy</i><br><i>average_precision_score_weighted</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n",
|
|
||||||
"|**whitelist_models**|List of models that AutoML should use. The possible values are listed [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings).|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 60,\n",
|
|
||||||
" iterations = 10,\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" enable_tf=True,\n",
|
|
||||||
" whitelist_models=whitelist_models,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(local_run).show() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"\n",
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model that has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the third iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 3\n",
|
|
||||||
"third_run, third_model = local_run.get_output(iteration = iteration)\n",
|
|
||||||
"print(third_run)\n",
|
|
||||||
"print(third_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_test = digits.data[:10, :]\n",
|
|
||||||
"y_test = digits.target[:10]\n",
|
|
||||||
"images = digits.images[:10]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Testing Our Best Fitted Model\n",
|
|
||||||
"We will try to predict 2 digits and see how our model works."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
|
|
||||||
" fig = plt.figure(1, figsize = (3,3))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" plt.show()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1,482 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Classification with Local Compute**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)\n",
|
|
||||||
"\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"\n",
|
|
||||||
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"3. Train the model using local compute.\n",
|
|
||||||
"4. Explore the results.\n",
|
|
||||||
"5. Test the best fitted model."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Accessing the Azure ML workspace requires authentication with Azure.\n",
|
|
||||||
"\n",
|
|
||||||
"The default authentication is interactive authentication using the default tenant. Executing the `ws = Workspace.from_config()` line in the cell below will prompt for authentication the first time that it is run.\n",
|
|
||||||
"\n",
|
|
||||||
"If you have multiple Azure tenants, you can specify the tenant by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n",
|
|
||||||
"\n",
|
|
||||||
"```\n",
|
|
||||||
"from azureml.core.authentication import InteractiveLoginAuthentication\n",
|
|
||||||
"auth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"If you need to run in an environment where interactive login is not possible, you can use Service Principal authentication by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n",
|
|
||||||
"\n",
|
|
||||||
"```\n",
|
|
||||||
"from azureml.core.authentication import ServicePrincipalAuthentication\n",
|
|
||||||
"auth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"```\n",
|
|
||||||
"For more details, see [aka.ms/aml-notebook-auth](http://aka.ms/aml-notebook-auth)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
|
||||||
"experiment_name = 'automl-classification'\n",
|
|
||||||
"project_folder = './sample_projects/automl-classification'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data\n",
|
|
||||||
"\n",
|
|
||||||
"This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"\n",
|
|
||||||
"# Exclude the first 100 rows from training so that they can be used for test.\n",
|
|
||||||
"X_train = digits.data[100:,:]\n",
|
|
||||||
"y_train = digits.target[100:]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
|
||||||
"|\n",
|
|
||||||
"\n",
|
|
||||||
"Automated machine learning trains multiple machine learning pipelines. Each pipelines training is known as an iteration.\n",
|
|
||||||
"* You can specify a maximum number of iterations using the `iterations` parameter.\n",
|
|
||||||
"* You can specify a maximum time for the run using the `experiment_timeout_minutes` parameter.\n",
|
|
||||||
"* If you specify neither the `iterations` nor the `experiment_timeout_minutes`, automated ML keeps running iterations while it continues to see improvements in the scores.\n",
|
|
||||||
"\n",
|
|
||||||
"The following example doesn't specify `iterations` or `experiment_timeout_minutes` and so runs until the scores stop improving.\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" n_cross_validations = 3)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Optionally, you can continue an interrupted local run by calling `continue_experiment` without the `iterations` parameter, or run more iterations for a completed run by specifying the `iterations` parameter:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = local_run.continue_experiment(X = X_train, \n",
|
|
||||||
" y = y_train, \n",
|
|
||||||
" show_output = True,\n",
|
|
||||||
" iterations = 5)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(local_run).show() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"\n",
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
|
||||||
"print(best_run)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Print the properties of the model\n",
|
|
||||||
"The fitted_model is a python object and you can read the different properties of the object.\n",
|
|
||||||
"The following shows printing hyperparameters for each step in the pipeline."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from pprint import pprint\n",
|
|
||||||
"\n",
|
|
||||||
"def print_model(model, prefix=\"\"):\n",
|
|
||||||
" for step in model.steps:\n",
|
|
||||||
" print(prefix + step[0])\n",
|
|
||||||
" if hasattr(step[1], 'estimators') and hasattr(step[1], 'weights'):\n",
|
|
||||||
" pprint({'estimators': list(e[0] for e in step[1].estimators), 'weights': step[1].weights})\n",
|
|
||||||
" print()\n",
|
|
||||||
" for estimator in step[1].estimators:\n",
|
|
||||||
" print_model(estimator[1], estimator[0]+ ' - ')\n",
|
|
||||||
" elif hasattr(step[1], '_base_learners') and hasattr(step[1], '_meta_learner'):\n",
|
|
||||||
" print(\"\\nMeta Learner\")\n",
|
|
||||||
" pprint(step[1]._meta_learner)\n",
|
|
||||||
" print()\n",
|
|
||||||
" for estimator in step[1]._base_learners:\n",
|
|
||||||
" print_model(estimator[1], estimator[0]+ ' - ')\n",
|
|
||||||
" else:\n",
|
|
||||||
" pprint(step[1].get_params())\n",
|
|
||||||
" print()\n",
|
|
||||||
" \n",
|
|
||||||
"print_model(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model that has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print_model(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the third iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 3\n",
|
|
||||||
"third_run, third_model = local_run.get_output(iteration = iteration)\n",
|
|
||||||
"print(third_run)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print_model(third_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test \n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_test = digits.data[:10, :]\n",
|
|
||||||
"y_test = digits.target[:10]\n",
|
|
||||||
"images = digits.images[:10]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Testing Our Best Fitted Model\n",
|
|
||||||
"We will try to predict 2 digits and see how our model works."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
|
|
||||||
" fig = plt.figure(1, figsize = (3,3))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" plt.show()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,576 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning \n",
|
||||||
|
"**Continuous retraining using Pipelines and Time-Series TabularDataset**\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"2. [Setup](#Setup)\n",
|
||||||
|
"3. [Compute](#Compute)\n",
|
||||||
|
"4. [Run Configuration](#Run-Configuration)\n",
|
||||||
|
"5. [Data Ingestion Pipeline](#Data-Ingestion-Pipeline)\n",
|
||||||
|
"6. [Training Pipeline](#Training-Pipeline)\n",
|
||||||
|
"7. [Publish Retraining Pipeline and Schedule](#Publish-Retraining-Pipeline-and-Schedule)\n",
|
||||||
|
"8. [Test Retraining](#Test-Retraining)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"In this example we use AutoML and Pipelines to enable contious retraining of a model based on updates to the training dataset. We will create two pipelines, the first one to demonstrate a training dataset that gets updated over time. We leverage time-series capabilities of `TabularDataset` to achieve this. The second pipeline utilizes pipeline `Schedule` to trigger continuous retraining. \n",
|
||||||
|
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"* Create an Experiment in an existing Workspace.\n",
|
||||||
|
"* Configure AutoML using AutoMLConfig.\n",
|
||||||
|
"* Create data ingestion pipeline to update a time-series based TabularDataset\n",
|
||||||
|
"* Create training pipeline to prepare data, run AutoML, register the model and setup pipeline triggers.\n",
|
||||||
|
"\n",
|
||||||
|
"## Setup\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"from sklearn import datasets\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Accessing the Azure ML workspace requires authentication with Azure.\n",
|
||||||
|
"\n",
|
||||||
|
"The default authentication is interactive authentication using the default tenant. Executing the ws = Workspace.from_config() line in the cell below will prompt for authentication the first time that it is run.\n",
|
||||||
|
"\n",
|
||||||
|
"If you have multiple Azure tenants, you can specify the tenant by replacing the ws = Workspace.from_config() line in the cell below with the following:\n",
|
||||||
|
"```\n",
|
||||||
|
"from azureml.core.authentication import InteractiveLoginAuthentication\n",
|
||||||
|
"auth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\n",
|
||||||
|
"ws = Workspace.from_config(auth = auth)\n",
|
||||||
|
"```\n",
|
||||||
|
"If you need to run in an environment where interactive login is not possible, you can use Service Principal authentication by replacing the ws = Workspace.from_config() line in the cell below with the following:\n",
|
||||||
|
"```\n",
|
||||||
|
"from azureml.core.authentication import ServicePrincipalAuthentication\n",
|
||||||
|
"auth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\n",
|
||||||
|
"ws = Workspace.from_config(auth = auth)\n",
|
||||||
|
"```\n",
|
||||||
|
"For more details, see aka.ms/aml-notebook-auth"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"dstor = ws.get_default_datastore()\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for the run history container in the workspace.\n",
|
||||||
|
"experiment_name = 'retrain-noaaweather'\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Run History Name'] = experiment_name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Compute \n",
|
||||||
|
"\n",
|
||||||
|
"#### Create or Attach existing AmlCompute\n",
|
||||||
|
"\n",
|
||||||
|
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read this article on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"amlcompute_cluster_name = \"cont-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Run Configuration"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.runconfig import CondaDependencies, RunConfiguration\n",
|
||||||
|
"\n",
|
||||||
|
"# create a new RunConfig object\n",
|
||||||
|
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Set compute target to AmlCompute\n",
|
||||||
|
"conda_run_config.target = compute_target\n",
|
||||||
|
"\n",
|
||||||
|
"conda_run_config.environment.docker.enabled = True\n",
|
||||||
|
"\n",
|
||||||
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', 'applicationinsights', 'azureml-opendatasets', 'azureml-defaults'], \n",
|
||||||
|
" conda_packages=['numpy==1.16.2'], \n",
|
||||||
|
" pin_sdk_version=False)\n",
|
||||||
|
"conda_run_config.environment.python.conda_dependencies = cd\n",
|
||||||
|
"\n",
|
||||||
|
"print('run config is ready')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Data Ingestion Pipeline \n",
|
||||||
|
"For this demo, we will use NOAA weather data from [Azure Open Datasets](https://azure.microsoft.com/services/open-datasets/). You can replace this with your own dataset, or you can skip this pipeline if you already have a time-series based `TabularDataset`.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# The name and target column of the Dataset to create \n",
|
||||||
|
"dataset = \"NOAA-Weather-DS4\"\n",
|
||||||
|
"target_column_name = \"temperature\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
"### Upload Data Step\n",
|
||||||
|
"The data ingestion pipeline has a single step with a script to query the latest weather data and upload it to the blob store. During the first run, the script will create and register a time-series based `TabularDataset` with the past one week of weather data. For each subsequent run, the script will create a partition in the blob store by querying NOAA for new weather data since the last modified time of the dataset (`dataset.data_changed_time`) and creating a data.csv file."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Pipeline, PipelineParameter\n",
|
||||||
|
"from azureml.pipeline.steps import PythonScriptStep\n",
|
||||||
|
"\n",
|
||||||
|
"ds_name = PipelineParameter(name=\"ds_name\", default_value=dataset)\n",
|
||||||
|
"upload_data_step = PythonScriptStep(script_name=\"upload_weather_data.py\", \n",
|
||||||
|
" allow_reuse=False,\n",
|
||||||
|
" name=\"upload_weather_data\",\n",
|
||||||
|
" arguments=[\"--ds_name\", ds_name],\n",
|
||||||
|
" compute_target=compute_target, \n",
|
||||||
|
" runconfig=conda_run_config)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Submit Pipeline Run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data_pipeline = Pipeline(\n",
|
||||||
|
" description=\"pipeline_with_uploaddata\",\n",
|
||||||
|
" workspace=ws, \n",
|
||||||
|
" steps=[upload_data_step])\n",
|
||||||
|
"data_pipeline_run = experiment.submit(data_pipeline, pipeline_parameters={\"ds_name\":dataset})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data_pipeline_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Training Pipeline\n",
|
||||||
|
"### Prepare Training Data Step\n",
|
||||||
|
"\n",
|
||||||
|
"Script to check if new data is available since the model was last trained. If no new data is available, we cancel the remaining pipeline steps. We need to set allow_reuse flag to False to allow the pipeline to run even when inputs don't change. We also need the name of the model to check the time the model was last trained."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import PipelineData\n",
|
||||||
|
"\n",
|
||||||
|
"# The model name with which to register the trained model in the workspace.\n",
|
||||||
|
"model_name = PipelineParameter(\"model_name\", default_value=\"noaaweatherds\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data_prep_step = PythonScriptStep(script_name=\"check_data.py\", \n",
|
||||||
|
" allow_reuse=False,\n",
|
||||||
|
" name=\"check_data\",\n",
|
||||||
|
" arguments=[\"--ds_name\", ds_name,\n",
|
||||||
|
" \"--model_name\", model_name],\n",
|
||||||
|
" compute_target=compute_target, \n",
|
||||||
|
" runconfig=conda_run_config)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Dataset\n",
|
||||||
|
"train_ds = Dataset.get_by_name(ws, dataset)\n",
|
||||||
|
"train_ds = train_ds.drop_columns([\"partition_date\"])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### AutoMLStep\n",
|
||||||
|
"Create an AutoMLConfig and a training step."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"from azureml.pipeline.steps import AutoMLStep\n",
|
||||||
|
"\n",
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"iteration_timeout_minutes\": 10,\n",
|
||||||
|
" \"experiment_timeout_hours\": 0.25,\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"primary_metric\": 'r2_score',\n",
|
||||||
|
" \"max_concurrent_iterations\": 3,\n",
|
||||||
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
" \"enable_early_stopping\": True\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'regression',\n",
|
||||||
|
" debug_log = 'automl_errors.log',\n",
|
||||||
|
" path = \".\",\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" training_data = train_ds,\n",
|
||||||
|
" label_column_name = target_column_name,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import PipelineData, TrainingOutput\n",
|
||||||
|
"\n",
|
||||||
|
"metrics_output_name = 'metrics_output'\n",
|
||||||
|
"best_model_output_name = 'best_model_output'\n",
|
||||||
|
"\n",
|
||||||
|
"metrics_data = PipelineData(name='metrics_data',\n",
|
||||||
|
" datastore=dstor,\n",
|
||||||
|
" pipeline_output_name=metrics_output_name,\n",
|
||||||
|
" training_output=TrainingOutput(type='Metrics'))\n",
|
||||||
|
"model_data = PipelineData(name='model_data',\n",
|
||||||
|
" datastore=dstor,\n",
|
||||||
|
" pipeline_output_name=best_model_output_name,\n",
|
||||||
|
" training_output=TrainingOutput(type='Model'))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_step = AutoMLStep(\n",
|
||||||
|
" name='automl_module',\n",
|
||||||
|
" automl_config=automl_config,\n",
|
||||||
|
" outputs=[metrics_data, model_data],\n",
|
||||||
|
" allow_reuse=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Register Model Step\n",
|
||||||
|
"Script to register the model to the workspace. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"register_model_step = PythonScriptStep(script_name=\"register_model.py\",\n",
|
||||||
|
" name=\"register_model\",\n",
|
||||||
|
" allow_reuse=False,\n",
|
||||||
|
" arguments=[\"--model_name\", model_name, \"--model_path\", model_data, \"--ds_name\", ds_name],\n",
|
||||||
|
" inputs=[model_data],\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" runconfig=conda_run_config)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Submit Pipeline Run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_pipeline = Pipeline(\n",
|
||||||
|
" description=\"training_pipeline\",\n",
|
||||||
|
" workspace=ws, \n",
|
||||||
|
" steps=[data_prep_step, automl_step, register_model_step])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_pipeline_run = experiment.submit(training_pipeline, pipeline_parameters={\n",
|
||||||
|
" \"ds_name\": dataset, \"model_name\": \"noaaweatherds\"})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_pipeline_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Publish Retraining Pipeline and Schedule\n",
|
||||||
|
"Once we are happy with the pipeline, we can publish the training pipeline to the workspace and create a schedule to trigger on blob change. The schedule polls the blob store where the data is being uploaded and runs the retraining pipeline if there is a data change. A new version of the model will be registered to the workspace once the run is complete."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"pipeline_name = \"Retraining-Pipeline-NOAAWeather\"\n",
|
||||||
|
"\n",
|
||||||
|
"published_pipeline = training_pipeline.publish(\n",
|
||||||
|
" name=pipeline_name, \n",
|
||||||
|
" description=\"Pipeline that retrains AutoML model\")\n",
|
||||||
|
"\n",
|
||||||
|
"published_pipeline"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Schedule\n",
|
||||||
|
"schedule = Schedule.create(workspace=ws, name=\"RetrainingSchedule\",\n",
|
||||||
|
" pipeline_parameters={\"ds_name\": dataset, \"model_name\": \"noaaweatherds\"},\n",
|
||||||
|
" pipeline_id=published_pipeline.id, \n",
|
||||||
|
" experiment_name=experiment_name, \n",
|
||||||
|
" datastore=dstor,\n",
|
||||||
|
" wait_for_provisioning=True,\n",
|
||||||
|
" polling_interval=1440)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Test Retraining\n",
|
||||||
|
"Here we setup the data ingestion pipeline to run on a schedule, to verify that the retraining pipeline runs as expected. \n",
|
||||||
|
"\n",
|
||||||
|
"Note: \n",
|
||||||
|
"* Azure NOAA Weather data is updated daily and retraining will not trigger if there is no new data available. \n",
|
||||||
|
"* Depending on the polling interval set in the schedule, the retraining may take some time trigger after data ingestion pipeline completes."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"pipeline_name = \"DataIngestion-Pipeline-NOAAWeather\"\n",
|
||||||
|
"\n",
|
||||||
|
"published_pipeline = training_pipeline.publish(\n",
|
||||||
|
" name=pipeline_name, \n",
|
||||||
|
" description=\"Pipeline that updates NOAAWeather Dataset\")\n",
|
||||||
|
"\n",
|
||||||
|
"published_pipeline"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Schedule\n",
|
||||||
|
"schedule = Schedule.create(workspace=ws, name=\"RetrainingSchedule-DataIngestion\",\n",
|
||||||
|
" pipeline_parameters={\"ds_name\":dataset},\n",
|
||||||
|
" pipeline_id=published_pipeline.id, \n",
|
||||||
|
" experiment_name=experiment_name, \n",
|
||||||
|
" datastore=dstor,\n",
|
||||||
|
" wait_for_provisioning=True,\n",
|
||||||
|
" polling_interval=1440)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "anshirga"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-continuous-retraining
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import azureml.core
|
||||||
|
from datetime import datetime
|
||||||
|
import pandas as pd
|
||||||
|
import pytz
|
||||||
|
from azureml.core import Dataset, Model
|
||||||
|
from azureml.core.run import Run, _OfflineRun
|
||||||
|
from azureml.core import Workspace
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
ws = None
|
||||||
|
if type(run) == _OfflineRun:
|
||||||
|
ws = Workspace.from_config()
|
||||||
|
else:
|
||||||
|
ws = run.experiment.workspace
|
||||||
|
|
||||||
|
print("Check for new data.")
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser("split")
|
||||||
|
parser.add_argument("--ds_name", help="input dataset name")
|
||||||
|
parser.add_argument("--model_name", help="name of the deployed model")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
print("Argument 1(ds_name): %s" % args.ds_name)
|
||||||
|
print("Argument 2(model_name): %s" % args.model_name)
|
||||||
|
|
||||||
|
# Get the latest registered model
|
||||||
|
try:
|
||||||
|
model = Model(ws, args.model_name)
|
||||||
|
last_train_time = model.created_time
|
||||||
|
print("Model was last trained on {0}.".format(last_train_time))
|
||||||
|
except Exception as e:
|
||||||
|
print("Could not get last model train time.")
|
||||||
|
last_train_time = datetime.min.replace(tzinfo=pytz.UTC)
|
||||||
|
|
||||||
|
train_ds = Dataset.get_by_name(ws, args.ds_name)
|
||||||
|
dataset_changed_time = train_ds.data_changed_time
|
||||||
|
|
||||||
|
if not dataset_changed_time > last_train_time:
|
||||||
|
print("Cancelling run since there is no new data.")
|
||||||
|
run.parent.cancel()
|
||||||
|
else:
|
||||||
|
# New data is available since the model was last trained
|
||||||
|
print("Dataset was last updated on {0}. Retraining...".format(dataset_changed_time))
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from azureml.core.model import Model, Dataset
|
||||||
|
from azureml.core.run import Run, _OfflineRun
|
||||||
|
from azureml.core import Workspace
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--model_name")
|
||||||
|
parser.add_argument("--model_path")
|
||||||
|
parser.add_argument("--ds_name")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
print("Argument 1(model_name): %s" % args.model_name)
|
||||||
|
print("Argument 2(model_path): %s" % args.model_path)
|
||||||
|
print("Argument 3(ds_name): %s" % args.ds_name)
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
ws = None
|
||||||
|
if type(run) == _OfflineRun:
|
||||||
|
ws = Workspace.from_config()
|
||||||
|
else:
|
||||||
|
ws = run.experiment.workspace
|
||||||
|
|
||||||
|
train_ds = Dataset.get_by_name(ws, args.ds_name)
|
||||||
|
datasets = [(Dataset.Scenario.TRAINING, train_ds)]
|
||||||
|
|
||||||
|
# Register model with training dataset
|
||||||
|
|
||||||
|
model = Model.register(workspace=ws,
|
||||||
|
model_path=args.model_path,
|
||||||
|
model_name=args.model_name,
|
||||||
|
datasets=datasets)
|
||||||
|
|
||||||
|
print("Registered version {0} of model {1}".format(model.version, model.name))
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
from dateutil.relativedelta import relativedelta
|
||||||
|
import pandas as pd
|
||||||
|
import traceback
|
||||||
|
from azureml.core import Dataset
|
||||||
|
from azureml.core.run import Run, _OfflineRun
|
||||||
|
from azureml.core import Workspace
|
||||||
|
from azureml.opendatasets import NoaaIsdWeather
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
ws = None
|
||||||
|
if type(run) == _OfflineRun:
|
||||||
|
ws = Workspace.from_config()
|
||||||
|
else:
|
||||||
|
ws = run.experiment.workspace
|
||||||
|
|
||||||
|
usaf_list = ['725724', '722149', '723090', '722159', '723910', '720279',
|
||||||
|
'725513', '725254', '726430', '720381', '723074', '726682',
|
||||||
|
'725486', '727883', '723177', '722075', '723086', '724053',
|
||||||
|
'725070', '722073', '726060', '725224', '725260', '724520',
|
||||||
|
'720305', '724020', '726510', '725126', '722523', '703333',
|
||||||
|
'722249', '722728', '725483', '722972', '724975', '742079',
|
||||||
|
'727468', '722193', '725624', '722030', '726380', '720309',
|
||||||
|
'722071', '720326', '725415', '724504', '725665', '725424',
|
||||||
|
'725066']
|
||||||
|
|
||||||
|
|
||||||
|
def get_noaa_data(start_time, end_time):
|
||||||
|
columns = ['usaf', 'wban', 'datetime', 'latitude', 'longitude', 'elevation',
|
||||||
|
'windAngle', 'windSpeed', 'temperature', 'stationName', 'p_k']
|
||||||
|
isd = NoaaIsdWeather(start_time, end_time, cols=columns)
|
||||||
|
noaa_df = isd.to_pandas_dataframe()
|
||||||
|
df_filtered = noaa_df[noaa_df["usaf"].isin(usaf_list)]
|
||||||
|
df_filtered.reset_index(drop=True)
|
||||||
|
print("Received {0} rows of training data between {1} and {2}".format(
|
||||||
|
df_filtered.shape[0], start_time, end_time))
|
||||||
|
return df_filtered
|
||||||
|
|
||||||
|
|
||||||
|
print("Check for new data and prepare the data")
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser("split")
|
||||||
|
parser.add_argument("--ds_name", help="name of the Dataset to update")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
print("Argument 1(ds_name): %s" % args.ds_name)
|
||||||
|
|
||||||
|
dstor = ws.get_default_datastore()
|
||||||
|
register_dataset = False
|
||||||
|
try:
|
||||||
|
ds = Dataset.get_by_name(ws, args.ds_name)
|
||||||
|
end_time_last_slice = ds.data_changed_time.replace(tzinfo=None)
|
||||||
|
print("Dataset {0} last updated on {1}".format(args.ds_name,
|
||||||
|
end_time_last_slice))
|
||||||
|
except Exception as e:
|
||||||
|
print(traceback.format_exc())
|
||||||
|
print("Dataset with name {0} not found, registering new dataset.".format(args.ds_name))
|
||||||
|
register_dataset = True
|
||||||
|
end_time_last_slice = datetime.today() - relativedelta(weeks=2)
|
||||||
|
|
||||||
|
end_time = datetime.utcnow()
|
||||||
|
train_df = get_noaa_data(end_time_last_slice, end_time)
|
||||||
|
|
||||||
|
if train_df.size > 0:
|
||||||
|
print("Received {0} rows of new data after {0}.".format(
|
||||||
|
train_df.shape[0], end_time_last_slice))
|
||||||
|
folder_name = "{}/{:04d}/{:02d}/{:02d}/{:02d}/{:02d}/{:02d}".format(args.ds_name, end_time.year,
|
||||||
|
end_time.month, end_time.day,
|
||||||
|
end_time.hour, end_time.minute,
|
||||||
|
end_time.second)
|
||||||
|
file_path = "{0}/data.csv".format(folder_name)
|
||||||
|
|
||||||
|
# Add a new partition to the registered dataset
|
||||||
|
os.makedirs(folder_name, exist_ok=True)
|
||||||
|
train_df.to_csv(file_path, index=False)
|
||||||
|
|
||||||
|
dstor.upload_files(files=[file_path],
|
||||||
|
target_path=folder_name,
|
||||||
|
overwrite=True,
|
||||||
|
show_progress=True)
|
||||||
|
else:
|
||||||
|
print("No new data since {0}.".format(end_time_last_slice))
|
||||||
|
|
||||||
|
if register_dataset:
|
||||||
|
ds = Dataset.Tabular.from_delimited_files(dstor.path("{}/**/*.csv".format(
|
||||||
|
args.ds_name)), partition_format='/{partition_date:yyyy/MM/dd/HH/mm/ss}/data.csv')
|
||||||
|
ds.register(ws, name=args.ds_name)
|
||||||
@@ -1,526 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Prepare Data using `azureml.dataprep` for Remote Execution (DSVM)**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we showcase how you can use the `azureml.dataprep` SDK to load and prepare data for AutoML. `azureml.dataprep` can also be used standalone; full documentation can be found [here](https://github.com/Microsoft/PendletonDocs).\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Define data loading and preparation steps in a `Dataflow` using `azureml.dataprep`.\n",
|
|
||||||
"2. Pass the `Dataflow` to AutoML for a local run.\n",
|
|
||||||
"3. Pass the `Dataflow` to AutoML for a remote run."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"Currently, Data Prep only supports __Ubuntu 16__ and __Red Hat Enterprise Linux 7__. We are working on supporting more linux distros."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"import time\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.compute import DsvmCompute\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"import azureml.dataprep as dprep\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
" \n",
|
|
||||||
"# choose a name for experiment\n",
|
|
||||||
"experiment_name = 'automl-dataprep-remote-dsvm'\n",
|
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-dataprep-remote-dsvm'\n",
|
|
||||||
" \n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
" \n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# You can use `auto_read_file` which intelligently figures out delimiters and datatypes of a file.\n",
|
|
||||||
"# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n",
|
|
||||||
"# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n",
|
|
||||||
"# and convert column types manually.\n",
|
|
||||||
"example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\n",
|
|
||||||
"dflow = dprep.auto_read_file(example_data).skip(1) # Remove the header row.\n",
|
|
||||||
"dflow.get_profile()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# As `Primary Type` is our y data, we need to drop the values those are null in this column.\n",
|
|
||||||
"dflow = dflow.drop_nulls('Primary Type')\n",
|
|
||||||
"dflow.head(5)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Review the Data Preparation Result\n",
|
|
||||||
"\n",
|
|
||||||
"You can peek the result of a Dataflow at any range using `skip(i)` and `head(j)`. Doing so evaluates only `j` records for all the steps in the Dataflow, which makes it fast even against large datasets.\n",
|
|
||||||
"\n",
|
|
||||||
"`Dataflow` objects are immutable and are composed of a list of data preparation steps. A `Dataflow` object can be branched at any point for further usage."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X = dflow.drop_columns(columns=['Primary Type', 'FBI Code'])\n",
|
|
||||||
"y = dflow.keep_columns(columns=['Primary Type'], validate_column_exists=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"This creates a general AutoML settings object applicable for both local and remote runs."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_settings = {\n",
|
|
||||||
" \"iteration_timeout_minutes\" : 10,\n",
|
|
||||||
" \"iterations\" : 2,\n",
|
|
||||||
" \"primary_metric\" : 'AUC_weighted',\n",
|
|
||||||
" \"preprocess\" : True,\n",
|
|
||||||
" \"verbosity\" : logging.INFO\n",
|
|
||||||
"}"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create or Attach an AmlCompute cluster"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.compute import AmlCompute\n",
|
|
||||||
"from azureml.core.compute import ComputeTarget\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for your cluster.\n",
|
|
||||||
"amlcompute_cluster_name = \"cpu-cluster\"\n",
|
|
||||||
"\n",
|
|
||||||
"found = False\n",
|
|
||||||
"\n",
|
|
||||||
"# Check if this compute target already exists in the workspace.\n",
|
|
||||||
"\n",
|
|
||||||
"cts = ws.compute_targets\n",
|
|
||||||
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n",
|
|
||||||
" found = True\n",
|
|
||||||
" print('Found existing compute target.')\n",
|
|
||||||
" compute_target = cts[amlcompute_cluster_name]\n",
|
|
||||||
"\n",
|
|
||||||
"if not found:\n",
|
|
||||||
" print('Creating a new compute target...')\n",
|
|
||||||
" provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # for GPU, use \"STANDARD_NC6\"\n",
|
|
||||||
" #vm_priority = 'lowpriority', # optional\n",
|
|
||||||
" max_nodes = 6)\n",
|
|
||||||
"\n",
|
|
||||||
" # Create the cluster.\\n\",\n",
|
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n",
|
|
||||||
"\n",
|
|
||||||
" # Can poll for a minimum number of nodes and for a specific timeout.\n",
|
|
||||||
" # If no min_node_count is provided, it will use the scale settings for the cluster.\n",
|
|
||||||
" compute_target.wait_for_completion(show_output = True, min_node_count = None, timeout_in_minutes = 20)\n",
|
|
||||||
"\n",
|
|
||||||
" # For a more detailed view of current AmlCompute status, use get_status()."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"\n",
|
|
||||||
"# create a new RunConfig object\n",
|
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Set compute target to AmlCompute\n",
|
|
||||||
"conda_run_config.target = compute_target\n",
|
|
||||||
"conda_run_config.environment.docker.enabled = True\n",
|
|
||||||
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
|
||||||
"\n",
|
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Pass Data with `Dataflow` Objects\n",
|
|
||||||
"\n",
|
|
||||||
"The `Dataflow` objects captured above can also be passed to the `submit` method for a remote run. AutoML will serialize the `Dataflow` object and send it to the remote compute target. The `Dataflow` will not be evaluated locally."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" path = project_folder,\n",
|
|
||||||
" run_configuration=conda_run_config,\n",
|
|
||||||
" X = X,\n",
|
|
||||||
" y = y,\n",
|
|
||||||
" **automl_settings)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Pre-process cache cleanup\n",
|
|
||||||
"The preprocess data gets cache at user default file store. When the run is completed the cache can be cleaned by running below cell"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run.clean_preprocessor_cache()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Cancelling Runs\n",
|
|
||||||
"You can cancel ongoing remote runs using the `cancel` and `cancel_iteration` functions."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Cancel the ongoing experiment and stop scheduling new iterations.\n",
|
|
||||||
"# remote_run.cancel()\n",
|
|
||||||
"\n",
|
|
||||||
"# Cancel iteration 1 and move onto iteration 2.\n",
|
|
||||||
"# remote_run.cancel_iteration(1)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(remote_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(remote_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
" \n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = remote_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model that has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = remote_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the first iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 0\n",
|
|
||||||
"best_run, fitted_model = remote_run.get_output(iteration = iteration)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data\n",
|
|
||||||
"For the test data, it should have the same preparation step as the train data. Otherwise it might get failed at the preprocessing step."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"dflow_test = dprep.auto_read_file(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv').skip(1)\n",
|
|
||||||
"dflow_test = dflow_test.drop_nulls('Primary Type')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Testing Our Best Fitted Model\n",
|
|
||||||
"We will use confusion matrix to see how our model works."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from pandas_ml import ConfusionMatrix\n",
|
|
||||||
"\n",
|
|
||||||
"y_test = dflow_test.keep_columns(columns=['Primary Type']).to_pandas_dataframe()\n",
|
|
||||||
"X_test = dflow_test.drop_columns(columns=['Primary Type', 'FBI Code']).to_pandas_dataframe()\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"ypred = fitted_model.predict(X_test)\n",
|
|
||||||
"\n",
|
|
||||||
"cm = ConfusionMatrix(y_test['Primary Type'], ypred)\n",
|
|
||||||
"\n",
|
|
||||||
"print(cm)\n",
|
|
||||||
"\n",
|
|
||||||
"cm.plot()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.5"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1,417 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Prepare Data using `azureml.dataprep` for Local Execution**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we showcase how you can use the `azureml.dataprep` SDK to load and prepare data for AutoML. `azureml.dataprep` can also be used standalone; full documentation can be found [here](https://github.com/Microsoft/PendletonDocs).\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Define data loading and preparation steps in a `Dataflow` using `azureml.dataprep`.\n",
|
|
||||||
"2. Pass the `Dataflow` to AutoML for a local run.\n",
|
|
||||||
"3. Pass the `Dataflow` to AutoML for a remote run."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"Currently, Data Prep only supports __Ubuntu 16__ and __Red Hat Enterprise Linux 7__. We are working on supporting more linux distros."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"import azureml.dataprep as dprep\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
" \n",
|
|
||||||
"# choose a name for experiment\n",
|
|
||||||
"experiment_name = 'automl-dataprep-local'\n",
|
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-dataprep-local'\n",
|
|
||||||
" \n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
" \n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# You can use `auto_read_file` which intelligently figures out delimiters and datatypes of a file.\n",
|
|
||||||
"# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n",
|
|
||||||
"# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n",
|
|
||||||
"# and convert column types manually.\n",
|
|
||||||
"example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\n",
|
|
||||||
"dflow = dprep.auto_read_file(example_data).skip(1) # Remove the header row.\n",
|
|
||||||
"dflow.get_profile()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# As `Primary Type` is our y data, we need to drop the values those are null in this column.\n",
|
|
||||||
"dflow = dflow.drop_nulls('Primary Type')\n",
|
|
||||||
"dflow.head(5)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Review the Data Preparation Result\n",
|
|
||||||
"\n",
|
|
||||||
"You can peek the result of a Dataflow at any range using `skip(i)` and `head(j)`. Doing so evaluates only `j` records for all the steps in the Dataflow, which makes it fast even against large datasets.\n",
|
|
||||||
"\n",
|
|
||||||
"`Dataflow` objects are immutable and are composed of a list of data preparation steps. A `Dataflow` object can be branched at any point for further usage."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X = dflow.drop_columns(columns=['Primary Type', 'FBI Code'])\n",
|
|
||||||
"y = dflow.keep_columns(columns=['Primary Type'], validate_column_exists=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"This creates a general AutoML settings object applicable for both local and remote runs."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_settings = {\n",
|
|
||||||
" \"iteration_timeout_minutes\" : 10,\n",
|
|
||||||
" \"iterations\" : 2,\n",
|
|
||||||
" \"primary_metric\" : 'AUC_weighted',\n",
|
|
||||||
" \"preprocess\" : True,\n",
|
|
||||||
" \"verbosity\" : logging.INFO\n",
|
|
||||||
"}"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Pass Data with `Dataflow` Objects\n",
|
|
||||||
"\n",
|
|
||||||
"The `Dataflow` objects captured above can be passed to the `submit` method for a local run. AutoML will retrieve the results from the `Dataflow` for model training."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" X = X,\n",
|
|
||||||
" y = y,\n",
|
|
||||||
" **automl_settings)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(local_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
" \n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model that has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the first iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 0\n",
|
|
||||||
"best_run, fitted_model = local_run.get_output(iteration = iteration)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data\n",
|
|
||||||
"For the test data, it should have the same preparation step as the train data. Otherwise it might get failed at the preprocessing step."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"dflow_test = dprep.auto_read_file(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv').skip(1)\n",
|
|
||||||
"dflow_test = dflow_test.drop_nulls('Primary Type')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Testing Our Best Fitted Model\n",
|
|
||||||
"We will use confusion matrix to see how our model works."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from pandas_ml import ConfusionMatrix\n",
|
|
||||||
"\n",
|
|
||||||
"y_test = dflow_test.keep_columns(columns=['Primary Type']).to_pandas_dataframe()\n",
|
|
||||||
"X_test = dflow_test.drop_columns(columns=['Primary Type', 'FBI Code']).to_pandas_dataframe()\n",
|
|
||||||
"\n",
|
|
||||||
"ypred = fitted_model.predict(X_test)\n",
|
|
||||||
"\n",
|
|
||||||
"cm = ConfusionMatrix(y_test['Primary Type'], ypred)\n",
|
|
||||||
"\n",
|
|
||||||
"print(cm)\n",
|
|
||||||
"\n",
|
|
||||||
"cm.plot()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.5"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Experimental Notebooks for Automated ML
|
||||||
|
Notebooks listed in this folder are leveraging experimental features. Namespaces or function signitures may change in future SDK releases. The notebooks published here will reflect the latest supported APIs. All of these notebooks can run on a client-only installation of the Automated ML SDK.
|
||||||
|
The client only installation doesn't contain any of the machine learning libraries, such as scikit-learn, xgboost, or tensorflow, making it much faster to install and is less likely to conflict with any packages in an existing environment. However, since the ML libraries are not available locally, models cannot be downloaded and loaded directly in the client. To replace the functionality of having models locally, these notebooks also demonstrate the ModelProxy feature which will allow you to submit a predict/forecast to the training environment.
|
||||||
|
|
||||||
|
<a name="localconda"></a>
|
||||||
|
## Setup using a Local Conda environment
|
||||||
|
|
||||||
|
To run these notebook on your own notebook server, use these installation instructions.
|
||||||
|
The instructions below will install everything you need and then start a Jupyter notebook.
|
||||||
|
If you would like to use a lighter-weight version of the client that does not install all of the machine learning libraries locally, you can leverage the [experimental notebooks.](experimental/README.md)
|
||||||
|
|
||||||
|
### 1. Install mini-conda from [here](https://conda.io/miniconda.html), choose 64-bit Python 3.7 or higher.
|
||||||
|
- **Note**: if you already have conda installed, you can keep using it but it should be version 4.4.10 or later (as shown by: conda -V). If you have a previous version installed, you can update it using the command: conda update conda.
|
||||||
|
There's no need to install mini-conda specifically.
|
||||||
|
|
||||||
|
### 2. Downloading the sample notebooks
|
||||||
|
- Download the sample notebooks from [GitHub](https://github.com/Azure/MachineLearningNotebooks) as zip and extract the contents to a local directory. The automated ML sample notebooks are in the "automated-machine-learning" folder.
|
||||||
|
|
||||||
|
### 3. Setup a new conda environment
|
||||||
|
The **automl_setup_thin_client** script creates a new conda environment, installs the necessary packages, configures the widget and starts a jupyter notebook. It takes the conda environment name as an optional parameter. The default conda environment name is azure_automl_experimental. The exact command depends on the operating system. See the specific sections below for Windows, Mac and Linux. It can take about 10 minutes to execute.
|
||||||
|
|
||||||
|
Packages installed by the **automl_setup** script:
|
||||||
|
<ul><li>python</li><li>nb_conda</li><li>matplotlib</li><li>numpy</li><li>cython</li><li>urllib3</li><li>pandas</li><li>azureml-sdk</li><li>azureml-widgets</li><li>pandas-ml</li></ul>
|
||||||
|
|
||||||
|
For more details refer to the [automl_env_thin_client.yml](./automl_env_thin_client.yml)
|
||||||
|
## Windows
|
||||||
|
Start an **Anaconda Prompt** window, cd to the **how-to-use-azureml/automated-machine-learning/experimental** folder where the sample notebooks were extracted and then run:
|
||||||
|
```
|
||||||
|
automl_setup_thin_client
|
||||||
|
```
|
||||||
|
## Mac
|
||||||
|
Install "Command line developer tools" if it is not already installed (you can use the command: `xcode-select --install`).
|
||||||
|
|
||||||
|
Start a Terminal windows, cd to the **how-to-use-azureml/automated-machine-learning/experimental** folder where the sample notebooks were extracted and then run:
|
||||||
|
|
||||||
|
```
|
||||||
|
bash automl_setup_thin_client_mac.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Linux
|
||||||
|
cd to the **how-to-use-azureml/automated-machine-learning/experimental** folder where the sample notebooks were extracted and then run:
|
||||||
|
|
||||||
|
```
|
||||||
|
bash automl_setup_thin_client_linux.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Running configuration.ipynb
|
||||||
|
- Before running any samples you next need to run the configuration notebook. Click on [configuration](../../configuration.ipynb) notebook
|
||||||
|
- Execute the cells in the notebook to Register Machine Learning Services Resource Provider and create a workspace. (*instructions in notebook*)
|
||||||
|
|
||||||
|
### 5. Running Samples
|
||||||
|
- Please make sure you use the Python [conda env:azure_automl_experimental] kernel when trying the sample Notebooks.
|
||||||
|
- Follow the instructions in the individual notebooks to explore various features in automated ML.
|
||||||
|
|
||||||
|
### 6. Starting jupyter notebook manually
|
||||||
|
To start your Jupyter notebook manually, use:
|
||||||
|
|
||||||
|
```
|
||||||
|
conda activate azure_automl
|
||||||
|
jupyter notebook
|
||||||
|
```
|
||||||
|
|
||||||
|
or on Mac or Linux:
|
||||||
|
|
||||||
|
```
|
||||||
|
source activate azure_automl
|
||||||
|
jupyter notebook
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<a name="samples"></a>
|
||||||
|
# Automated ML SDK Sample Notebooks
|
||||||
|
|
||||||
|
- [auto-ml-regression-model-proxy.ipynb](regression-model-proxy/auto-ml-regression-model-proxy.ipynb)
|
||||||
|
- Dataset: Hardware Performance Dataset
|
||||||
|
- Simple example of using automated ML for regression
|
||||||
|
- Uses azure compute for training
|
||||||
|
- Uses ModelProxy for submitting prediction to training environment on azure compute
|
||||||
|
|
||||||
|
<a name="documentation"></a>
|
||||||
|
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
||||||
|
|
||||||
|
<a name="pythoncommand"></a>
|
||||||
|
# Running using python command
|
||||||
|
Jupyter notebook provides a File / Download as / Python (.py) option for saving the notebook as a Python file.
|
||||||
|
You can then run this file using the python command.
|
||||||
|
However, on Windows the file needs to be modified before it can be run.
|
||||||
|
The following condition must be added to the main code in the file:
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
The main code of the file must be indented so that it is under this condition.
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
@echo off
|
||||||
|
set conda_env_name=%1
|
||||||
|
set automl_env_file=%2
|
||||||
|
set options=%3
|
||||||
|
set PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
|
||||||
|
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl_experimental"
|
||||||
|
IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml"
|
||||||
|
|
||||||
|
IF NOT EXIST %automl_env_file% GOTO YmlMissing
|
||||||
|
|
||||||
|
IF "%CONDA_EXE%"=="" GOTO CondaMissing
|
||||||
|
|
||||||
|
call conda activate %conda_env_name% 2>nul:
|
||||||
|
|
||||||
|
if not errorlevel 1 (
|
||||||
|
echo Upgrading existing conda environment %conda_env_name%
|
||||||
|
call pip uninstall azureml-train-automl -y -q
|
||||||
|
call conda env update --name %conda_env_name% --file %automl_env_file%
|
||||||
|
if errorlevel 1 goto ErrorExit
|
||||||
|
) else (
|
||||||
|
call conda env create -f %automl_env_file% -n %conda_env_name%
|
||||||
|
)
|
||||||
|
|
||||||
|
call conda activate %conda_env_name% 2>nul:
|
||||||
|
if errorlevel 1 goto ErrorExit
|
||||||
|
|
||||||
|
call python -m ipykernel install --user --name %conda_env_name% --display-name "Python (%conda_env_name%)"
|
||||||
|
|
||||||
|
REM azureml.widgets is now installed as part of the pip install under the conda env.
|
||||||
|
REM Removing the old user install so that the notebooks will use the latest widget.
|
||||||
|
call jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo.
|
||||||
|
echo ***************************************
|
||||||
|
echo * AutoML setup completed successfully *
|
||||||
|
echo ***************************************
|
||||||
|
IF NOT "%options%"=="nolaunch" (
|
||||||
|
echo.
|
||||||
|
echo Starting jupyter notebook - please run the configuration notebook
|
||||||
|
echo.
|
||||||
|
jupyter notebook --log-level=50 --notebook-dir='..\..'
|
||||||
|
)
|
||||||
|
|
||||||
|
goto End
|
||||||
|
|
||||||
|
:CondaMissing
|
||||||
|
echo Please run this script from an Anaconda Prompt window.
|
||||||
|
echo You can start an Anaconda Prompt window by
|
||||||
|
echo typing Anaconda Prompt on the Start menu.
|
||||||
|
echo If you don't see the Anaconda Prompt app, install Miniconda.
|
||||||
|
echo If you are running an older version of Miniconda or Anaconda,
|
||||||
|
echo you can upgrade using the command: conda update conda
|
||||||
|
goto End
|
||||||
|
|
||||||
|
:YmlMissing
|
||||||
|
echo File %automl_env_file% not found.
|
||||||
|
|
||||||
|
:ErrorExit
|
||||||
|
echo Install failed
|
||||||
|
|
||||||
|
:End
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
CONDA_ENV_NAME=$1
|
||||||
|
AUTOML_ENV_FILE=$2
|
||||||
|
OPTIONS=$3
|
||||||
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
|
||||||
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
|
then
|
||||||
|
CONDA_ENV_NAME="azure_automl_experimental"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$AUTOML_ENV_FILE" == "" ]
|
||||||
|
then
|
||||||
|
AUTOML_ENV_FILE="automl_env.yml"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $AUTOML_ENV_FILE ]; then
|
||||||
|
echo "File $AUTOML_ENV_FILE not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
|
then
|
||||||
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
|
pip uninstall azureml-train-automl -y -q
|
||||||
|
conda env update --name $CONDA_ENV_NAME --file $AUTOML_ENV_FILE &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
|
else
|
||||||
|
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
||||||
|
source activate $CONDA_ENV_NAME &&
|
||||||
|
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets &&
|
||||||
|
echo "" &&
|
||||||
|
echo "" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
echo "* AutoML setup completed successfully *" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
if [ "$OPTIONS" != "nolaunch" ]
|
||||||
|
then
|
||||||
|
echo "" &&
|
||||||
|
echo "Starting jupyter notebook - please run the configuration notebook" &&
|
||||||
|
echo "" &&
|
||||||
|
jupyter notebook --log-level=50 --notebook-dir '../..'
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $? -gt 0 ]
|
||||||
|
then
|
||||||
|
echo "Installation failed"
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
CONDA_ENV_NAME=$1
|
||||||
|
AUTOML_ENV_FILE=$2
|
||||||
|
OPTIONS=$3
|
||||||
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
|
||||||
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
|
then
|
||||||
|
CONDA_ENV_NAME="azure_automl_experimental"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$AUTOML_ENV_FILE" == "" ]
|
||||||
|
then
|
||||||
|
AUTOML_ENV_FILE="automl_env.yml"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $AUTOML_ENV_FILE ]; then
|
||||||
|
echo "File $AUTOML_ENV_FILE not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
|
then
|
||||||
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
|
pip uninstall azureml-train-automl -y -q
|
||||||
|
conda env update --name $CONDA_ENV_NAME --file $AUTOML_ENV_FILE &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
|
else
|
||||||
|
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
||||||
|
source activate $CONDA_ENV_NAME &&
|
||||||
|
conda install lightgbm -c conda-forge -y &&
|
||||||
|
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets &&
|
||||||
|
echo "" &&
|
||||||
|
echo "" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
echo "* AutoML setup completed successfully *" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
if [ "$OPTIONS" != "nolaunch" ]
|
||||||
|
then
|
||||||
|
echo "" &&
|
||||||
|
echo "Starting jupyter notebook - please run the configuration notebook" &&
|
||||||
|
echo "" &&
|
||||||
|
jupyter notebook --log-level=50 --notebook-dir '../..'
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $? -gt 0 ]
|
||||||
|
then
|
||||||
|
echo "Installation failed"
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
name: azure_automl_experimental
|
||||||
|
dependencies:
|
||||||
|
# The python interpreter version.
|
||||||
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip<=19.3.1
|
||||||
|
- python>=3.5.2,<3.8
|
||||||
|
- nb_conda
|
||||||
|
- matplotlib==2.1.0
|
||||||
|
- numpy~=1.18.0
|
||||||
|
- cython
|
||||||
|
- urllib3<1.24
|
||||||
|
- scikit-learn==0.22.1
|
||||||
|
- pandas==0.25.1
|
||||||
|
|
||||||
|
- pip:
|
||||||
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
|
- azureml-defaults
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-widgets
|
||||||
|
- azureml-explain-model
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
name: azure_automl_experimental
|
||||||
|
dependencies:
|
||||||
|
# The python interpreter version.
|
||||||
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip<=19.3.1
|
||||||
|
- nomkl
|
||||||
|
- python>=3.5.2,<3.8
|
||||||
|
- nb_conda
|
||||||
|
- matplotlib==2.1.0
|
||||||
|
- numpy~=1.18.0
|
||||||
|
- cython
|
||||||
|
- urllib3<1.24
|
||||||
|
- scikit-learn==0.22.1
|
||||||
|
- pandas==0.25.1
|
||||||
|
|
||||||
|
- pip:
|
||||||
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
|
- azureml-defaults
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-widgets
|
||||||
|
- azureml-explain-model
|
||||||
@@ -0,0 +1,481 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Regression with Aml Compute**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Data](#Data)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"In this example we use an experimental feature, Model Proxy, to do a predict on the best generated model without downloading the model locally. The prediction will happen on same compute and environment that was used to train the model. This feature is currently in the experimental state, which means that the API is prone to changing, please make sure to run on the latest version of this notebook if you face any issues.\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"3. Train the model using remote compute.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Test the best fitted model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
" \n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for the experiment.\n",
|
||||||
|
"experiment_name = 'automl-regression-model-proxy'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Run History Name'] = experiment_name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Using AmlCompute\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"cpu_cluster_name = \"reg-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Data\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"Load the hardware dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv\"\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
|
||||||
|
"\n",
|
||||||
|
"# Split the dataset into train and test datasets\n",
|
||||||
|
"train_data, test_data = dataset.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"\n",
|
||||||
|
"label = \"ERP\"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification, regression or forecasting|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
||||||
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
|
"|**training_data**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
||||||
|
"|**label_column_name**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
||||||
|
"\n",
|
||||||
|
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"automlconfig-remarks-sample"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"primary_metric\": 'r2_score',\n",
|
||||||
|
" \"enable_early_stopping\": True, \n",
|
||||||
|
" \"experiment_timeout_hours\": 0.3, #for real scenarios we reccommend a timeout of at least one hour \n",
|
||||||
|
" \"max_concurrent_iterations\": 4,\n",
|
||||||
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'regression',\n",
|
||||||
|
" compute_target = compute_target,\n",
|
||||||
|
" training_data = train_data,\n",
|
||||||
|
" label_column_name = label,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Call the `submit` method on the experiment object and pass the run configuration. Execution of remote runs is asynchronous. Depending on the data and the number of iterations this can run for a while. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# If you need to retrieve a run that already started, use the following code\n",
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Widget for Monitoring Runs\n",
|
||||||
|
"\n",
|
||||||
|
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
||||||
|
"\n",
|
||||||
|
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.widgets import RunDetails\n",
|
||||||
|
"RunDetails(remote_run).show() "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve the Best Child Run\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_best_child` method returns the best run. Overloads on `get_best_child` allow you to retrieve the best run for *any* logged metric."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run = remote_run.get_best_child()\n",
|
||||||
|
"print(best_run)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Best Child Run Based on Any Other Metric\n",
|
||||||
|
"Show the run and the model that has the smallest `root_mean_squared_error` value (which turned out to be the same as the one with largest `spearman_correlation` value):"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"lookup_metric = \"root_mean_squared_error\"\n",
|
||||||
|
"best_run = remote_run.get_best_child(metric = lookup_metric)\n",
|
||||||
|
"print(best_run)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# preview the first 3 rows of the dataset\n",
|
||||||
|
"\n",
|
||||||
|
"test_data = test_data.to_pandas_dataframe()\n",
|
||||||
|
"y_test = test_data['ERP'].fillna(0)\n",
|
||||||
|
"test_data = test_data.drop('ERP', 1)\n",
|
||||||
|
"test_data = test_data.fillna(0)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"train_data = train_data.to_pandas_dataframe()\n",
|
||||||
|
"y_train = train_data['ERP'].fillna(0)\n",
|
||||||
|
"train_data = train_data.drop('ERP', 1)\n",
|
||||||
|
"train_data = train_data.fillna(0)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Creating ModelProxy for submitting prediction runs to the training environment.\n",
|
||||||
|
"We will create a ModelProxy for the best child run, which will allow us to submit a run that does the prediction in the training environment. Unlike the local client, which can have different versions of some libraries, the training environment will have all the compatible libraries for the model already."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.model_proxy import ModelProxy\n",
|
||||||
|
"best_model_proxy = ModelProxy(best_run)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_pred_train = best_model_proxy.predict(train_data).to_pandas_dataframe().values.flatten()\n",
|
||||||
|
"y_residual_train = y_train - y_pred_train\n",
|
||||||
|
"\n",
|
||||||
|
"y_pred_test = best_model_proxy.predict(test_data).to_pandas_dataframe().values.flatten()\n",
|
||||||
|
"y_residual_test = y_test - y_pred_test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"from sklearn.metrics import mean_squared_error, r2_score\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up a multi-plot chart.\n",
|
||||||
|
"f, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})\n",
|
||||||
|
"f.suptitle('Regression Residual Values', fontsize = 18)\n",
|
||||||
|
"f.set_figheight(6)\n",
|
||||||
|
"f.set_figwidth(16)\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of training set.\n",
|
||||||
|
"a0.axis([0, 360, -100, 100])\n",
|
||||||
|
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
|
||||||
|
"a0.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
||||||
|
"a0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\n",
|
||||||
|
"a0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)),fontsize = 12)\n",
|
||||||
|
"a0.set_xlabel('Training samples', fontsize = 12)\n",
|
||||||
|
"a0.set_ylabel('Residual Values', fontsize = 12)\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of test set.\n",
|
||||||
|
"a1.axis([0, 90, -100, 100])\n",
|
||||||
|
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
|
||||||
|
"a1.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
||||||
|
"a1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\n",
|
||||||
|
"a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)),fontsize = 12)\n",
|
||||||
|
"a1.set_xlabel('Test samples', fontsize = 12)\n",
|
||||||
|
"a1.set_yticklabels([])\n",
|
||||||
|
"\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"test_pred = plt.scatter(y_test, y_pred_test, color='')\n",
|
||||||
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "rakellam"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-regression-model-proxy
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -1,349 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Exploring Previous Runs**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Explore](#Explore)\n",
|
|
||||||
"1. [Download](#Download)\n",
|
|
||||||
"1. [Register](#Register)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we present some examples on navigating previously executed runs. We also show how you can download a fitted model for any previous run.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. List all experiments in a workspace.\n",
|
|
||||||
"2. List all AutoML runs in an experiment.\n",
|
|
||||||
"3. Get details for an AutoML run, including settings, run widget, and all metrics.\n",
|
|
||||||
"4. Download a fitted pipeline for any iteration."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"import json\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Explore"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### List Experiments"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"experiment_list = Experiment.list(workspace=ws)\n",
|
|
||||||
"\n",
|
|
||||||
"summary_df = pd.DataFrame(index = ['No of Runs'])\n",
|
|
||||||
"for experiment in experiment_list:\n",
|
|
||||||
" automl_runs = list(experiment.get_runs(type='automl'))\n",
|
|
||||||
" summary_df[experiment.name] = [len(automl_runs)]\n",
|
|
||||||
" \n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"summary_df.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### List runs for an experiment\n",
|
|
||||||
"Set `experiment_name` to any experiment name from the result of the Experiment.list cell to load the AutoML runs."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"experiment_name = 'automl-local-classification' # Replace this with any project name from previous cell.\n",
|
|
||||||
"\n",
|
|
||||||
"proj = ws.experiments[experiment_name]\n",
|
|
||||||
"summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name'])\n",
|
|
||||||
"automl_runs = list(proj.get_runs(type='automl'))\n",
|
|
||||||
"automl_runs_project = []\n",
|
|
||||||
"for run in automl_runs:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" tags = run.get_tags()\n",
|
|
||||||
" amlsettings = json.loads(properties['AMLSettingsJsonString'])\n",
|
|
||||||
" if 'iterations' in tags:\n",
|
|
||||||
" iterations = tags['iterations']\n",
|
|
||||||
" else:\n",
|
|
||||||
" iterations = properties['num_iterations']\n",
|
|
||||||
" summary_df[run.id] = [amlsettings['task_type'], run.get_details()['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name']]\n",
|
|
||||||
" if run.get_details()['status'] == 'Completed':\n",
|
|
||||||
" automl_runs_project.append(run.id)\n",
|
|
||||||
" \n",
|
|
||||||
"from IPython.display import HTML\n",
|
|
||||||
"projname_html = HTML(\"<h3>{}</h3>\".format(proj.name))\n",
|
|
||||||
"\n",
|
|
||||||
"from IPython.display import display\n",
|
|
||||||
"display(projname_html)\n",
|
|
||||||
"display(summary_df.T)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Get details for a run\n",
|
|
||||||
"\n",
|
|
||||||
"Copy the project name and run id from the previous cell output to find more details on a particular run."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"run_id = automl_runs_project[0] # Replace with your own run_id from above run ids\n",
|
|
||||||
"assert (run_id in summary_df.keys()), \"Run id not found! Please set run id to a value from above run ids\"\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"ml_run = AutoMLRun(experiment = experiment, run_id = run_id)\n",
|
|
||||||
"\n",
|
|
||||||
"summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name', 'Start Time', 'End Time'])\n",
|
|
||||||
"properties = ml_run.get_properties()\n",
|
|
||||||
"tags = ml_run.get_tags()\n",
|
|
||||||
"status = ml_run.get_details()\n",
|
|
||||||
"amlsettings = json.loads(properties['AMLSettingsJsonString'])\n",
|
|
||||||
"if 'iterations' in tags:\n",
|
|
||||||
" iterations = tags['iterations']\n",
|
|
||||||
"else:\n",
|
|
||||||
" iterations = properties['num_iterations']\n",
|
|
||||||
"start_time = None\n",
|
|
||||||
"if 'startTimeUtc' in status:\n",
|
|
||||||
" start_time = status['startTimeUtc']\n",
|
|
||||||
"end_time = None\n",
|
|
||||||
"if 'endTimeUtc' in status:\n",
|
|
||||||
" end_time = status['endTimeUtc']\n",
|
|
||||||
"summary_df[ml_run.id] = [amlsettings['task_type'], status['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name'], start_time, end_time]\n",
|
|
||||||
"display(HTML('<h3>Runtime Details</h3>'))\n",
|
|
||||||
"display(summary_df)\n",
|
|
||||||
"\n",
|
|
||||||
"#settings_df = pd.DataFrame(data = amlsettings, index = [''])\n",
|
|
||||||
"display(HTML('<h3>AutoML Settings</h3>'))\n",
|
|
||||||
"display(amlsettings)\n",
|
|
||||||
"\n",
|
|
||||||
"display(HTML('<h3>Iterations</h3>'))\n",
|
|
||||||
"RunDetails(ml_run).show() \n",
|
|
||||||
"\n",
|
|
||||||
"children = list(ml_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"display(HTML('<h3>Metrics</h3>'))\n",
|
|
||||||
"display(rundata)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Download"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Download the Best Model for Any Given Metric"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"metric = 'AUC_weighted' # Replace with a metric name.\n",
|
|
||||||
"best_run, fitted_model = ml_run.get_output(metric = metric)\n",
|
|
||||||
"fitted_model"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Download the Model for Any Given Iteration"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 1 # Replace with an iteration number.\n",
|
|
||||||
"best_run, fitted_model = ml_run.get_output(iteration = iteration)\n",
|
|
||||||
"fitted_model"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Register"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Register fitted model for deployment\n",
|
|
||||||
"If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"description = 'AutoML Model'\n",
|
|
||||||
"tags = None\n",
|
|
||||||
"ml_run.register_model(description = description, tags = tags)\n",
|
|
||||||
"print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Register the Best Model for Any Given Metric"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"metric = 'AUC_weighted' # Replace with a metric name.\n",
|
|
||||||
"description = 'AutoML Model'\n",
|
|
||||||
"tags = None\n",
|
|
||||||
"ml_run.register_model(description = description, tags = tags, metric = metric)\n",
|
|
||||||
"print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Register the Model for Any Given Iteration"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 1 # Replace with an iteration number.\n",
|
|
||||||
"description = 'AutoML Model'\n",
|
|
||||||
"tags = None\n",
|
|
||||||
"ml_run.register_model(description = description, tags = tags, iteration = iteration)\n",
|
|
||||||
"print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
DATE,grain,BeerProduction
|
||||||
|
2017-01-01,grain,9049
|
||||||
|
2017-02-01,grain,10458
|
||||||
|
2017-03-01,grain,12489
|
||||||
|
2017-04-01,grain,11499
|
||||||
|
2017-05-01,grain,13553
|
||||||
|
2017-06-01,grain,14740
|
||||||
|
2017-07-01,grain,11424
|
||||||
|
2017-08-01,grain,13412
|
||||||
|
2017-09-01,grain,11917
|
||||||
|
2017-10-01,grain,12721
|
||||||
|
2017-11-01,grain,13272
|
||||||
|
2017-12-01,grain,14278
|
||||||
|
2018-01-01,grain,9572
|
||||||
|
2018-02-01,grain,10423
|
||||||
|
2018-03-01,grain,12667
|
||||||
|
2018-04-01,grain,11904
|
||||||
|
2018-05-01,grain,14120
|
||||||
|
2018-06-01,grain,14565
|
||||||
|
2018-07-01,grain,12622
|
||||||
|
@@ -0,0 +1,301 @@
|
|||||||
|
DATE,grain,BeerProduction
|
||||||
|
1992-01-01,grain,3459
|
||||||
|
1992-02-01,grain,3458
|
||||||
|
1992-03-01,grain,4002
|
||||||
|
1992-04-01,grain,4564
|
||||||
|
1992-05-01,grain,4221
|
||||||
|
1992-06-01,grain,4529
|
||||||
|
1992-07-01,grain,4466
|
||||||
|
1992-08-01,grain,4137
|
||||||
|
1992-09-01,grain,4126
|
||||||
|
1992-10-01,grain,4259
|
||||||
|
1992-11-01,grain,4240
|
||||||
|
1992-12-01,grain,4936
|
||||||
|
1993-01-01,grain,3031
|
||||||
|
1993-02-01,grain,3261
|
||||||
|
1993-03-01,grain,4160
|
||||||
|
1993-04-01,grain,4377
|
||||||
|
1993-05-01,grain,4307
|
||||||
|
1993-06-01,grain,4696
|
||||||
|
1993-07-01,grain,4458
|
||||||
|
1993-08-01,grain,4457
|
||||||
|
1993-09-01,grain,4364
|
||||||
|
1993-10-01,grain,4236
|
||||||
|
1993-11-01,grain,4500
|
||||||
|
1993-12-01,grain,4974
|
||||||
|
1994-01-01,grain,3075
|
||||||
|
1994-02-01,grain,3377
|
||||||
|
1994-03-01,grain,4443
|
||||||
|
1994-04-01,grain,4261
|
||||||
|
1994-05-01,grain,4460
|
||||||
|
1994-06-01,grain,4985
|
||||||
|
1994-07-01,grain,4324
|
||||||
|
1994-08-01,grain,4719
|
||||||
|
1994-09-01,grain,4374
|
||||||
|
1994-10-01,grain,4248
|
||||||
|
1994-11-01,grain,4784
|
||||||
|
1994-12-01,grain,4971
|
||||||
|
1995-01-01,grain,3370
|
||||||
|
1995-02-01,grain,3484
|
||||||
|
1995-03-01,grain,4269
|
||||||
|
1995-04-01,grain,3994
|
||||||
|
1995-05-01,grain,4715
|
||||||
|
1995-06-01,grain,4974
|
||||||
|
1995-07-01,grain,4223
|
||||||
|
1995-08-01,grain,5000
|
||||||
|
1995-09-01,grain,4235
|
||||||
|
1995-10-01,grain,4554
|
||||||
|
1995-11-01,grain,4851
|
||||||
|
1995-12-01,grain,4826
|
||||||
|
1996-01-01,grain,3699
|
||||||
|
1996-02-01,grain,3983
|
||||||
|
1996-03-01,grain,4262
|
||||||
|
1996-04-01,grain,4619
|
||||||
|
1996-05-01,grain,5219
|
||||||
|
1996-06-01,grain,4836
|
||||||
|
1996-07-01,grain,4941
|
||||||
|
1996-08-01,grain,5062
|
||||||
|
1996-09-01,grain,4365
|
||||||
|
1996-10-01,grain,5012
|
||||||
|
1996-11-01,grain,4850
|
||||||
|
1996-12-01,grain,5097
|
||||||
|
1997-01-01,grain,3758
|
||||||
|
1997-02-01,grain,3825
|
||||||
|
1997-03-01,grain,4454
|
||||||
|
1997-04-01,grain,4635
|
||||||
|
1997-05-01,grain,5210
|
||||||
|
1997-06-01,grain,5057
|
||||||
|
1997-07-01,grain,5231
|
||||||
|
1997-08-01,grain,5034
|
||||||
|
1997-09-01,grain,4970
|
||||||
|
1997-10-01,grain,5342
|
||||||
|
1997-11-01,grain,4831
|
||||||
|
1997-12-01,grain,5965
|
||||||
|
1998-01-01,grain,3796
|
||||||
|
1998-02-01,grain,4019
|
||||||
|
1998-03-01,grain,4898
|
||||||
|
1998-04-01,grain,5090
|
||||||
|
1998-05-01,grain,5237
|
||||||
|
1998-06-01,grain,5447
|
||||||
|
1998-07-01,grain,5435
|
||||||
|
1998-08-01,grain,5107
|
||||||
|
1998-09-01,grain,5515
|
||||||
|
1998-10-01,grain,5583
|
||||||
|
1998-11-01,grain,5346
|
||||||
|
1998-12-01,grain,6286
|
||||||
|
1999-01-01,grain,4032
|
||||||
|
1999-02-01,grain,4435
|
||||||
|
1999-03-01,grain,5479
|
||||||
|
1999-04-01,grain,5483
|
||||||
|
1999-05-01,grain,5587
|
||||||
|
1999-06-01,grain,6176
|
||||||
|
1999-07-01,grain,5621
|
||||||
|
1999-08-01,grain,5889
|
||||||
|
1999-09-01,grain,5828
|
||||||
|
1999-10-01,grain,5849
|
||||||
|
1999-11-01,grain,6180
|
||||||
|
1999-12-01,grain,6771
|
||||||
|
2000-01-01,grain,4243
|
||||||
|
2000-02-01,grain,4952
|
||||||
|
2000-03-01,grain,6008
|
||||||
|
2000-04-01,grain,5353
|
||||||
|
2000-05-01,grain,6435
|
||||||
|
2000-06-01,grain,6673
|
||||||
|
2000-07-01,grain,5636
|
||||||
|
2000-08-01,grain,6630
|
||||||
|
2000-09-01,grain,5887
|
||||||
|
2000-10-01,grain,6322
|
||||||
|
2000-11-01,grain,6520
|
||||||
|
2000-12-01,grain,6678
|
||||||
|
2001-01-01,grain,5082
|
||||||
|
2001-02-01,grain,5216
|
||||||
|
2001-03-01,grain,5893
|
||||||
|
2001-04-01,grain,5894
|
||||||
|
2001-05-01,grain,6799
|
||||||
|
2001-06-01,grain,6667
|
||||||
|
2001-07-01,grain,6374
|
||||||
|
2001-08-01,grain,6840
|
||||||
|
2001-09-01,grain,5575
|
||||||
|
2001-10-01,grain,6545
|
||||||
|
2001-11-01,grain,6789
|
||||||
|
2001-12-01,grain,7180
|
||||||
|
2002-01-01,grain,5117
|
||||||
|
2002-02-01,grain,5442
|
||||||
|
2002-03-01,grain,6337
|
||||||
|
2002-04-01,grain,6525
|
||||||
|
2002-05-01,grain,7216
|
||||||
|
2002-06-01,grain,6761
|
||||||
|
2002-07-01,grain,6958
|
||||||
|
2002-08-01,grain,7070
|
||||||
|
2002-09-01,grain,6148
|
||||||
|
2002-10-01,grain,6924
|
||||||
|
2002-11-01,grain,6716
|
||||||
|
2002-12-01,grain,7975
|
||||||
|
2003-01-01,grain,5326
|
||||||
|
2003-02-01,grain,5609
|
||||||
|
2003-03-01,grain,6414
|
||||||
|
2003-04-01,grain,6741
|
||||||
|
2003-05-01,grain,7144
|
||||||
|
2003-06-01,grain,7133
|
||||||
|
2003-07-01,grain,7568
|
||||||
|
2003-08-01,grain,7266
|
||||||
|
2003-09-01,grain,6634
|
||||||
|
2003-10-01,grain,7626
|
||||||
|
2003-11-01,grain,6843
|
||||||
|
2003-12-01,grain,8540
|
||||||
|
2004-01-01,grain,5629
|
||||||
|
2004-02-01,grain,5898
|
||||||
|
2004-03-01,grain,7045
|
||||||
|
2004-04-01,grain,7094
|
||||||
|
2004-05-01,grain,7333
|
||||||
|
2004-06-01,grain,7918
|
||||||
|
2004-07-01,grain,7289
|
||||||
|
2004-08-01,grain,7396
|
||||||
|
2004-09-01,grain,7259
|
||||||
|
2004-10-01,grain,7268
|
||||||
|
2004-11-01,grain,7731
|
||||||
|
2004-12-01,grain,9058
|
||||||
|
2005-01-01,grain,5557
|
||||||
|
2005-02-01,grain,6237
|
||||||
|
2005-03-01,grain,7723
|
||||||
|
2005-04-01,grain,7262
|
||||||
|
2005-05-01,grain,8241
|
||||||
|
2005-06-01,grain,8757
|
||||||
|
2005-07-01,grain,7352
|
||||||
|
2005-08-01,grain,8496
|
||||||
|
2005-09-01,grain,7741
|
||||||
|
2005-10-01,grain,7710
|
||||||
|
2005-11-01,grain,8247
|
||||||
|
2005-12-01,grain,8902
|
||||||
|
2006-01-01,grain,6066
|
||||||
|
2006-02-01,grain,6590
|
||||||
|
2006-03-01,grain,7923
|
||||||
|
2006-04-01,grain,7335
|
||||||
|
2006-05-01,grain,8843
|
||||||
|
2006-06-01,grain,9327
|
||||||
|
2006-07-01,grain,7792
|
||||||
|
2006-08-01,grain,9156
|
||||||
|
2006-09-01,grain,8037
|
||||||
|
2006-10-01,grain,8640
|
||||||
|
2006-11-01,grain,9128
|
||||||
|
2006-12-01,grain,9545
|
||||||
|
2007-01-01,grain,6627
|
||||||
|
2007-02-01,grain,6743
|
||||||
|
2007-03-01,grain,8195
|
||||||
|
2007-04-01,grain,7828
|
||||||
|
2007-05-01,grain,9570
|
||||||
|
2007-06-01,grain,9484
|
||||||
|
2007-07-01,grain,8608
|
||||||
|
2007-08-01,grain,9543
|
||||||
|
2007-09-01,grain,8123
|
||||||
|
2007-10-01,grain,9649
|
||||||
|
2007-11-01,grain,9390
|
||||||
|
2007-12-01,grain,10065
|
||||||
|
2008-01-01,grain,7093
|
||||||
|
2008-02-01,grain,7483
|
||||||
|
2008-03-01,grain,8365
|
||||||
|
2008-04-01,grain,8895
|
||||||
|
2008-05-01,grain,9794
|
||||||
|
2008-06-01,grain,9977
|
||||||
|
2008-07-01,grain,9553
|
||||||
|
2008-08-01,grain,9375
|
||||||
|
2008-09-01,grain,9225
|
||||||
|
2008-10-01,grain,9948
|
||||||
|
2008-11-01,grain,8758
|
||||||
|
2008-12-01,grain,10839
|
||||||
|
2009-01-01,grain,7266
|
||||||
|
2009-02-01,grain,7578
|
||||||
|
2009-03-01,grain,8688
|
||||||
|
2009-04-01,grain,9162
|
||||||
|
2009-05-01,grain,9369
|
||||||
|
2009-06-01,grain,10167
|
||||||
|
2009-07-01,grain,9507
|
||||||
|
2009-08-01,grain,8923
|
||||||
|
2009-09-01,grain,9272
|
||||||
|
2009-10-01,grain,9075
|
||||||
|
2009-11-01,grain,8949
|
||||||
|
2009-12-01,grain,10843
|
||||||
|
2010-01-01,grain,6558
|
||||||
|
2010-02-01,grain,7481
|
||||||
|
2010-03-01,grain,9475
|
||||||
|
2010-04-01,grain,9424
|
||||||
|
2010-05-01,grain,9351
|
||||||
|
2010-06-01,grain,10552
|
||||||
|
2010-07-01,grain,9077
|
||||||
|
2010-08-01,grain,9273
|
||||||
|
2010-09-01,grain,9420
|
||||||
|
2010-10-01,grain,9413
|
||||||
|
2010-11-01,grain,9866
|
||||||
|
2010-12-01,grain,11455
|
||||||
|
2011-01-01,grain,6901
|
||||||
|
2011-02-01,grain,8014
|
||||||
|
2011-03-01,grain,9832
|
||||||
|
2011-04-01,grain,9281
|
||||||
|
2011-05-01,grain,9967
|
||||||
|
2011-06-01,grain,11344
|
||||||
|
2011-07-01,grain,9106
|
||||||
|
2011-08-01,grain,10469
|
||||||
|
2011-09-01,grain,10085
|
||||||
|
2011-10-01,grain,9612
|
||||||
|
2011-11-01,grain,10328
|
||||||
|
2011-12-01,grain,11483
|
||||||
|
2012-01-01,grain,7486
|
||||||
|
2012-02-01,grain,8641
|
||||||
|
2012-03-01,grain,9709
|
||||||
|
2012-04-01,grain,9423
|
||||||
|
2012-05-01,grain,11342
|
||||||
|
2012-06-01,grain,11274
|
||||||
|
2012-07-01,grain,9845
|
||||||
|
2012-08-01,grain,11163
|
||||||
|
2012-09-01,grain,9532
|
||||||
|
2012-10-01,grain,10754
|
||||||
|
2012-11-01,grain,10953
|
||||||
|
2012-12-01,grain,11922
|
||||||
|
2013-01-01,grain,8395
|
||||||
|
2013-02-01,grain,8888
|
||||||
|
2013-03-01,grain,10110
|
||||||
|
2013-04-01,grain,10493
|
||||||
|
2013-05-01,grain,12218
|
||||||
|
2013-06-01,grain,11385
|
||||||
|
2013-07-01,grain,11186
|
||||||
|
2013-08-01,grain,11462
|
||||||
|
2013-09-01,grain,10494
|
||||||
|
2013-10-01,grain,11540
|
||||||
|
2013-11-01,grain,11138
|
||||||
|
2013-12-01,grain,12709
|
||||||
|
2014-01-01,grain,8557
|
||||||
|
2014-02-01,grain,9059
|
||||||
|
2014-03-01,grain,10055
|
||||||
|
2014-04-01,grain,10977
|
||||||
|
2014-05-01,grain,11792
|
||||||
|
2014-06-01,grain,11904
|
||||||
|
2014-07-01,grain,10965
|
||||||
|
2014-08-01,grain,10981
|
||||||
|
2014-09-01,grain,10828
|
||||||
|
2014-10-01,grain,11817
|
||||||
|
2014-11-01,grain,10470
|
||||||
|
2014-12-01,grain,13310
|
||||||
|
2015-01-01,grain,8400
|
||||||
|
2015-02-01,grain,9062
|
||||||
|
2015-03-01,grain,10722
|
||||||
|
2015-04-01,grain,11107
|
||||||
|
2015-05-01,grain,11508
|
||||||
|
2015-06-01,grain,12904
|
||||||
|
2015-07-01,grain,11869
|
||||||
|
2015-08-01,grain,11224
|
||||||
|
2015-09-01,grain,12022
|
||||||
|
2015-10-01,grain,11983
|
||||||
|
2015-11-01,grain,11506
|
||||||
|
2015-12-01,grain,14183
|
||||||
|
2016-01-01,grain,8650
|
||||||
|
2016-02-01,grain,10323
|
||||||
|
2016-03-01,grain,12110
|
||||||
|
2016-04-01,grain,11424
|
||||||
|
2016-05-01,grain,12243
|
||||||
|
2016-06-01,grain,13686
|
||||||
|
2016-07-01,grain,10956
|
||||||
|
2016-08-01,grain,12706
|
||||||
|
2016-09-01,grain,12279
|
||||||
|
2016-10-01,grain,11914
|
||||||
|
2016-11-01,grain,13025
|
||||||
|
2016-12-01,grain,14431
|
||||||
|
@@ -0,0 +1,677 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"**Beer Production Forecasting**\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Data](#Data)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Evaluate](#Evaluate)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"This notebook demonstrates demand forecasting for Beer Production Dataset using AutoML.\n",
|
||||||
|
"\n",
|
||||||
|
"AutoML highlights here include using Deep Learning forecasts, Arima, Prophet, Remote Execution and Remote Inferencing, and working with the `forecast` function. Please also look at the additional forecasting notebooks, which document lagging, rolling windows, forecast quantiles, other ways to use the forecast function, and forecaster deployment.\n",
|
||||||
|
"\n",
|
||||||
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
|
"\n",
|
||||||
|
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)\n",
|
||||||
|
"\n",
|
||||||
|
"Notebook synopsis:\n",
|
||||||
|
"1. Creating an Experiment in an existing Workspace\n",
|
||||||
|
"2. Configuration and remote run of AutoML for a time-series model exploring Regression learners, Arima, Prophet and DNNs\n",
|
||||||
|
"4. Evaluating the fitted model using a rolling test "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import logging\n",
|
||||||
|
"import warnings\n",
|
||||||
|
"\n",
|
||||||
|
"from pandas.tseries.frequencies import to_offset\n",
|
||||||
|
"\n",
|
||||||
|
"# Squash warning messages for cleaner output in the notebook\n",
|
||||||
|
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
||||||
|
"\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
||||||
|
"from azureml.train.estimator import Estimator"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a name for the run history container in the workspace\n",
|
||||||
|
"experiment_name = 'beer-remote-cpu'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Run History Name'] = experiment_name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"### Using AmlCompute\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"cpu_cluster_name = \"beer-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## Data\n",
|
||||||
|
"Read Beer demand data from file, and preview data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Let's set up what we know about the dataset. \n",
|
||||||
|
"\n",
|
||||||
|
"**Target column** is what we want to forecast.\n",
|
||||||
|
"\n",
|
||||||
|
"**Time column** is the time axis along which to predict.\n",
|
||||||
|
"\n",
|
||||||
|
"**Time series identifier columns** are identified by values of the columns listed `time_series_id_column_names`, for example \"store\" and \"item\" if your data has multiple time series of sales, one series for each combination of store and item sold.\n",
|
||||||
|
"\n",
|
||||||
|
"This dataset has only one time series. Please see the [orange juice notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales) for an example of a multi-time series dataset."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"from pandas import DataFrame\n",
|
||||||
|
"from pandas import Grouper\n",
|
||||||
|
"from pandas import concat\n",
|
||||||
|
"from pandas.plotting import register_matplotlib_converters\n",
|
||||||
|
"\n",
|
||||||
|
"register_matplotlib_converters()\n",
|
||||||
|
"plt.figure(figsize=(20, 10))\n",
|
||||||
|
"plt.tight_layout()\n",
|
||||||
|
"\n",
|
||||||
|
"plt.subplot(2, 1, 1)\n",
|
||||||
|
"plt.title('Beer Production By Year')\n",
|
||||||
|
"df = pd.read_csv(\"Beer_no_valid_split_train.csv\", parse_dates=True, index_col= 'DATE').drop(columns='grain')\n",
|
||||||
|
"test_df = pd.read_csv(\"Beer_no_valid_split_test.csv\", parse_dates=True, index_col= 'DATE').drop(columns='grain')\n",
|
||||||
|
"plt.plot(df)\n",
|
||||||
|
"\n",
|
||||||
|
"plt.subplot(2, 1, 2)\n",
|
||||||
|
"plt.title('Beer Production By Month')\n",
|
||||||
|
"groups = df.groupby(df.index.month)\n",
|
||||||
|
"months = concat([DataFrame(x[1].values) for x in groups], axis=1)\n",
|
||||||
|
"months = DataFrame(months)\n",
|
||||||
|
"months.columns = range(1,13)\n",
|
||||||
|
"months.boxplot()\n",
|
||||||
|
"\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"target_column_name = 'BeerProduction'\n",
|
||||||
|
"time_column_name = 'DATE'\n",
|
||||||
|
"time_series_id_column_names = []\n",
|
||||||
|
"freq = 'M' #Monthly data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Split Training data into Train and Validation set and Upload to Datastores"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from helper import split_fraction_by_grain\n",
|
||||||
|
"from helper import split_full_for_forecasting\n",
|
||||||
|
"\n",
|
||||||
|
"train, valid = split_full_for_forecasting(df, time_column_name)\n",
|
||||||
|
"train.to_csv(\"train.csv\")\n",
|
||||||
|
"valid.to_csv(\"valid.csv\")\n",
|
||||||
|
"test_df.to_csv(\"test.csv\")\n",
|
||||||
|
"\n",
|
||||||
|
"datastore = ws.get_default_datastore()\n",
|
||||||
|
"datastore.upload_files(files = ['./train.csv'], target_path = 'beer-dataset/tabular/', overwrite = True,show_progress = True)\n",
|
||||||
|
"datastore.upload_files(files = ['./valid.csv'], target_path = 'beer-dataset/tabular/', overwrite = True,show_progress = True)\n",
|
||||||
|
"datastore.upload_files(files = ['./test.csv'], target_path = 'beer-dataset/tabular/', overwrite = True,show_progress = True)\n",
|
||||||
|
"\n",
|
||||||
|
"from azureml.core import Dataset\n",
|
||||||
|
"train_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/train.csv')])\n",
|
||||||
|
"valid_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/valid.csv')])\n",
|
||||||
|
"test_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/test.csv')])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"### Setting forecaster maximum horizon \n",
|
||||||
|
"\n",
|
||||||
|
"The forecast horizon is the number of periods into the future that the model should predict. Here, we set the horizon to 12 periods (i.e. 12 months). Notice that this is much shorter than the number of months in the test set; we will need to use a rolling test to evaluate the performance on the whole test set. For more discussion of forecast horizons and guiding principles for setting them, please see the [energy demand notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand). "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"forecast_horizon = 12"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|forecasting|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>\n",
|
||||||
|
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
||||||
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
|
"|**enable_dnn**|Enable Forecasting DNNs|\n",
|
||||||
|
"\n",
|
||||||
|
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
|
" time_column_name=time_column_name, forecast_horizon=forecast_horizon\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task='forecasting', \n",
|
||||||
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
|
" experiment_timeout_hours = 1,\n",
|
||||||
|
" training_data=train_dataset,\n",
|
||||||
|
" label_column_name=target_column_name,\n",
|
||||||
|
" validation_data=valid_dataset, \n",
|
||||||
|
" verbosity=logging.INFO,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" max_concurrent_iterations=4,\n",
|
||||||
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" enable_dnn=True,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"We will now run the experiment, starting with 10 iterations of model search. The experiment can be continued for more iterations if more accurate results are required. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output= False)\n",
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# If you need to retrieve a run that already started, use the following code\n",
|
||||||
|
"# from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"# remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Displaying the run objects gives you links to the visual tools in the Azure Portal. Go try them!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve the Best Model for Each Algorithm\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The get_output method on automl_classifier returns the best run and the fitted model for the last fit invocation. There are overloads on get_output that allow you to retrieve the best run and fitted model for any logged metric or a particular iteration."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from helper import get_result_df\n",
|
||||||
|
"summary_df = get_result_df(remote_run)\n",
|
||||||
|
"summary_df"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.run import Run\n",
|
||||||
|
"from azureml.widgets import RunDetails\n",
|
||||||
|
"forecast_model = 'TCNForecaster'\n",
|
||||||
|
"if not forecast_model in summary_df['run_id']:\n",
|
||||||
|
" forecast_model = 'ForecastTCN'\n",
|
||||||
|
" \n",
|
||||||
|
"best_dnn_run_id = summary_df['run_id'][forecast_model]\n",
|
||||||
|
"best_dnn_run = Run(experiment, best_dnn_run_id)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_dnn_run.parent\n",
|
||||||
|
"RunDetails(best_dnn_run.parent).show() "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_dnn_run\n",
|
||||||
|
"RunDetails(best_dnn_run).show() "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## Evaluate on Test Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"We now use the best fitted model from the AutoML Run to make forecasts for the test set. \n",
|
||||||
|
"\n",
|
||||||
|
"We always score on the original dataset whose schema matches the training set schema."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Dataset\n",
|
||||||
|
"test_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/test.csv')])\n",
|
||||||
|
"# preview the first 3 rows of the dataset\n",
|
||||||
|
"test_dataset.take(5).to_pandas_dataframe()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"compute_target = ws.compute_targets['beer-cluster']\n",
|
||||||
|
"test_experiment = Experiment(ws, experiment_name + \"_test\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"import shutil\n",
|
||||||
|
"\n",
|
||||||
|
"script_folder = os.path.join(os.getcwd(), 'inference')\n",
|
||||||
|
"os.makedirs(script_folder, exist_ok=True)\n",
|
||||||
|
"shutil.copy('infer.py', script_folder)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from helper import run_inference\n",
|
||||||
|
"\n",
|
||||||
|
"test_run = run_inference(test_experiment, compute_target, script_folder, best_dnn_run, test_dataset, valid_dataset, forecast_horizon,\n",
|
||||||
|
" target_column_name, time_column_name, freq)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"RunDetails(test_run).show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from helper import run_multiple_inferences\n",
|
||||||
|
"\n",
|
||||||
|
"summary_df = run_multiple_inferences(summary_df, experiment, test_experiment, compute_target, script_folder, test_dataset, \n",
|
||||||
|
" valid_dataset, forecast_horizon, target_column_name, time_column_name, freq)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"for run_name, run_summary in summary_df.iterrows():\n",
|
||||||
|
" print(run_name)\n",
|
||||||
|
" print(run_summary)\n",
|
||||||
|
" run_id = run_summary.run_id\n",
|
||||||
|
" test_run_id = run_summary.test_run_id\n",
|
||||||
|
" test_run = Run(test_experiment, test_run_id)\n",
|
||||||
|
" test_run.wait_for_completion()\n",
|
||||||
|
" test_score = test_run.get_metrics()[run_summary.primary_metric]\n",
|
||||||
|
" summary_df.loc[summary_df.run_id == run_id, 'Test Score'] = test_score\n",
|
||||||
|
" print(\"Test Score: \", test_score)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"hideCode": false,
|
||||||
|
"hidePrompt": false
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"summary_df"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "omkarm"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"hide_code_all_hidden": false,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-beer-remote
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import pandas as pd
|
||||||
|
from azureml.core import Environment
|
||||||
|
from azureml.core.conda_dependencies import CondaDependencies
|
||||||
|
from azureml.train.estimator import Estimator
|
||||||
|
from azureml.core.run import Run
|
||||||
|
|
||||||
|
|
||||||
|
def split_fraction_by_grain(df, fraction, time_column_name,
|
||||||
|
grain_column_names=None):
|
||||||
|
|
||||||
|
if not grain_column_names:
|
||||||
|
df['tmp_grain_column'] = 'grain'
|
||||||
|
grain_column_names = ['tmp_grain_column']
|
||||||
|
|
||||||
|
"""Group df by grain and split on last n rows for each group."""
|
||||||
|
df_grouped = (df.sort_values(time_column_name)
|
||||||
|
.groupby(grain_column_names, group_keys=False))
|
||||||
|
|
||||||
|
df_head = df_grouped.apply(lambda dfg: dfg.iloc[:-int(len(dfg) *
|
||||||
|
fraction)] if fraction > 0 else dfg)
|
||||||
|
|
||||||
|
df_tail = df_grouped.apply(lambda dfg: dfg.iloc[-int(len(dfg) *
|
||||||
|
fraction):] if fraction > 0 else dfg[:0])
|
||||||
|
|
||||||
|
if 'tmp_grain_column' in grain_column_names:
|
||||||
|
for df2 in (df, df_head, df_tail):
|
||||||
|
df2.drop('tmp_grain_column', axis=1, inplace=True)
|
||||||
|
|
||||||
|
grain_column_names.remove('tmp_grain_column')
|
||||||
|
|
||||||
|
return df_head, df_tail
|
||||||
|
|
||||||
|
|
||||||
|
def split_full_for_forecasting(df, time_column_name,
|
||||||
|
grain_column_names=None, test_split=0.2):
|
||||||
|
index_name = df.index.name
|
||||||
|
|
||||||
|
# Assumes that there isn't already a column called tmpindex
|
||||||
|
|
||||||
|
df['tmpindex'] = df.index
|
||||||
|
|
||||||
|
train_df, test_df = split_fraction_by_grain(
|
||||||
|
df, test_split, time_column_name, grain_column_names)
|
||||||
|
|
||||||
|
train_df = train_df.set_index('tmpindex')
|
||||||
|
train_df.index.name = index_name
|
||||||
|
|
||||||
|
test_df = test_df.set_index('tmpindex')
|
||||||
|
test_df.index.name = index_name
|
||||||
|
|
||||||
|
df.drop('tmpindex', axis=1, inplace=True)
|
||||||
|
|
||||||
|
return train_df, test_df
|
||||||
|
|
||||||
|
|
||||||
|
def get_result_df(remote_run):
|
||||||
|
children = list(remote_run.get_children(recursive=True))
|
||||||
|
summary_df = pd.DataFrame(index=['run_id', 'run_algorithm',
|
||||||
|
'primary_metric', 'Score'])
|
||||||
|
goal_minimize = False
|
||||||
|
for run in children:
|
||||||
|
if('run_algorithm' in run.properties and 'score' in run.properties):
|
||||||
|
summary_df[run.id] = [run.id, run.properties['run_algorithm'],
|
||||||
|
run.properties['primary_metric'],
|
||||||
|
float(run.properties['score'])]
|
||||||
|
if('goal' in run.properties):
|
||||||
|
goal_minimize = run.properties['goal'].split('_')[-1] == 'min'
|
||||||
|
|
||||||
|
summary_df = summary_df.T.sort_values(
|
||||||
|
'Score',
|
||||||
|
ascending=goal_minimize).drop_duplicates(['run_algorithm'])
|
||||||
|
summary_df = summary_df.set_index('run_algorithm')
|
||||||
|
return summary_df
|
||||||
|
|
||||||
|
|
||||||
|
def run_inference(test_experiment, compute_target, script_folder, train_run,
|
||||||
|
test_dataset, lookback_dataset, max_horizon,
|
||||||
|
target_column_name, time_column_name, freq):
|
||||||
|
model_base_name = 'model.pkl'
|
||||||
|
if 'model_data_location' in train_run.properties:
|
||||||
|
model_location = train_run.properties['model_data_location']
|
||||||
|
_, model_base_name = model_location.rsplit('/', 1)
|
||||||
|
train_run.download_file('outputs/{}'.format(model_base_name), 'inference/{}'.format(model_base_name))
|
||||||
|
train_run.download_file('outputs/conda_env_v_1_0_0.yml', 'inference/condafile.yml')
|
||||||
|
|
||||||
|
inference_env = Environment("myenv")
|
||||||
|
inference_env.docker.enabled = True
|
||||||
|
inference_env.python.conda_dependencies = CondaDependencies(
|
||||||
|
conda_dependencies_file_path='inference/condafile.yml')
|
||||||
|
|
||||||
|
est = Estimator(source_directory=script_folder,
|
||||||
|
entry_script='infer.py',
|
||||||
|
script_params={
|
||||||
|
'--max_horizon': max_horizon,
|
||||||
|
'--target_column_name': target_column_name,
|
||||||
|
'--time_column_name': time_column_name,
|
||||||
|
'--frequency': freq,
|
||||||
|
'--model_path': model_base_name
|
||||||
|
},
|
||||||
|
inputs=[test_dataset.as_named_input('test_data'),
|
||||||
|
lookback_dataset.as_named_input('lookback_data')],
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment_definition=inference_env)
|
||||||
|
|
||||||
|
run = test_experiment.submit(
|
||||||
|
est, tags={
|
||||||
|
'training_run_id': train_run.id,
|
||||||
|
'run_algorithm': train_run.properties['run_algorithm'],
|
||||||
|
'valid_score': train_run.properties['score'],
|
||||||
|
'primary_metric': train_run.properties['primary_metric']
|
||||||
|
})
|
||||||
|
|
||||||
|
run.log("run_algorithm", run.tags['run_algorithm'])
|
||||||
|
return run
|
||||||
|
|
||||||
|
|
||||||
|
def run_multiple_inferences(summary_df, train_experiment, test_experiment,
|
||||||
|
compute_target, script_folder, test_dataset,
|
||||||
|
lookback_dataset, max_horizon, target_column_name,
|
||||||
|
time_column_name, freq):
|
||||||
|
|
||||||
|
for run_name, run_summary in summary_df.iterrows():
|
||||||
|
print(run_name)
|
||||||
|
print(run_summary)
|
||||||
|
run_id = run_summary.run_id
|
||||||
|
train_run = Run(train_experiment, run_id)
|
||||||
|
|
||||||
|
test_run = run_inference(
|
||||||
|
test_experiment, compute_target, script_folder, train_run,
|
||||||
|
test_dataset, lookback_dataset, max_horizon, target_column_name,
|
||||||
|
time_column_name, freq)
|
||||||
|
|
||||||
|
print(test_run)
|
||||||
|
summary_df.loc[summary_df.run_id == run_id,
|
||||||
|
'test_run_id'] = test_run.id
|
||||||
|
|
||||||
|
return summary_df
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
import argparse
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from pandas.tseries.frequencies import to_offset
|
||||||
|
from sklearn.externals import joblib
|
||||||
|
from sklearn.metrics import mean_absolute_error, mean_squared_error
|
||||||
|
|
||||||
|
from azureml.automl.runtime.shared.score import scoring, constants
|
||||||
|
from azureml.core import Run
|
||||||
|
|
||||||
|
|
||||||
|
def align_outputs(y_predicted, X_trans, X_test, y_test,
|
||||||
|
predicted_column_name='predicted',
|
||||||
|
horizon_colname='horizon_origin'):
|
||||||
|
"""
|
||||||
|
Demonstrates how to get the output aligned to the inputs
|
||||||
|
using pandas indexes. Helps understand what happened if
|
||||||
|
the output's shape differs from the input shape, or if
|
||||||
|
the data got re-sorted by time and grain during forecasting.
|
||||||
|
|
||||||
|
Typical causes of misalignment are:
|
||||||
|
* we predicted some periods that were missing in actuals -> drop from eval
|
||||||
|
* model was asked to predict past max_horizon -> increase max horizon
|
||||||
|
* data at start of X_test was needed for lags -> provide previous periods
|
||||||
|
"""
|
||||||
|
if (horizon_colname in X_trans):
|
||||||
|
df_fcst = pd.DataFrame({predicted_column_name: y_predicted,
|
||||||
|
horizon_colname: X_trans[horizon_colname]})
|
||||||
|
else:
|
||||||
|
df_fcst = pd.DataFrame({predicted_column_name: y_predicted})
|
||||||
|
|
||||||
|
# y and X outputs are aligned by forecast() function contract
|
||||||
|
df_fcst.index = X_trans.index
|
||||||
|
|
||||||
|
# align original X_test to y_test
|
||||||
|
X_test_full = X_test.copy()
|
||||||
|
X_test_full[target_column_name] = y_test
|
||||||
|
|
||||||
|
# X_test_full's index does not include origin, so reset for merge
|
||||||
|
df_fcst.reset_index(inplace=True)
|
||||||
|
X_test_full = X_test_full.reset_index().drop(columns='index')
|
||||||
|
together = df_fcst.merge(X_test_full, how='right')
|
||||||
|
|
||||||
|
# drop rows where prediction or actuals are nan
|
||||||
|
# happens because of missing actuals
|
||||||
|
# or at edges of time due to lags/rolling windows
|
||||||
|
clean = together[together[[target_column_name,
|
||||||
|
predicted_column_name]].notnull().all(axis=1)]
|
||||||
|
return(clean)
|
||||||
|
|
||||||
|
|
||||||
|
def do_rolling_forecast_with_lookback(fitted_model, X_test, y_test,
|
||||||
|
max_horizon, X_lookback, y_lookback,
|
||||||
|
freq='D'):
|
||||||
|
"""
|
||||||
|
Produce forecasts on a rolling origin over the given test set.
|
||||||
|
|
||||||
|
Each iteration makes a forecast for the next 'max_horizon' periods
|
||||||
|
with respect to the current origin, then advances the origin by the
|
||||||
|
horizon time duration. The prediction context for each forecast is set so
|
||||||
|
that the forecaster uses the actual target values prior to the current
|
||||||
|
origin time for constructing lag features.
|
||||||
|
|
||||||
|
This function returns a concatenated DataFrame of rolling forecasts.
|
||||||
|
"""
|
||||||
|
print("Using lookback of size: ", y_lookback.size)
|
||||||
|
df_list = []
|
||||||
|
origin_time = X_test[time_column_name].min()
|
||||||
|
X = X_lookback.append(X_test)
|
||||||
|
y = np.concatenate((y_lookback, y_test), axis=0)
|
||||||
|
while origin_time <= X_test[time_column_name].max():
|
||||||
|
# Set the horizon time - end date of the forecast
|
||||||
|
horizon_time = origin_time + max_horizon * to_offset(freq)
|
||||||
|
|
||||||
|
# Extract test data from an expanding window up-to the horizon
|
||||||
|
expand_wind = (X[time_column_name] < horizon_time)
|
||||||
|
X_test_expand = X[expand_wind]
|
||||||
|
y_query_expand = np.zeros(len(X_test_expand)).astype(np.float)
|
||||||
|
y_query_expand.fill(np.NaN)
|
||||||
|
|
||||||
|
if origin_time != X[time_column_name].min():
|
||||||
|
# Set the context by including actuals up-to the origin time
|
||||||
|
test_context_expand_wind = (X[time_column_name] < origin_time)
|
||||||
|
context_expand_wind = (
|
||||||
|
X_test_expand[time_column_name] < origin_time)
|
||||||
|
y_query_expand[context_expand_wind] = y[test_context_expand_wind]
|
||||||
|
|
||||||
|
# Print some debug info
|
||||||
|
print("Horizon_time:", horizon_time,
|
||||||
|
" origin_time: ", origin_time,
|
||||||
|
" max_horizon: ", max_horizon,
|
||||||
|
" freq: ", freq)
|
||||||
|
print("expand_wind: ", expand_wind)
|
||||||
|
print("y_query_expand")
|
||||||
|
print(y_query_expand)
|
||||||
|
print("X_test")
|
||||||
|
print(X)
|
||||||
|
print("X_test_expand")
|
||||||
|
print(X_test_expand)
|
||||||
|
print("Type of X_test_expand: ", type(X_test_expand))
|
||||||
|
print("Type of y_query_expand: ", type(y_query_expand))
|
||||||
|
|
||||||
|
print("y_query_expand")
|
||||||
|
print(y_query_expand)
|
||||||
|
|
||||||
|
# Make a forecast out to the maximum horizon
|
||||||
|
# y_fcst, X_trans = y_query_expand, X_test_expand
|
||||||
|
y_fcst, X_trans = fitted_model.forecast(X_test_expand, y_query_expand)
|
||||||
|
|
||||||
|
print("y_fcst")
|
||||||
|
print(y_fcst)
|
||||||
|
|
||||||
|
# Align forecast with test set for dates within
|
||||||
|
# the current rolling window
|
||||||
|
trans_tindex = X_trans.index.get_level_values(time_column_name)
|
||||||
|
trans_roll_wind = (trans_tindex >= origin_time) & (
|
||||||
|
trans_tindex < horizon_time)
|
||||||
|
test_roll_wind = expand_wind & (X[time_column_name] >= origin_time)
|
||||||
|
df_list.append(align_outputs(
|
||||||
|
y_fcst[trans_roll_wind], X_trans[trans_roll_wind],
|
||||||
|
X[test_roll_wind], y[test_roll_wind]))
|
||||||
|
|
||||||
|
# Advance the origin time
|
||||||
|
origin_time = horizon_time
|
||||||
|
|
||||||
|
return pd.concat(df_list, ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
|
def do_rolling_forecast(fitted_model, X_test, y_test, max_horizon, freq='D'):
|
||||||
|
"""
|
||||||
|
Produce forecasts on a rolling origin over the given test set.
|
||||||
|
|
||||||
|
Each iteration makes a forecast for the next 'max_horizon' periods
|
||||||
|
with respect to the current origin, then advances the origin by the
|
||||||
|
horizon time duration. The prediction context for each forecast is set so
|
||||||
|
that the forecaster uses the actual target values prior to the current
|
||||||
|
origin time for constructing lag features.
|
||||||
|
|
||||||
|
This function returns a concatenated DataFrame of rolling forecasts.
|
||||||
|
"""
|
||||||
|
df_list = []
|
||||||
|
origin_time = X_test[time_column_name].min()
|
||||||
|
while origin_time <= X_test[time_column_name].max():
|
||||||
|
# Set the horizon time - end date of the forecast
|
||||||
|
horizon_time = origin_time + max_horizon * to_offset(freq)
|
||||||
|
|
||||||
|
# Extract test data from an expanding window up-to the horizon
|
||||||
|
expand_wind = (X_test[time_column_name] < horizon_time)
|
||||||
|
X_test_expand = X_test[expand_wind]
|
||||||
|
y_query_expand = np.zeros(len(X_test_expand)).astype(np.float)
|
||||||
|
y_query_expand.fill(np.NaN)
|
||||||
|
|
||||||
|
if origin_time != X_test[time_column_name].min():
|
||||||
|
# Set the context by including actuals up-to the origin time
|
||||||
|
test_context_expand_wind = (X_test[time_column_name] < origin_time)
|
||||||
|
context_expand_wind = (
|
||||||
|
X_test_expand[time_column_name] < origin_time)
|
||||||
|
y_query_expand[context_expand_wind] = y_test[
|
||||||
|
test_context_expand_wind]
|
||||||
|
|
||||||
|
# Print some debug info
|
||||||
|
print("Horizon_time:", horizon_time,
|
||||||
|
" origin_time: ", origin_time,
|
||||||
|
" max_horizon: ", max_horizon,
|
||||||
|
" freq: ", freq)
|
||||||
|
print("expand_wind: ", expand_wind)
|
||||||
|
print("y_query_expand")
|
||||||
|
print(y_query_expand)
|
||||||
|
print("X_test")
|
||||||
|
print(X_test)
|
||||||
|
print("X_test_expand")
|
||||||
|
print(X_test_expand)
|
||||||
|
print("Type of X_test_expand: ", type(X_test_expand))
|
||||||
|
print("Type of y_query_expand: ", type(y_query_expand))
|
||||||
|
print("y_query_expand")
|
||||||
|
print(y_query_expand)
|
||||||
|
|
||||||
|
# Make a forecast out to the maximum horizon
|
||||||
|
y_fcst, X_trans = fitted_model.forecast(X_test_expand, y_query_expand)
|
||||||
|
|
||||||
|
print("y_fcst")
|
||||||
|
print(y_fcst)
|
||||||
|
|
||||||
|
# Align forecast with test set for dates within the
|
||||||
|
# current rolling window
|
||||||
|
trans_tindex = X_trans.index.get_level_values(time_column_name)
|
||||||
|
trans_roll_wind = (trans_tindex >= origin_time) & (
|
||||||
|
trans_tindex < horizon_time)
|
||||||
|
test_roll_wind = expand_wind & (
|
||||||
|
X_test[time_column_name] >= origin_time)
|
||||||
|
df_list.append(align_outputs(y_fcst[trans_roll_wind],
|
||||||
|
X_trans[trans_roll_wind],
|
||||||
|
X_test[test_roll_wind],
|
||||||
|
y_test[test_roll_wind]))
|
||||||
|
|
||||||
|
# Advance the origin time
|
||||||
|
origin_time = horizon_time
|
||||||
|
|
||||||
|
return pd.concat(df_list, ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
|
def APE(actual, pred):
|
||||||
|
"""
|
||||||
|
Calculate absolute percentage error.
|
||||||
|
Returns a vector of APE values with same length as actual/pred.
|
||||||
|
"""
|
||||||
|
return 100 * np.abs((actual - pred) / actual)
|
||||||
|
|
||||||
|
|
||||||
|
def MAPE(actual, pred):
|
||||||
|
"""
|
||||||
|
Calculate mean absolute percentage error.
|
||||||
|
Remove NA and values where actual is close to zero
|
||||||
|
"""
|
||||||
|
not_na = ~(np.isnan(actual) | np.isnan(pred))
|
||||||
|
not_zero = ~np.isclose(actual, 0.0)
|
||||||
|
actual_safe = actual[not_na & not_zero]
|
||||||
|
pred_safe = pred[not_na & not_zero]
|
||||||
|
return np.mean(APE(actual_safe, pred_safe))
|
||||||
|
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument(
|
||||||
|
'--max_horizon', type=int, dest='max_horizon',
|
||||||
|
default=10, help='Max Horizon for forecasting')
|
||||||
|
parser.add_argument(
|
||||||
|
'--target_column_name', type=str, dest='target_column_name',
|
||||||
|
help='Target Column Name')
|
||||||
|
parser.add_argument(
|
||||||
|
'--time_column_name', type=str, dest='time_column_name',
|
||||||
|
help='Time Column Name')
|
||||||
|
parser.add_argument(
|
||||||
|
'--frequency', type=str, dest='freq',
|
||||||
|
help='Frequency of prediction')
|
||||||
|
parser.add_argument(
|
||||||
|
'--model_path', type=str, dest='model_path',
|
||||||
|
default='model.pkl', help='Filename of model to be loaded')
|
||||||
|
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
max_horizon = args.max_horizon
|
||||||
|
target_column_name = args.target_column_name
|
||||||
|
time_column_name = args.time_column_name
|
||||||
|
freq = args.freq
|
||||||
|
model_path = args.model_path
|
||||||
|
|
||||||
|
|
||||||
|
print('args passed are: ')
|
||||||
|
print(max_horizon)
|
||||||
|
print(target_column_name)
|
||||||
|
print(time_column_name)
|
||||||
|
print(freq)
|
||||||
|
print(model_path)
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
# get input dataset by name
|
||||||
|
test_dataset = run.input_datasets['test_data']
|
||||||
|
lookback_dataset = run.input_datasets['lookback_data']
|
||||||
|
|
||||||
|
grain_column_names = []
|
||||||
|
|
||||||
|
df = test_dataset.to_pandas_dataframe()
|
||||||
|
|
||||||
|
print('Read df')
|
||||||
|
print(df)
|
||||||
|
|
||||||
|
X_test_df = test_dataset.drop_columns(columns=[target_column_name])
|
||||||
|
y_test_df = test_dataset.with_timestamp_columns(
|
||||||
|
None).keep_columns(columns=[target_column_name])
|
||||||
|
|
||||||
|
X_lookback_df = lookback_dataset.drop_columns(columns=[target_column_name])
|
||||||
|
y_lookback_df = lookback_dataset.with_timestamp_columns(
|
||||||
|
None).keep_columns(columns=[target_column_name])
|
||||||
|
|
||||||
|
fitted_model = joblib.load(model_path)
|
||||||
|
|
||||||
|
|
||||||
|
if hasattr(fitted_model, 'get_lookback'):
|
||||||
|
lookback = fitted_model.get_lookback()
|
||||||
|
df_all = do_rolling_forecast_with_lookback(
|
||||||
|
fitted_model,
|
||||||
|
X_test_df.to_pandas_dataframe(),
|
||||||
|
y_test_df.to_pandas_dataframe().values.T[0],
|
||||||
|
max_horizon,
|
||||||
|
X_lookback_df.to_pandas_dataframe()[-lookback:],
|
||||||
|
y_lookback_df.to_pandas_dataframe().values.T[0][-lookback:],
|
||||||
|
freq)
|
||||||
|
else:
|
||||||
|
df_all = do_rolling_forecast(
|
||||||
|
fitted_model,
|
||||||
|
X_test_df.to_pandas_dataframe(),
|
||||||
|
y_test_df.to_pandas_dataframe().values.T[0],
|
||||||
|
max_horizon,
|
||||||
|
freq)
|
||||||
|
|
||||||
|
print(df_all)
|
||||||
|
|
||||||
|
print("target values:::")
|
||||||
|
print(df_all[target_column_name])
|
||||||
|
print("predicted values:::")
|
||||||
|
print(df_all['predicted'])
|
||||||
|
|
||||||
|
# Use the AutoML scoring module
|
||||||
|
regression_metrics = list(constants.REGRESSION_SCALAR_SET)
|
||||||
|
y_test = np.array(df_all[target_column_name])
|
||||||
|
y_pred = np.array(df_all['predicted'])
|
||||||
|
scores = scoring.score_regression(y_test, y_pred, regression_metrics)
|
||||||
|
|
||||||
|
print("scores:")
|
||||||
|
print(scores)
|
||||||
|
|
||||||
|
for key, value in scores.items():
|
||||||
|
run.log(key, value)
|
||||||
|
|
||||||
|
print("Simple forecasting model")
|
||||||
|
rmse = np.sqrt(mean_squared_error(
|
||||||
|
df_all[target_column_name], df_all['predicted']))
|
||||||
|
print("[Test Data] \nRoot Mean squared error: %.2f" % rmse)
|
||||||
|
mae = mean_absolute_error(df_all[target_column_name], df_all['predicted'])
|
||||||
|
print('mean_absolute_error score: %.2f' % mae)
|
||||||
|
print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))
|
||||||
|
|
||||||
|
run.log('rmse', rmse)
|
||||||
|
run.log('mae', mae)
|
||||||
@@ -26,8 +26,10 @@
|
|||||||
"## Contents\n",
|
"## Contents\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#Introduction)\n",
|
||||||
"1. [Setup](#Setup)\n",
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Compute](#Compute)\n",
|
||||||
"1. [Data](#Data)\n",
|
"1. [Data](#Data)\n",
|
||||||
"1. [Train](#Train)\n",
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Featurization](#Featurization)\n",
|
||||||
"1. [Evaluate](#Evaluate)"
|
"1. [Evaluate](#Evaluate)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -36,19 +38,17 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"In this example, we show how AutoML can be used for bike share forecasting.\n",
|
"This notebook demonstrates demand forecasting for a bike-sharing service using AutoML.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The purpose is to demonstrate how to take advantage of the built-in holiday featurization, access the feature names, and further demonstrate how to work with the `forecast` function. Please also look at the additional forecasting notebooks, which document lagging, rolling windows, forecast quantiles, other ways to use the forecast function, and forecaster deployment.\n",
|
"AutoML highlights here include built-in holiday featurization, accessing engineered feature names, and working with the `forecast` function. Please also look at the additional forecasting notebooks, which document lagging, rolling windows, forecast quantiles, other ways to use the forecast function, and forecaster deployment.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you would see\n",
|
"Notebook synopsis:\n",
|
||||||
"1. Creating an Experiment in an existing Workspace\n",
|
"1. Creating an Experiment in an existing Workspace\n",
|
||||||
"2. Instantiating AutoMLConfig with new task type \"forecasting\" for timeseries data training, and other timeseries related settings: for this dataset we use the basic one: \"time_column_name\" \n",
|
"2. Configuration and local run of AutoML for a time-series model with lag and holiday features \n",
|
||||||
"3. Training the Model using local compute\n",
|
"3. Viewing the engineered names for featurized data and featurization summary for all raw features\n",
|
||||||
"4. Exploring the results\n",
|
"4. Evaluating the fitted model using a rolling test "
|
||||||
"5. Viewing the engineered names for featurized data and featurization summary for all raw features\n",
|
|
||||||
"6. Testing the fitted model"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -68,23 +68,34 @@
|
|||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"import warnings\n",
|
|
||||||
"# Squash warning messages for cleaner output in the notebook\n",
|
|
||||||
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"from azureml.core import Workspace, Experiment, Dataset\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"from matplotlib import pyplot as plt\n",
|
"from datetime import datetime"
|
||||||
"from sklearn.metrics import mean_absolute_error, mean_squared_error"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"As part of the setup you have already created a <b>Workspace</b>. For AutoML you would need to create an <b>Experiment</b>. An <b>Experiment</b> is a named object in a <b>Workspace</b>, which is used to run experiments."
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -97,18 +108,15 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'automl-bikeshareforecasting'\n",
|
"experiment_name = 'automl-bikeshareforecasting'\n",
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-local-bikeshareforecasting'\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['SKU'] = ws.sku\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output['Location'] = ws.location\n",
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output['Run History Name'] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
@@ -119,8 +127,11 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Data\n",
|
"## Compute\n",
|
||||||
"Read bike share demand data from file, and preview data."
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read this article on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -129,22 +140,52 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"data = pd.read_csv('bike-no.csv', parse_dates=['date'])"
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your cluster.\n",
|
||||||
|
"amlcompute_cluster_name = \"bike-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Let's set up what we know abou the dataset. \n",
|
"## Data\n",
|
||||||
|
"\n",
|
||||||
|
"The [Machine Learning service workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace) is paired with the storage account, which contains the default data store. We will use it to upload the bike share data and create [tabular dataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) for training. A tabular dataset defines a series of lazily-evaluated, immutable operations to load data from the data source into tabular representation."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"datastore = ws.get_default_datastore()\n",
|
||||||
|
"datastore.upload_files(files = ['./bike-no.csv'], target_path = 'dataset/', overwrite = True,show_progress = True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's set up what we know about the dataset. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"**Target column** is what we want to forecast.\n",
|
"**Target column** is what we want to forecast.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"**Time column** is the time axis along which to predict.\n",
|
"**Time column** is the time axis along which to predict."
|
||||||
"\n",
|
|
||||||
"**Grain** is another word for an individual time series in your dataset. Grains are identified by values of the columns listed `grain_column_names`, for example \"store\" and \"item\" if your data has multiple time series of sales, one series for each combination of store and item sold.\n",
|
|
||||||
"\n",
|
|
||||||
"This dataset has only one time series. Please see the [orange juice notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales) for an example of a multi-time series dataset."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -154,17 +195,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"target_column_name = 'cnt'\n",
|
"target_column_name = 'cnt'\n",
|
||||||
"time_column_name = 'date'\n",
|
"time_column_name = 'date'"
|
||||||
"grain_column_names = []"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Split the data\n",
|
|
||||||
"\n",
|
|
||||||
"The first split we make is into train and test sets. Note we are splitting on time."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -173,29 +204,17 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"train = data[data[time_column_name] < '2012-09-01']\n",
|
"dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'dataset/bike-no.csv')]).with_timestamp_columns(fine_grain_timestamp=time_column_name) \n",
|
||||||
"test = data[data[time_column_name] >= '2012-09-01']\n",
|
"dataset.take(5).to_pandas_dataframe().reset_index(drop=True)"
|
||||||
"\n",
|
|
||||||
"X_train = train.copy()\n",
|
|
||||||
"y_train = X_train.pop(target_column_name).values\n",
|
|
||||||
"\n",
|
|
||||||
"X_test = test.copy()\n",
|
|
||||||
"y_test = X_test.pop(target_column_name).values\n",
|
|
||||||
"\n",
|
|
||||||
"print(X_train.shape)\n",
|
|
||||||
"print(y_train.shape)\n",
|
|
||||||
"print(X_test.shape)\n",
|
|
||||||
"print(y_test.shape)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Setting forecaster maximum horizon \n",
|
"### Split the data\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Assuming your test data forms a full and regular time series(regular time intervals and no holes), \n",
|
"The first split we make is into train and test sets. Note we are splitting on time. Data before 9/1 will be used for training, and data after and including 9/1 will be used for testing."
|
||||||
"the maximum horizon you will need to forecast is the length of the longest grain in your test set."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -204,10 +223,35 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"if len(grain_column_names) == 0:\n",
|
"# select data that occurs before a specified date\n",
|
||||||
" max_horizon = len(X_test)\n",
|
"train = dataset.time_before(datetime(2012, 8, 31), include_boundary=True)\n",
|
||||||
"else:\n",
|
"train.to_pandas_dataframe().tail(5).reset_index(drop=True)"
|
||||||
" max_horizon = X_test.groupby(grain_column_names)[time_column_name].count().max()"
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"test = dataset.time_after(datetime(2012, 9, 1), include_boundary=True)\n",
|
||||||
|
"test.to_pandas_dataframe().head(5).reset_index(drop=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Forecasting Parameters\n",
|
||||||
|
"To define forecasting parameters for your experiment training, you can leverage the ForecastingParameters class. The table below details the forecasting parameter we will be passing into our experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**time_column_name**|The name of your time column.|\n",
|
||||||
|
"|**forecast_horizon**|The forecast horizon is how many periods forward you would like to forecast. This integer horizon is in units of the timeseries frequency (e.g. daily, weekly).|\n",
|
||||||
|
"|**country_or_region_for_holidays**|The country/region used to generate holiday features. These should be ISO 3166 two-letter country/region codes (i.e. 'US', 'GB').|\n",
|
||||||
|
"|**target_lags**|The target_lags specifies how far back we will construct the lags of the target variable.|\n",
|
||||||
|
"|**drop_column_names**|Name(s) of columns to drop prior to modeling|"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -222,49 +266,78 @@
|
|||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
"|**task**|forecasting|\n",
|
"|**task**|forecasting|\n",
|
||||||
"|**primary_metric**|This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>\n",
|
"|**primary_metric**|This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>\n",
|
||||||
"|**iterations**|Number of iterations. In each iteration, Auto ML trains a specific pipeline on the given data|\n",
|
"|**blocked_models**|Models in blocked_models won't be used by AutoML. All supported models can be found at [here](https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.constants.supportedmodels.forecasting?view=azure-ml-py).|\n",
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
"|**experiment_timeout_hours**|Experimentation timeout in hours.|\n",
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
|
"|**compute_target**|The remote compute for training.|\n",
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
"|**country_or_region**|The country/region used to generate holiday features. These should be ISO 3166 two-letter country/region codes (i.e. 'US', 'GB').|\n",
|
"|**enable_early_stopping**|If early stopping is on, training will stop when the primary metric is no longer improving.|\n",
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder. "
|
"|**forecasting_parameters**|A class that holds all the forecasting related parameters.|\n",
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"time_column_name = 'date'\n",
|
|
||||||
"automl_settings = {\n",
|
|
||||||
" \"time_column_name\": time_column_name,\n",
|
|
||||||
" # these columns are a breakdown of the total and therefore a leak\n",
|
|
||||||
" \"drop_column_names\": ['casual', 'registered'],\n",
|
|
||||||
" # knowing the country/region allows Automated ML to bring in holidays\n",
|
|
||||||
" \"country_or_region\" : 'US',\n",
|
|
||||||
" \"max_horizon\" : max_horizon,\n",
|
|
||||||
" \"target_lags\": 1 \n",
|
|
||||||
"}\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task = 'forecasting', \n",
|
"This notebook uses the blocked_models parameter to exclude some models that take a longer time to train on this dataset. You can choose to remove models from the blocked_models list but you may need to increase the experiment_timeout_hours parameter value to get results."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Setting forecaster maximum horizon \n",
|
||||||
|
"\n",
|
||||||
|
"The forecast horizon is the number of periods into the future that the model should predict. Here, we set the horizon to 14 periods (i.e. 14 days). Notice that this is much shorter than the number of days in the test set; we will need to use a rolling test to evaluate the performance on the whole test set. For more discussion of forecast horizons and guiding principles for setting them, please see the [energy demand notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand). "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"forecast_horizon = 14"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Config AutoML"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
|
" time_column_name=time_column_name,\n",
|
||||||
|
" forecast_horizon=forecast_horizon,\n",
|
||||||
|
" country_or_region_for_holidays='US', # set country_or_region will trigger holiday featurizer\n",
|
||||||
|
" target_lags='auto', # use heuristic based lag setting \n",
|
||||||
|
" drop_column_names=['casual', 'registered'] # these columns are a breakdown of the total and therefore a leak\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task='forecasting', \n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
" iterations = 10,\n",
|
" blocked_models = ['ExtremeRandomTrees'], \n",
|
||||||
" iteration_timeout_minutes = 5,\n",
|
" experiment_timeout_hours=0.3,\n",
|
||||||
" X = X_train,\n",
|
" training_data=train,\n",
|
||||||
" y = y_train,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" n_cross_validations = 3, \n",
|
" compute_target=compute_target,\n",
|
||||||
" path=project_folder,\n",
|
" enable_early_stopping=True,\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" n_cross_validations=3, \n",
|
||||||
" **automl_settings)"
|
" max_concurrent_iterations=4,\n",
|
||||||
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" verbosity=logging.INFO,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"We will now run the experiment, starting with 10 iterations of model search. Experiment can be continued for more iterations if the results are not yet good. You will see the currently running iterations printing to the console."
|
"We will now run the experiment, you can go to Azure ML portal to view the run details. "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -273,14 +346,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run = experiment.submit(automl_config, show_output=True)"
|
"remote_run = experiment.submit(automl_config, show_output=False)\n",
|
||||||
]
|
"remote_run"
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Displaying the run objects gives you links to the visual tools in the Azure Portal. Go try them!"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -289,7 +356,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run"
|
"remote_run.wait_for_completion()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -297,7 +364,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Retrieve the Best Model\n",
|
"### Retrieve the Best Model\n",
|
||||||
"Below we select the best pipeline from our iterations. The get_output method on automl_classifier returns the best run and the fitted model for the last fit invocation. There are overloads on get_output that allow you to retrieve the best run and fitted model for any logged metric or a particular iteration."
|
"Below we select the best model from all the training iterations using get_output method."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -306,7 +373,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
"fitted_model.steps"
|
"fitted_model.steps"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -314,9 +381,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### View the engineered names for featurized data\n",
|
"## Featurization\n",
|
||||||
"\n",
|
"\n",
|
||||||
"You can accees the engineered feature names generated in time-series featurization. Note that a number of named holiday periods are represented. We recommend that you have at least one year of data when using this feature to ensure that all yearly holidays are captured in the training featurization."
|
"You can access the engineered feature names generated in time-series featurization. Note that a number of named holiday periods are represented. We recommend that you have at least one year of data when using this feature to ensure that all yearly holidays are captured in the training featurization."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -349,45 +416,26 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()"
|
"# Get the featurization summary as a list of JSON\n",
|
||||||
|
"featurization_summary = fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()\n",
|
||||||
|
"# View the featurization summary as a pandas dataframe\n",
|
||||||
|
"pd.DataFrame.from_records(featurization_summary)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Test the Best Fitted Model\n",
|
"## Evaluate"
|
||||||
"\n",
|
|
||||||
"Predict on training and test set, and calculate residual values.\n",
|
|
||||||
"\n",
|
|
||||||
"We always score on the original dataset whose schema matches the scheme of the training dataset."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X_test.head()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"y_query = y_test.copy().astype(np.float)\n",
|
|
||||||
"y_query.fill(np.NaN)\n",
|
|
||||||
"y_fcst, X_trans = fitted_model.forecast(X_test, y_query)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"It is a good practice to always align the output explicitly to the input, as the count and order of the rows may have changed during transformations that span multiple rows."
|
"We now use the best fitted model from the AutoML Run to make forecasts for the test set. We will do batch scoring on the test dataset which should have the same schema as training dataset.\n",
|
||||||
|
"\n",
|
||||||
|
"The scoring will run on a remote compute. In this example, it will reuse the training compute."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -396,38 +444,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def align_outputs(y_predicted, X_trans, X_test, y_test, predicted_column_name = 'predicted'):\n",
|
"test_experiment = Experiment(ws, experiment_name + \"_test\")"
|
||||||
" \"\"\"\n",
|
]
|
||||||
" Demonstrates how to get the output aligned to the inputs\n",
|
},
|
||||||
" using pandas indexes. Helps understand what happened if\n",
|
{
|
||||||
" the output's shape differs from the input shape, or if\n",
|
"cell_type": "markdown",
|
||||||
" the data got re-sorted by time and grain during forecasting.\n",
|
"metadata": {},
|
||||||
" \n",
|
"source": [
|
||||||
" Typical causes of misalignment are:\n",
|
"### Retrieving forecasts from the model\n",
|
||||||
" * we predicted some periods that were missing in actuals -> drop from eval\n",
|
"To run the forecast on the remote compute we will use a helper script: forecasting_script. This script contains the utility methods which will be used by the remote estimator. We copy the script to the project folder to upload it to remote compute."
|
||||||
" * model was asked to predict past max_horizon -> increase max horizon\n",
|
|
||||||
" * data at start of X_test was needed for lags -> provide previous periods\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" df_fcst = pd.DataFrame({predicted_column_name : y_predicted})\n",
|
|
||||||
" # y and X outputs are aligned by forecast() function contract\n",
|
|
||||||
" df_fcst.index = X_trans.index\n",
|
|
||||||
" \n",
|
|
||||||
" # align original X_test to y_test \n",
|
|
||||||
" X_test_full = X_test.copy()\n",
|
|
||||||
" X_test_full[target_column_name] = y_test\n",
|
|
||||||
"\n",
|
|
||||||
" # X_test_full's index does not include origin, so reset for merge\n",
|
|
||||||
" df_fcst.reset_index(inplace=True)\n",
|
|
||||||
" X_test_full = X_test_full.reset_index().drop(columns='index')\n",
|
|
||||||
" together = df_fcst.merge(X_test_full, how='right')\n",
|
|
||||||
" \n",
|
|
||||||
" # drop rows where prediction or actuals are nan \n",
|
|
||||||
" # happens because of missing actuals \n",
|
|
||||||
" # or at edges of time due to lags/rolling windows\n",
|
|
||||||
" clean = together[together[[target_column_name, predicted_column_name]].notnull().all(axis=1)]\n",
|
|
||||||
" return(clean)\n",
|
|
||||||
"\n",
|
|
||||||
"df_all = align_outputs(y_fcst, X_trans, X_test, y_test)\n"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -436,17 +461,19 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def MAPE(actual, pred):\n",
|
"import os\n",
|
||||||
" \"\"\"\n",
|
"import shutil\n",
|
||||||
" Calculate mean absolute percentage error.\n",
|
"\n",
|
||||||
" Remove NA and values where actual is close to zero\n",
|
"script_folder = os.path.join(os.getcwd(), 'forecast')\n",
|
||||||
" \"\"\"\n",
|
"os.makedirs(script_folder, exist_ok=True)\n",
|
||||||
" not_na = ~(np.isnan(actual) | np.isnan(pred))\n",
|
"shutil.copy('forecasting_script.py', script_folder)"
|
||||||
" not_zero = ~np.isclose(actual, 0.0)\n",
|
]
|
||||||
" actual_safe = actual[not_na & not_zero]\n",
|
},
|
||||||
" pred_safe = pred[not_na & not_zero]\n",
|
{
|
||||||
" APE = 100*np.abs((actual_safe - pred_safe)/actual_safe)\n",
|
"cell_type": "markdown",
|
||||||
" return np.mean(APE)"
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"For brevity, we have created a function called run_forecast that submits the test data to the best model determined during the training run and retrieves forecasts. The test set is longer than the forecast horizon specified at train time, so the forecasting script uses a so-called rolling evaluation to generate predictions over the whole test set. A rolling evaluation iterates the forecaster over the test set, using the actuals in the test set to make lag features as needed. "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -455,28 +482,138 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"Simple forecasting model\")\n",
|
"from run_forecast import run_rolling_forecast\n",
|
||||||
"rmse = np.sqrt(mean_squared_error(df_all[target_column_name], df_all['predicted']))\n",
|
|
||||||
"print(\"[Test Data] \\nRoot Mean squared error: %.2f\" % rmse)\n",
|
|
||||||
"mae = mean_absolute_error(df_all[target_column_name], df_all['predicted'])\n",
|
|
||||||
"print('mean_absolute_error score: %.2f' % mae)\n",
|
|
||||||
"print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
|
"remote_run = run_rolling_forecast(test_experiment, compute_target, best_run, test, target_column_name)\n",
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Download the prediction result for metrics calcuation\n",
|
||||||
|
"The test data with predictions are saved in artifact outputs/predictions.csv. You can download it and calculation some error metrics for the forecasts and vizualize the predictions vs. the actuals."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.download_file('outputs/predictions.csv', 'predictions.csv')\n",
|
||||||
|
"df_all = pd.read_csv('predictions.csv')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.core.shared import constants\n",
|
||||||
|
"from azureml.automl.runtime.shared.score import scoring\n",
|
||||||
|
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"\n",
|
||||||
|
"# use automl metrics module\n",
|
||||||
|
"scores = scoring.score_regression(\n",
|
||||||
|
" y_test=df_all[target_column_name],\n",
|
||||||
|
" y_pred=df_all['predicted'],\n",
|
||||||
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
|
"for key, value in scores.items(): \n",
|
||||||
|
" print('{}: {:.3f}'.format(key, value))\n",
|
||||||
|
" \n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib notebook\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Since we did a rolling evaluation on the test set, we can analyze the predictions by their forecast horizon relative to the rolling origin. The model was initially trained at a forecast horizon of 14, so each prediction from the model is associated with a horizon value from 1 to 14. The horizon values are in a column named, \"horizon_origin,\" in the prediction set. For example, we can calculate some of the error metrics grouped by the horizon:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from metrics_helper import MAPE, APE\n",
|
||||||
|
"df_all.groupby('horizon_origin').apply(\n",
|
||||||
|
" lambda df: pd.Series({'MAPE': MAPE(df[target_column_name], df['predicted']),\n",
|
||||||
|
" 'RMSE': np.sqrt(mean_squared_error(df[target_column_name], df['predicted'])),\n",
|
||||||
|
" 'MAE': mean_absolute_error(df[target_column_name], df['predicted'])}))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"To drill down more, we can look at the distributions of APE (absolute percentage error) by horizon. From the chart, it is clear that the overall MAPE is being skewed by one particular point where the actual value is of small absolute value."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"df_all_APE = df_all.assign(APE=APE(df_all[target_column_name], df_all['predicted']))\n",
|
||||||
|
"APEs = [df_all_APE[df_all['horizon_origin'] == h].APE.values for h in range(1, forecast_horizon + 1)]\n",
|
||||||
|
"\n",
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"plt.boxplot(APEs)\n",
|
||||||
|
"plt.yscale('log')\n",
|
||||||
|
"plt.xlabel('horizon')\n",
|
||||||
|
"plt.ylabel('APE (%)')\n",
|
||||||
|
"plt.title('Absolute Percentage Errors by Forecast Horizon')\n",
|
||||||
|
"\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "xiaga@microsoft.com, tosingli@microsoft.com"
|
"name": "erwright"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"Remote"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"BikeShare"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"file_extension": ".py",
|
||||||
|
"framework": [
|
||||||
|
"Azure ML AutoML"
|
||||||
|
],
|
||||||
|
"friendly_name": "Forecasting BikeShare Demand",
|
||||||
|
"index_order": 1,
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
"display_name": "Python 3.6",
|
"display_name": "Python 3.6",
|
||||||
"language": "python",
|
"language": "python",
|
||||||
@@ -493,8 +630,17 @@
|
|||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.7"
|
"version": "3.6.7"
|
||||||
}
|
},
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"npconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"tags": [
|
||||||
|
"Forecasting"
|
||||||
|
],
|
||||||
|
"task": "Forecasting",
|
||||||
|
"version": 3
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 2
|
"nbformat_minor": 4
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-bike-share
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import argparse
|
||||||
|
import azureml.train.automl
|
||||||
|
from azureml.core import Run
|
||||||
|
from sklearn.externals import joblib
|
||||||
|
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument(
|
||||||
|
'--target_column_name', type=str, dest='target_column_name',
|
||||||
|
help='Target Column Name')
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
target_column_name = args.target_column_name
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
# get input dataset by name
|
||||||
|
test_dataset = run.input_datasets['test_data']
|
||||||
|
|
||||||
|
df = test_dataset.to_pandas_dataframe().reset_index(drop=True)
|
||||||
|
|
||||||
|
X_test_df = test_dataset.drop_columns(columns=[target_column_name]).to_pandas_dataframe().reset_index(drop=True)
|
||||||
|
y_test_df = test_dataset.with_timestamp_columns(None).keep_columns(columns=[target_column_name]).to_pandas_dataframe()
|
||||||
|
|
||||||
|
fitted_model = joblib.load('model.pkl')
|
||||||
|
|
||||||
|
y_pred, X_trans = fitted_model.rolling_evaluation(X_test_df, y_test_df.values)
|
||||||
|
|
||||||
|
# Add predictions, actuals, and horizon relative to rolling origin to the test feature data
|
||||||
|
assign_dict = {'horizon_origin': X_trans['horizon_origin'].values, 'predicted': y_pred,
|
||||||
|
target_column_name: y_test_df[target_column_name].values}
|
||||||
|
df_all = X_test_df.assign(**assign_dict)
|
||||||
|
|
||||||
|
file_name = 'outputs/predictions.csv'
|
||||||
|
export_csv = df_all.to_csv(file_name, header=True)
|
||||||
|
|
||||||
|
# Upload the predictions into artifacts
|
||||||
|
run.upload_file(name=file_name, path_or_stream=file_name)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
def APE(actual, pred):
|
||||||
|
"""
|
||||||
|
Calculate absolute percentage error.
|
||||||
|
Returns a vector of APE values with same length as actual/pred.
|
||||||
|
"""
|
||||||
|
return 100 * np.abs((actual - pred) / actual)
|
||||||
|
|
||||||
|
|
||||||
|
def MAPE(actual, pred):
|
||||||
|
"""
|
||||||
|
Calculate mean absolute percentage error.
|
||||||
|
Remove NA and values where actual is close to zero
|
||||||
|
"""
|
||||||
|
not_na = ~(np.isnan(actual) | np.isnan(pred))
|
||||||
|
not_zero = ~np.isclose(actual, 0.0)
|
||||||
|
actual_safe = actual[not_na & not_zero]
|
||||||
|
pred_safe = pred[not_na & not_zero]
|
||||||
|
return np.mean(APE(actual_safe, pred_safe))
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from azureml.train.estimator import Estimator
|
||||||
|
|
||||||
|
|
||||||
|
def run_rolling_forecast(test_experiment, compute_target, train_run, test_dataset,
|
||||||
|
target_column_name, inference_folder='./forecast'):
|
||||||
|
train_run.download_file('outputs/model.pkl',
|
||||||
|
inference_folder + '/model.pkl')
|
||||||
|
|
||||||
|
inference_env = train_run.get_environment()
|
||||||
|
|
||||||
|
est = Estimator(source_directory=inference_folder,
|
||||||
|
entry_script='forecasting_script.py',
|
||||||
|
script_params={
|
||||||
|
'--target_column_name': target_column_name
|
||||||
|
},
|
||||||
|
inputs=[test_dataset.as_named_input('test_data')],
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment_definition=inference_env)
|
||||||
|
|
||||||
|
run = test_experiment.submit(est,
|
||||||
|
tags={
|
||||||
|
'training_run_id': train_run.id,
|
||||||
|
'run_algorithm': train_run.properties['run_algorithm'],
|
||||||
|
'valid_score': train_run.properties['score'],
|
||||||
|
'primary_metric': train_run.properties['primary_metric']
|
||||||
|
})
|
||||||
|
|
||||||
|
run.log("run_algorithm", run.tags['run_algorithm'])
|
||||||
|
return run
|
||||||
@@ -21,13 +21,17 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Automated Machine Learning\n",
|
"# Automated Machine Learning\n",
|
||||||
"_**Energy Demand Forecasting**_\n",
|
"_**Forecasting using the Energy Demand Dataset**_\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Contents\n",
|
"## Contents\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#Introduction)\n",
|
||||||
"1. [Setup](#Setup)\n",
|
"1. [Setup](#Setup)\n",
|
||||||
"1. [Data](#Data)\n",
|
"1. [Data and Forecasting Configurations](#Data)\n",
|
||||||
"1. [Train](#Train)"
|
"1. [Train](#Train)\n",
|
||||||
|
"\n",
|
||||||
|
"Advanced Forecasting\n",
|
||||||
|
"1. [Advanced Training](#advanced_training)\n",
|
||||||
|
"1. [Advanced Results](#advanced_results)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -35,24 +39,25 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"In this example, we show how AutoML can be used for energy demand forecasting.\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"In this example we use the associated New York City energy demand dataset to showcase how you can use AutoML for a simple forecasting problem and explore the results. The goal is predict the energy demand for the next 48 hours based on historic time-series data.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you would see\n",
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration notebook](../../../configuration.ipynb) first, if you haven't already, to establish your connection to the AzureML Workspace.\n",
|
||||||
"1. Creating an Experiment in an existing Workspace\n",
|
"\n",
|
||||||
"2. Instantiating AutoMLConfig with new task type \"forecasting\" for timeseries data training, and other timeseries related settings: for this dataset we use the basic one: \"time_column_name\" \n",
|
"In this notebook you will learn how to:\n",
|
||||||
"3. Training the Model using local compute\n",
|
"1. Creating an Experiment using an existing Workspace\n",
|
||||||
"4. Exploring the results\n",
|
"1. Configure AutoML using 'AutoMLConfig'\n",
|
||||||
"5. Viewing the engineered names for featurized data and featurization summary for all raw features\n",
|
"1. Train the model using AmlCompute\n",
|
||||||
"6. Testing the fitted model"
|
"1. Explore the engineered features and results\n",
|
||||||
|
"1. Configuration and remote run of AutoML for a time-series model with lag and rolling window features\n",
|
||||||
|
"1. Run and explore the forecast"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Setup\n"
|
"## Setup"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -61,27 +66,46 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import azureml.core\n",
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import logging\n",
|
|
||||||
"import warnings\n",
|
"import warnings\n",
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
"# Squash warning messages for cleaner output in the notebook\n",
|
"# Squash warning messages for cleaner output in the notebook\n",
|
||||||
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"import azureml.core\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core import Experiment, Workspace, Dataset\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"from matplotlib import pyplot as plt\n",
|
"from datetime import datetime"
|
||||||
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"As part of the setup you have already created a <b>Workspace</b>. For AutoML you would need to create an <b>Experiment</b>. An <b>Experiment</b> is a named object in a <b>Workspace</b>, which is used to run experiments."
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -93,19 +117,18 @@
|
|||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'automl-energydemandforecasting'\n",
|
"experiment_name = 'automl-forecasting-energydemand'\n",
|
||||||
"# project folder\n",
|
"\n",
|
||||||
"project_folder = './sample_projects/automl-local-energydemandforecasting'\n",
|
"# # project folder\n",
|
||||||
|
"# project_folder = './sample_projects/automl-forecasting-energy-demand'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output['Workspace'] = ws.name\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output['Location'] = ws.location\n",
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output['Run History Name'] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
@@ -116,8 +139,14 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Data\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"Read energy demanding data from file, and preview data."
|
"A compute target is required to execute a remote Automated ML run. \n",
|
||||||
|
"\n",
|
||||||
|
"[Azure Machine Learning Compute](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) is a managed-compute infrastructure that allows the user to easily create a single or multi-node compute. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -126,26 +155,45 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"data = pd.read_csv(\"nyc_energy.csv\", parse_dates=['timeStamp'])\n",
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
"data.head()"
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
]
|
"\n",
|
||||||
},
|
"# Choose a name for your cluster.\n",
|
||||||
{
|
"amlcompute_cluster_name = \"energy-cluster\"\n",
|
||||||
"cell_type": "code",
|
"\n",
|
||||||
"execution_count": null,
|
"# Verify that cluster does not exist already\n",
|
||||||
"metadata": {},
|
"try:\n",
|
||||||
"outputs": [],
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
"source": [
|
" print('Found existing cluster, use it.')\n",
|
||||||
"# let's take note of what columns means what in the data\n",
|
"except ComputeTargetException:\n",
|
||||||
"time_column_name = 'timeStamp'\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
||||||
"target_column_name = 'demand'"
|
" max_nodes=6)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Split the data into train and test sets\n"
|
"# Data\n",
|
||||||
|
"\n",
|
||||||
|
"We will use energy consumption [data from New York City](http://mis.nyiso.com/public/P-58Blist.htm) for model training. The data is stored in a tabular format and includes energy demand and basic weather data at an hourly frequency. \n",
|
||||||
|
"\n",
|
||||||
|
"With Azure Machine Learning datasets you can keep a single copy of data in your storage, easily access data during model training, share data and collaborate with other users. Below, we will upload the datatset and create a [tabular dataset](https://docs.microsoft.com/bs-latn-ba/azure/machine-learning/service/how-to-create-register-datasets#dataset-types) to be used training and prediction."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's set up what we know about the dataset.\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Target column</b> is what we want to forecast.<br></br>\n",
|
||||||
|
"<b>Time column</b> is the time axis along which to predict.\n",
|
||||||
|
"\n",
|
||||||
|
"The other columns, \"temp\" and \"precip\", are implicitly designated as features."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -154,10 +202,106 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"X_train = data[data[time_column_name] < '2017-02-01']\n",
|
"target_column_name = 'demand'\n",
|
||||||
"X_test = data[data[time_column_name] >= '2017-02-01']\n",
|
"time_column_name = 'timeStamp'"
|
||||||
"y_train = X_train.pop(target_column_name).values\n",
|
]
|
||||||
"y_test = X_test.pop(target_column_name).values"
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(path = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/nyc_energy.csv\").with_timestamp_columns(fine_grain_timestamp=time_column_name) \n",
|
||||||
|
"dataset.take(5).to_pandas_dataframe().reset_index(drop=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The NYC Energy dataset is missing energy demand values for all datetimes later than August 10th, 2017 5AM. Below, we trim the rows containing these missing values from the end of the dataset."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Cut off the end of the dataset due to large number of nan values\n",
|
||||||
|
"dataset = dataset.time_before(datetime(2017, 10, 10, 5))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Split the data into train and test sets"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The first split we make is into train and test sets. Note that we are splitting on time. Data before and including August 8th, 2017 5AM will be used for training, and data after will be used for testing."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# split into train based on time\n",
|
||||||
|
"train = dataset.time_before(datetime(2017, 8, 8, 5), include_boundary=True)\n",
|
||||||
|
"train.to_pandas_dataframe().reset_index(drop=True).sort_values(time_column_name).tail(5)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# split into test based on time\n",
|
||||||
|
"test = dataset.time_between(datetime(2017, 8, 8, 6), datetime(2017, 8, 10, 5))\n",
|
||||||
|
"test.to_pandas_dataframe().reset_index(drop=True).head(5)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Setting the maximum forecast horizon\n",
|
||||||
|
"\n",
|
||||||
|
"The forecast horizon is the number of periods into the future that the model should predict. It is generally recommend that users set forecast horizons to less than 100 time periods (i.e. less than 100 hours in the NYC energy example). Furthermore, **AutoML's memory use and computation time increase in proportion to the length of the horizon**, so consider carefully how this value is set. If a long horizon forecast really is necessary, consider aggregating the series to a coarser time scale. \n",
|
||||||
|
"\n",
|
||||||
|
"Learn more about forecast horizons in our [Auto-train a time-series forecast model](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-auto-train-forecast#configure-and-run-experiment) guide.\n",
|
||||||
|
"\n",
|
||||||
|
"In this example, we set the horizon to 48 hours."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"forecast_horizon = 48"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Forecasting Parameters\n",
|
||||||
|
"To define forecasting parameters for your experiment training, you can leverage the ForecastingParameters class. The table below details the forecasting parameter we will be passing into our experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**time_column_name**|The name of your time column.|\n",
|
||||||
|
"|**forecast_horizon**|The forecast horizon is how many periods forward you would like to forecast. This integer horizon is in units of the timeseries frequency (e.g. daily, weekly).|"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -166,18 +310,27 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Train\n",
|
"## Train\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
"Instantiate an AutoMLConfig object. This config defines the settings and data used to run the experiment. We can provide extra configurations within 'automl_settings', for this forecasting task we add the forecasting parameters to hold all the additional forecasting parameters.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"|Property|Description|\n",
|
"|Property|Description|\n",
|
||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
"|**task**|forecasting|\n",
|
"|**task**|forecasting|\n",
|
||||||
"|**primary_metric**|This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>\n",
|
"|**primary_metric**|This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
||||||
"|**iterations**|Number of iterations. In each iteration, Auto ML trains a specific pipeline on the given data|\n",
|
"|**blocked_models**|Models in blocked_models won't be used by AutoML. All supported models can be found at [here](https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.constants.supportedmodels.forecasting?view=azure-ml-py).|\n",
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
"|**experiment_timeout_hours**|Maximum amount of time in hours that the experiment take before it terminates.|\n",
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
"|**training_data**|The training data to be used within the experiment.|\n",
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
"|**compute_target**|The remote compute for training.|\n",
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder. "
|
"|**n_cross_validations**|Number of cross validation splits. Rolling Origin Validation is used to split time-series in a temporally consistent way.|\n",
|
||||||
|
"|**enable_early_stopping**|Flag to enble early termination if the score is not improving in the short term.|\n",
|
||||||
|
"|**forecasting_parameters**|A class holds all the forecasting related parameters.|\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This notebook uses the blocked_models parameter to exclude some models that take a longer time to train on this dataset. You can choose to remove models from the blocked_models list but you may need to increase the experiment_timeout_hours parameter value to get results."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -186,31 +339,30 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
" \"time_column_name\": time_column_name \n",
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
"}\n",
|
" time_column_name=time_column_name, forecast_horizon=forecast_horizon\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"automl_config = AutoMLConfig(task='forecasting', \n",
|
||||||
"automl_config = AutoMLConfig(task = 'forecasting',\n",
|
|
||||||
" debug_log = 'automl_nyc_energy_errors.log',\n",
|
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
" iterations = 10,\n",
|
" blocked_models = ['ExtremeRandomTrees', 'AutoArima', 'Prophet'], \n",
|
||||||
" iteration_timeout_minutes = 5,\n",
|
" experiment_timeout_hours=0.3,\n",
|
||||||
" X = X_train,\n",
|
" training_data=train,\n",
|
||||||
" y = y_train,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" n_cross_validations = 3,\n",
|
" compute_target=compute_target,\n",
|
||||||
" path=project_folder,\n",
|
" enable_early_stopping=True,\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" n_cross_validations=3, \n",
|
||||||
" **automl_settings)"
|
" verbosity=logging.INFO,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Submitting the configuration will start a new run in this experiment. For local runs, the execution is synchronous. Depending on the data and number of iterations, this can run for a while. Parameters controlling concurrency may speed up the process, depending on your hardware.\n",
|
"Call the `submit` method on the experiment object and pass the run configuration. Depending on the data and the number of iterations this can run for a while.\n",
|
||||||
"\n",
|
"One may specify `show_output = True` to print currently running iterations to the console."
|
||||||
"You will see the currently running iterations printing to the console."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -219,7 +371,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run = experiment.submit(automl_config, show_output=True)"
|
"remote_run = experiment.submit(automl_config, show_output=False)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -228,15 +380,24 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run"
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Retrieve the Best Model\n",
|
"## Retrieve the Best Model\n",
|
||||||
"Below we select the best pipeline from our iterations. The get_output method on automl_classifier returns the best run and the fitted model for the last fit invocation. There are overloads on get_output that allow you to retrieve the best run and fitted model for any logged metric or a particular iteration."
|
"Below we select the best model from all the training iterations using get_output method."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -245,7 +406,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
"fitted_model.steps"
|
"fitted_model.steps"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -253,8 +414,8 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### View the engineered names for featurized data\n",
|
"## Featurization\n",
|
||||||
"Below we display the engineered feature names generated for the featurized data using the time-series featurization."
|
"You can access the engineered feature names generated in time-series featurization."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -270,13 +431,53 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Test the Best Fitted Model\n",
|
"### View featurization summary\n",
|
||||||
|
"You can also see what featurization steps were performed on different raw features in the user data. For each raw feature in the user data, the following information is displayed:\n",
|
||||||
"\n",
|
"\n",
|
||||||
"For forecasting, we will use the `forecast` function instead of the `predict` function. There are two reasons for this.\n",
|
"+ Raw feature name\n",
|
||||||
"\n",
|
"+ Number of engineered features formed out of this raw feature\n",
|
||||||
"We need to pass the recent values of the target variable `y`, whereas the scikit-compatible `predict` function only takes the non-target variables `X`. In our case, the test data immediately follows the training data, and we fill the `y` variable with `NaN`. The `NaN` serves as a question mark for the forecaster to fill with the actuals. Using the forecast function will produce forecasts using the shortest possible forecast horizon. The last time at which a definite (non-NaN) value is seen is the _forecast origin_ - the last time when the value of the target is known. \n",
|
"+ Type detected\n",
|
||||||
"\n",
|
"+ If feature was dropped\n",
|
||||||
"Using the `predict` method would result in getting predictions for EVERY horizon the forecaster can predict at. This is useful when training and evaluating the performance of the forecaster at various horizons, but the level of detail is excessive for normal use."
|
"+ List of feature transformations for the raw feature"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Get the featurization summary as a list of JSON\n",
|
||||||
|
"featurization_summary = fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()\n",
|
||||||
|
"# View the featurization summary as a pandas dataframe\n",
|
||||||
|
"pd.DataFrame.from_records(featurization_summary)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Forecasting\n",
|
||||||
|
"\n",
|
||||||
|
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_test = test.to_pandas_dataframe().reset_index(drop=True)\n",
|
||||||
|
"y_test = X_test.pop(target_column_name).values"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Forecast Function\n",
|
||||||
|
"For forecasting, we will use the forecast function instead of the predict function. Using the predict method would result in getting predictions for EVERY horizon the forecaster can predict at. This is useful when training and evaluating the performance of the forecaster at various horizons, but the level of detail is excessive for normal use. Forecast function also can handle more complicated scenarios, see the [forecast function notebook](../forecasting-forecast-function/auto-ml-forecasting-function.ipynb)."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -285,15 +486,20 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Replace ALL values in y_pred by NaN. \n",
|
|
||||||
"# The forecast origin will be at the beginning of the first forecast period\n",
|
|
||||||
"# (which is the same time as the end of the last training period).\n",
|
|
||||||
"y_query = y_test.copy().astype(np.float)\n",
|
|
||||||
"y_query.fill(np.nan)\n",
|
|
||||||
"# The featurized data, aligned to y, will also be returned.\n",
|
"# The featurized data, aligned to y, will also be returned.\n",
|
||||||
"# This contains the assumptions that were made in the forecast\n",
|
"# This contains the assumptions that were made in the forecast\n",
|
||||||
"# and helps align the forecast to the original data\n",
|
"# and helps align the forecast to the original data\n",
|
||||||
"y_fcst, X_trans = fitted_model.forecast(X_test, y_query)"
|
"y_predictions, X_trans = fitted_model.forecast(X_test)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Evaluate\n",
|
||||||
|
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE).\n",
|
||||||
|
"\n",
|
||||||
|
"It is a good practice to always align the output explicitly to the input, as the count and order of the rows may have changed during transformations that span multiple rows."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -302,40 +508,37 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# limit the evaluation to data where y_test has actuals\n",
|
"from forecasting_helper import align_outputs\n",
|
||||||
"def align_outputs(y_predicted, X_trans, X_test, y_test, predicted_column_name = 'predicted'):\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" Demonstrates how to get the output aligned to the inputs\n",
|
|
||||||
" using pandas indexes. Helps understand what happened if\n",
|
|
||||||
" the output's shape differs from the input shape, or if\n",
|
|
||||||
" the data got re-sorted by time and grain during forecasting.\n",
|
|
||||||
" \n",
|
|
||||||
" Typical causes of misalignment are:\n",
|
|
||||||
" * we predicted some periods that were missing in actuals -> drop from eval\n",
|
|
||||||
" * model was asked to predict past max_horizon -> increase max horizon\n",
|
|
||||||
" * data at start of X_test was needed for lags -> provide previous periods\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" df_fcst = pd.DataFrame({predicted_column_name : y_predicted})\n",
|
|
||||||
" # y and X outputs are aligned by forecast() function contract\n",
|
|
||||||
" df_fcst.index = X_trans.index\n",
|
|
||||||
" \n",
|
|
||||||
" # align original X_test to y_test \n",
|
|
||||||
" X_test_full = X_test.copy()\n",
|
|
||||||
" X_test_full[target_column_name] = y_test\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
" # X_test_full's does not include origin, so reset for merge\n",
|
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
|
||||||
" df_fcst.reset_index(inplace=True)\n",
|
]
|
||||||
" X_test_full = X_test_full.reset_index().drop(columns='index')\n",
|
},
|
||||||
" together = df_fcst.merge(X_test_full, how='right')\n",
|
{
|
||||||
" \n",
|
"cell_type": "code",
|
||||||
" # drop rows where prediction or actuals are nan \n",
|
"execution_count": null,
|
||||||
" # happens because of missing actuals \n",
|
"metadata": {},
|
||||||
" # or at edges of time due to lags/rolling windows\n",
|
"outputs": [],
|
||||||
" clean = together[together[[target_column_name, predicted_column_name]].notnull().all(axis=1)]\n",
|
"source": [
|
||||||
" return(clean)\n",
|
"from azureml.automl.core.shared import constants\n",
|
||||||
|
"from azureml.automl.runtime.shared.score import scoring\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
"df_all = align_outputs(y_fcst, X_trans, X_test, y_test)\n",
|
"# use automl metrics module\n",
|
||||||
"df_all.head()"
|
"scores = scoring.score_regression(\n",
|
||||||
|
" y_test=df_all[target_column_name],\n",
|
||||||
|
" y_pred=df_all['predicted'],\n",
|
||||||
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
|
"for key, value in scores.items(): \n",
|
||||||
|
" print('{}: {:.3f}'.format(key, value))\n",
|
||||||
|
" \n",
|
||||||
|
"# Plot outputs\n",
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
|
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
||||||
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -358,7 +561,18 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Calculate accuracy metrics\n"
|
"## Advanced Training <a id=\"advanced_training\"></a>\n",
|
||||||
|
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Using lags and rolling window features\n",
|
||||||
|
"Now we will configure the target lags, that is the previous values of the target variables, meaning the prediction is no longer horizon-less. We therefore must still specify the `forecast_horizon` that the model will learn to forecast. The `target_lags` keyword specifies how far back we will construct the lags of the target variable, and the `target_rolling_window_size` specifies the size of the rolling window over which we will generate the `max`, `min` and `sum` features.\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook uses the blocked_models parameter to exclude some models that take a longer time to train on this dataset. You can choose to remove models from the blocked_models list but you may need to increase the iteration_timeout_minutes parameter value to get results."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -367,90 +581,29 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def MAPE(actual, pred):\n",
|
"advanced_forecasting_parameters = ForecastingParameters(\n",
|
||||||
" \"\"\"\n",
|
" time_column_name=time_column_name, forecast_horizon=forecast_horizon,\n",
|
||||||
" Calculate mean absolute percentage error.\n",
|
" target_lags=12, target_rolling_window_size=4\n",
|
||||||
" Remove NA and values where actual is close to zero\n",
|
")\n",
|
||||||
" \"\"\"\n",
|
|
||||||
" not_na = ~(np.isnan(actual) | np.isnan(pred))\n",
|
|
||||||
" not_zero = ~np.isclose(actual, 0.0)\n",
|
|
||||||
" actual_safe = actual[not_na & not_zero]\n",
|
|
||||||
" pred_safe = pred[not_na & not_zero]\n",
|
|
||||||
" APE = 100*np.abs((actual_safe - pred_safe)/actual_safe)\n",
|
|
||||||
" return np.mean(APE)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print(\"Simple forecasting model\")\n",
|
|
||||||
"rmse = np.sqrt(mean_squared_error(df_all[target_column_name], df_all['predicted']))\n",
|
|
||||||
"print(\"[Test Data] \\nRoot Mean squared error: %.2f\" % rmse)\n",
|
|
||||||
"mae = mean_absolute_error(df_all[target_column_name], df_all['predicted'])\n",
|
|
||||||
"print('mean_absolute_error score: %.2f' % mae)\n",
|
|
||||||
"print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"automl_config = AutoMLConfig(task='forecasting', \n",
|
||||||
"%matplotlib notebook\n",
|
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
|
||||||
"plt.show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"The distribution looks a little heavy tailed: we underestimate the excursions of the extremes. A normal-quantile transform of the target might help, but let's first try using some past data with the lags and rolling window transforms.\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Using lags and rolling window features to improve the forecast"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, grain and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data.\n",
|
|
||||||
"\n",
|
|
||||||
"Now that we configured target lags, that is the previous values of the target variables, and the prediction is no longer horizon-less. We therefore must specify the `max_horizon` that the model will learn to forecast. The `target_lags` keyword specifies how far back we will construct the lags of the target variable, and the `target_rolling_window_size` specifies the size of the rolling window over which we will generate the `max`, `min` and `sum` features."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_settings_lags = {\n",
|
|
||||||
" 'time_column_name': time_column_name,\n",
|
|
||||||
" 'target_lags': 1,\n",
|
|
||||||
" 'target_rolling_window_size': 5,\n",
|
|
||||||
" # you MUST set the max_horizon when using lags and rolling windows\n",
|
|
||||||
" # it is optional when looking-back features are not used \n",
|
|
||||||
" 'max_horizon': len(y_test), # only one grain\n",
|
|
||||||
"}\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"automl_config_lags = AutoMLConfig(task = 'forecasting',\n",
|
|
||||||
" debug_log = 'automl_nyc_energy_errors.log',\n",
|
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
" iterations = 10,\n",
|
" blocked_models = ['ElasticNet','ExtremeRandomTrees','GradientBoosting','XGBoostRegressor','ExtremeRandomTrees', 'AutoArima', 'Prophet'], #These models are blocked for tutorial purposes, remove this for real use cases. \n",
|
||||||
" iteration_timeout_minutes = 5,\n",
|
" experiment_timeout_hours=0.3,\n",
|
||||||
" X = X_train,\n",
|
" training_data=train,\n",
|
||||||
" y = y_train,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" n_cross_validations = 3,\n",
|
" compute_target=compute_target,\n",
|
||||||
" path=project_folder,\n",
|
" enable_early_stopping = True,\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" n_cross_validations=3, \n",
|
||||||
" **automl_settings_lags)"
|
" verbosity=logging.INFO,\n",
|
||||||
|
" forecasting_parameters=advanced_forecasting_parameters)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We now start a new remote run, this time with lag and rolling window featurization. AutoML applies featurizations in the setup stage, prior to iterating over ML models. The full training set is featurized first, followed by featurization of each of the CV splits. Lag and rolling window features introduce additional complexity, so the run will take longer than in the previous example that lacked these featurizations."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -459,7 +612,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run_lags = experiment.submit(automl_config_lags, show_output=True)"
|
"advanced_remote_run = experiment.submit(automl_config, show_output=False)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -468,10 +621,14 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run_lags, fitted_model_lags = local_run_lags.get_output()\n",
|
"advanced_remote_run.wait_for_completion()"
|
||||||
"y_fcst_lags, X_trans_lags = fitted_model_lags.forecast(X_test, y_query)\n",
|
]
|
||||||
"df_lags = align_outputs(y_fcst_lags, X_trans_lags, X_test, y_test)\n",
|
},
|
||||||
"df_lags.head()"
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve the Best Model"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -480,7 +637,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"X_trans_lags"
|
"best_run_lags, fitted_model_lags = advanced_remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Advanced Results<a id=\"advanced_results\"></a>\n",
|
||||||
|
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -489,60 +654,62 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"Forecasting model with lags\")\n",
|
"# The featurized data, aligned to y, will also be returned.\n",
|
||||||
"rmse = np.sqrt(mean_squared_error(df_lags[target_column_name], df_lags['predicted']))\n",
|
"# This contains the assumptions that were made in the forecast\n",
|
||||||
"print(\"[Test Data] \\nRoot Mean squared error: %.2f\" % rmse)\n",
|
"# and helps align the forecast to the original data\n",
|
||||||
"mae = mean_absolute_error(df_lags[target_column_name], df_lags['predicted'])\n",
|
"y_predictions, X_trans = fitted_model_lags.forecast(X_test)"
|
||||||
"print('mean_absolute_error score: %.2f' % mae)\n",
|
]
|
||||||
"print('MAPE: %.2f' % MAPE(df_lags[target_column_name], df_lags['predicted']))\n",
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from forecasting_helper import align_outputs\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.core.shared import constants\n",
|
||||||
|
"from azureml.automl.runtime.shared.score import scoring\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"\n",
|
||||||
|
"# use automl metrics module\n",
|
||||||
|
"scores = scoring.score_regression(\n",
|
||||||
|
" y_test=df_all[target_column_name],\n",
|
||||||
|
" y_pred=df_all['predicted'],\n",
|
||||||
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
|
"for key, value in scores.items(): \n",
|
||||||
|
" print('{}: {:.3f}'.format(key, value))\n",
|
||||||
|
" \n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib notebook\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_lags[target_column_name], df_lags['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### What features matter for the forecast?"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.train.automl.automlexplainer import explain_model\n",
|
|
||||||
"\n",
|
|
||||||
"# feature names are everything in the transformed data except the target\n",
|
|
||||||
"features = X_trans.columns[:-1]\n",
|
|
||||||
"expl = explain_model(fitted_model, X_train, X_test, features = features, best_run=best_run_lags, y_train = y_train)\n",
|
|
||||||
"# unpack the tuple\n",
|
|
||||||
"shap_values, expected_values, feat_overall_imp, feat_names, per_class_summary, per_class_imp = expl\n",
|
|
||||||
"best_run_lags"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Please go to the Azure Portal's best run to see the top features chart.\n",
|
|
||||||
"\n",
|
|
||||||
"The informative features make all sorts of intuitive sense. Temperature is a strong driver of heating and cooling demand in NYC. Apart from that, the daily life cycle, expressed by `hour`, and the weekly cycle, expressed by `wday` drives people's energy use habits."
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "xiaga, tosingli"
|
"name": "erwright"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
"display_name": "Python 3.6",
|
"display_name": "Python 3.6",
|
||||||
"language": "python",
|
"language": "python",
|
||||||
@@ -558,7 +725,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.7"
|
"version": "3.6.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-energy-demand
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import numpy as np
|
||||||
|
from pandas.tseries.frequencies import to_offset
|
||||||
|
|
||||||
|
|
||||||
|
def align_outputs(y_predicted, X_trans, X_test, y_test, target_column_name,
|
||||||
|
predicted_column_name='predicted',
|
||||||
|
horizon_colname='horizon_origin'):
|
||||||
|
"""
|
||||||
|
Demonstrates how to get the output aligned to the inputs
|
||||||
|
using pandas indexes. Helps understand what happened if
|
||||||
|
the output's shape differs from the input shape, or if
|
||||||
|
the data got re-sorted by time and grain during forecasting.
|
||||||
|
|
||||||
|
Typical causes of misalignment are:
|
||||||
|
* we predicted some periods that were missing in actuals -> drop from eval
|
||||||
|
* model was asked to predict past max_horizon -> increase max horizon
|
||||||
|
* data at start of X_test was needed for lags -> provide previous periods
|
||||||
|
"""
|
||||||
|
|
||||||
|
if (horizon_colname in X_trans):
|
||||||
|
df_fcst = pd.DataFrame({predicted_column_name: y_predicted,
|
||||||
|
horizon_colname: X_trans[horizon_colname]})
|
||||||
|
else:
|
||||||
|
df_fcst = pd.DataFrame({predicted_column_name: y_predicted})
|
||||||
|
|
||||||
|
# y and X outputs are aligned by forecast() function contract
|
||||||
|
df_fcst.index = X_trans.index
|
||||||
|
|
||||||
|
# align original X_test to y_test
|
||||||
|
X_test_full = X_test.copy()
|
||||||
|
X_test_full[target_column_name] = y_test
|
||||||
|
|
||||||
|
# X_test_full's index does not include origin, so reset for merge
|
||||||
|
df_fcst.reset_index(inplace=True)
|
||||||
|
X_test_full = X_test_full.reset_index().drop(columns='index')
|
||||||
|
together = df_fcst.merge(X_test_full, how='right')
|
||||||
|
|
||||||
|
# drop rows where prediction or actuals are nan
|
||||||
|
# happens because of missing actuals
|
||||||
|
# or at edges of time due to lags/rolling windows
|
||||||
|
clean = together[together[[target_column_name,
|
||||||
|
predicted_column_name]].notnull().all(axis=1)]
|
||||||
|
return(clean)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
def APE(actual, pred):
|
||||||
|
"""
|
||||||
|
Calculate absolute percentage error.
|
||||||
|
Returns a vector of APE values with same length as actual/pred.
|
||||||
|
"""
|
||||||
|
return 100 * np.abs((actual - pred) / actual)
|
||||||
|
|
||||||
|
|
||||||
|
def MAPE(actual, pred):
|
||||||
|
"""
|
||||||
|
Calculate mean absolute percentage error.
|
||||||
|
Remove NA and values where actual is close to zero
|
||||||
|
"""
|
||||||
|
not_na = ~(np.isnan(actual) | np.isnan(pred))
|
||||||
|
not_zero = ~np.isclose(actual, 0.0)
|
||||||
|
actual_safe = actual[not_na & not_zero]
|
||||||
|
pred_safe = pred[not_na & not_zero]
|
||||||
|
return np.mean(APE(actual_safe, pred_safe))
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,856 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"\n",
|
||||||
|
"#### Forecasting away from training data\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"2. [Setup](#Setup)\n",
|
||||||
|
"3. [Data](#Data)\n",
|
||||||
|
"4. [Prepare remote compute and data.](#prepare_remote)\n",
|
||||||
|
"4. [Create the configuration and train a forecaster](#train)\n",
|
||||||
|
"5. [Forecasting from the trained model](#forecasting)\n",
|
||||||
|
"6. [Forecasting away from training data](#forecasting_away)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"This notebook demonstrates the full interface to the `forecast()` function. \n",
|
||||||
|
"\n",
|
||||||
|
"The best known and most frequent usage of `forecast` enables forecasting on test sets that immediately follows training data. \n",
|
||||||
|
"\n",
|
||||||
|
"However, in many use cases it is necessary to continue using the model for some time before retraining it. This happens especially in **high frequency forecasting** when forecasts need to be made more frequently than the model can be retrained. Examples are in Internet of Things and predictive cloud resource scaling.\n",
|
||||||
|
"\n",
|
||||||
|
"Here we show how to use the `forecast()` function when a time gap exists between training data and prediction period.\n",
|
||||||
|
"\n",
|
||||||
|
"Terminology:\n",
|
||||||
|
"* forecast origin: the last period when the target value is known\n",
|
||||||
|
"* forecast periods(s): the period(s) for which the value of the target is desired.\n",
|
||||||
|
"* lookback: how many past periods (before forecast origin) the model function depends on. The larger of number of lags and length of rolling window.\n",
|
||||||
|
"* prediction context: `lookback` periods immediately preceding the forecast origin\n",
|
||||||
|
"\n",
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Please make sure you have followed the `configuration.ipynb` notebook so that your ML workspace information is saved in the config file."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import logging\n",
|
||||||
|
"import warnings\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"from pandas.tseries.frequencies import to_offset\n",
|
||||||
|
"from azureml.core.compute import AmlCompute\n",
|
||||||
|
"from azureml.core.compute import ComputeTarget\n",
|
||||||
|
"from azureml.core.runconfig import RunConfiguration\n",
|
||||||
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"\n",
|
||||||
|
"# Squash warning messages for cleaner output in the notebook\n",
|
||||||
|
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
||||||
|
"\n",
|
||||||
|
"np.set_printoptions(precision=4, suppress=True, linewidth=120)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"\n",
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a name for the run history container in the workspace\n",
|
||||||
|
"experiment_name = 'automl-forecast-function-demo'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['SKU'] = ws.sku\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Run History Name'] = experiment_name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Data\n",
|
||||||
|
"For the demonstration purposes we will generate the data artificially and use them for the forecasting."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"TIME_COLUMN_NAME = 'date'\n",
|
||||||
|
"TIME_SERIES_ID_COLUMN_NAME = 'time_series_id'\n",
|
||||||
|
"TARGET_COLUMN_NAME = 'y'\n",
|
||||||
|
"\n",
|
||||||
|
"def get_timeseries(train_len: int,\n",
|
||||||
|
" test_len: int,\n",
|
||||||
|
" time_column_name: str,\n",
|
||||||
|
" target_column_name: str,\n",
|
||||||
|
" time_series_id_column_name: str,\n",
|
||||||
|
" time_series_number: int = 1,\n",
|
||||||
|
" freq: str = 'H'):\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" Return the time series of designed length.\n",
|
||||||
|
"\n",
|
||||||
|
" :param train_len: The length of training data (one series).\n",
|
||||||
|
" :type train_len: int\n",
|
||||||
|
" :param test_len: The length of testing data (one series).\n",
|
||||||
|
" :type test_len: int\n",
|
||||||
|
" :param time_column_name: The desired name of a time column.\n",
|
||||||
|
" :type time_column_name: str\n",
|
||||||
|
" :param time_series_number: The number of time series in the data set.\n",
|
||||||
|
" :type time_series_number: int\n",
|
||||||
|
" :param freq: The frequency string representing pandas offset.\n",
|
||||||
|
" see https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html\n",
|
||||||
|
" :type freq: str\n",
|
||||||
|
" :returns: the tuple of train and test data sets.\n",
|
||||||
|
" :rtype: tuple\n",
|
||||||
|
"\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" data_train = [] # type: List[pd.DataFrame]\n",
|
||||||
|
" data_test = [] # type: List[pd.DataFrame]\n",
|
||||||
|
" data_length = train_len + test_len\n",
|
||||||
|
" for i in range(time_series_number):\n",
|
||||||
|
" X = pd.DataFrame({\n",
|
||||||
|
" time_column_name: pd.date_range(start='2000-01-01',\n",
|
||||||
|
" periods=data_length,\n",
|
||||||
|
" freq=freq),\n",
|
||||||
|
" target_column_name: np.arange(data_length).astype(float) + np.random.rand(data_length) + i*5,\n",
|
||||||
|
" 'ext_predictor': np.asarray(range(42, 42 + data_length)),\n",
|
||||||
|
" time_series_id_column_name: np.repeat('ts{}'.format(i), data_length)\n",
|
||||||
|
" })\n",
|
||||||
|
" data_train.append(X[:train_len])\n",
|
||||||
|
" data_test.append(X[train_len:])\n",
|
||||||
|
" X_train = pd.concat(data_train)\n",
|
||||||
|
" y_train = X_train.pop(target_column_name).values\n",
|
||||||
|
" X_test = pd.concat(data_test)\n",
|
||||||
|
" y_test = X_test.pop(target_column_name).values\n",
|
||||||
|
" return X_train, y_train, X_test, y_test\n",
|
||||||
|
"\n",
|
||||||
|
"n_test_periods = 6\n",
|
||||||
|
"n_train_periods = 30\n",
|
||||||
|
"X_train, y_train, X_test, y_test = get_timeseries(train_len=n_train_periods,\n",
|
||||||
|
" test_len=n_test_periods,\n",
|
||||||
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
|
" target_column_name=TARGET_COLUMN_NAME,\n",
|
||||||
|
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
||||||
|
" time_series_number=2)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's see what the training data looks like."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_train.tail()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# plot the example time series\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"whole_data = X_train.copy()\n",
|
||||||
|
"target_label = 'y'\n",
|
||||||
|
"whole_data[target_label] = y_train\n",
|
||||||
|
"for g in whole_data.groupby('time_series_id'): \n",
|
||||||
|
" plt.plot(g[1]['date'].values, g[1]['y'].values, label=g[0])\n",
|
||||||
|
"plt.legend()\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Prepare remote compute and data. <a id=\"prepare_remote\"></a>\n",
|
||||||
|
"The [Machine Learning service workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace), is paired with the storage account, which contains the default data store. We will use it to upload the artificial data and create [tabular dataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) for training. A tabular dataset defines a series of lazily-evaluated, immutable operations to load data from the data source into tabular representation."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# We need to save thw artificial data and then upload them to default workspace datastore.\n",
|
||||||
|
"DATA_PATH = \"fc_fn_data\"\n",
|
||||||
|
"DATA_PATH_X = \"{}/data_train.csv\".format(DATA_PATH)\n",
|
||||||
|
"if not os.path.isdir('data'):\n",
|
||||||
|
" os.mkdir('data')\n",
|
||||||
|
"pd.DataFrame(whole_data).to_csv(\"data/data_train.csv\", index=False)\n",
|
||||||
|
"# Upload saved data to the default data store.\n",
|
||||||
|
"ds = ws.get_default_datastore()\n",
|
||||||
|
"ds.upload(src_dir='./data', target_path=DATA_PATH, overwrite=True, show_progress=True)\n",
|
||||||
|
"train_data = Dataset.Tabular.from_delimited_files(path=ds.path(DATA_PATH_X))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"amlcompute_cluster_name = \"fcfn-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=6)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create the configuration and train a forecaster <a id=\"train\"></a>\n",
|
||||||
|
"First generate the configuration, in which we:\n",
|
||||||
|
"* Set metadata columns: target, time column and time-series id column names.\n",
|
||||||
|
"* Validate our data using cross validation with rolling window method.\n",
|
||||||
|
"* Set normalized root mean squared error as a metric to select the best model.\n",
|
||||||
|
"* Set early termination to True, so the iterations through the models will stop when no improvements in accuracy score will be made.\n",
|
||||||
|
"* Set limitations on the length of experiment run to 15 minutes.\n",
|
||||||
|
"* Finally, we set the task to be forecasting.\n",
|
||||||
|
"* We apply the lag lead operator to the target value i.e. we use the previous values as a predictor for the future ones."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
|
"lags = [1,2,3]\n",
|
||||||
|
"forecast_horizon = n_test_periods\n",
|
||||||
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
|
" forecast_horizon=forecast_horizon,\n",
|
||||||
|
" time_series_id_column_names=[ TIME_SERIES_ID_COLUMN_NAME ],\n",
|
||||||
|
" target_lags=lags\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Run the model selection and training process. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task='forecasting',\n",
|
||||||
|
" debug_log='automl_forecasting_function.log',\n",
|
||||||
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
|
" experiment_timeout_hours=0.25,\n",
|
||||||
|
" enable_early_stopping=True,\n",
|
||||||
|
" training_data=train_data,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" n_cross_validations=3,\n",
|
||||||
|
" verbosity = logging.INFO,\n",
|
||||||
|
" max_concurrent_iterations=4,\n",
|
||||||
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" label_column_name=target_label,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters)\n",
|
||||||
|
"\n",
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Retrieve the best model to use it further.\n",
|
||||||
|
"_, fitted_model = remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Forecasting from the trained model <a id=\"forecasting\"></a>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In this section we will review the `forecast` interface for two main scenarios: forecasting right after the training data, and the more complex interface for forecasting when there is a gap (in the time sense) between training and testing data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### X_train is directly followed by the X_test\n",
|
||||||
|
"\n",
|
||||||
|
"Let's first consider the case when the prediction period immediately follows the training data. This is typical in scenarios where we have the time to retrain the model every time we wish to forecast. Forecasts that are made on daily and slower cadence typically fall into this category. Retraining the model every time benefits the accuracy because the most recent data is often the most informative.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"We use `X_test` as a **forecast request** to generate the predictions."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Typical path: X_test is known, forecast all upcoming periods"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# The data set contains hourly data, the training set ends at 01/02/2000 at 05:00\n",
|
||||||
|
"\n",
|
||||||
|
"# These are predictions we are asking the model to make (does not contain thet target column y),\n",
|
||||||
|
"# for 6 periods beginning with 2000-01-02 06:00, which immediately follows the training data\n",
|
||||||
|
"X_test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_pred_no_gap, xy_nogap = fitted_model.forecast(X_test)\n",
|
||||||
|
"\n",
|
||||||
|
"# xy_nogap contains the predictions in the _automl_target_col column.\n",
|
||||||
|
"# Those same numbers are output in y_pred_no_gap\n",
|
||||||
|
"xy_nogap"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Confidence intervals"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Forecasting model may be used for the prediction of forecasting intervals by running ```forecast_quantiles()```. \n",
|
||||||
|
"This method accepts the same parameters as forecast()."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"quantiles = fitted_model.forecast_quantiles(X_test)\n",
|
||||||
|
"quantiles"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Distribution forecasts\n",
|
||||||
|
"\n",
|
||||||
|
"Often the figure of interest is not just the point prediction, but the prediction at some quantile of the distribution. \n",
|
||||||
|
"This arises when the forecast is used to control some kind of inventory, for example of grocery items or virtual machines for a cloud service. In such case, the control point is usually something like \"we want the item to be in stock and not run out 99% of the time\". This is called a \"service level\". Here is how you get quantile forecasts."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# specify which quantiles you would like \n",
|
||||||
|
"fitted_model.quantiles = [0.01, 0.5, 0.95]\n",
|
||||||
|
"# use forecast_quantiles function, not the forecast() one\n",
|
||||||
|
"y_pred_quantiles = fitted_model.forecast_quantiles(X_test)\n",
|
||||||
|
"\n",
|
||||||
|
"# quantile forecasts returned in a Dataframe along with the time and time series id columns \n",
|
||||||
|
"y_pred_quantiles"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Destination-date forecast: \"just do something\"\n",
|
||||||
|
"\n",
|
||||||
|
"In some scenarios, the X_test is not known. The forecast is likely to be weak, because it is missing contemporaneous predictors, which we will need to impute. If you still wish to predict forward under the assumption that the last known values will be carried forward, you can forecast out to \"destination date\". The destination date still needs to fit within the forecast horizon from training."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# We will take the destination date as a last date in the test set.\n",
|
||||||
|
"dest = max(X_test[TIME_COLUMN_NAME])\n",
|
||||||
|
"y_pred_dest, xy_dest = fitted_model.forecast(forecast_destination=dest)\n",
|
||||||
|
"\n",
|
||||||
|
"# This form also shows how we imputed the predictors which were not given. (Not so well! Use with caution!)\n",
|
||||||
|
"xy_dest"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Forecasting away from training data <a id=\"forecasting_away\"></a>\n",
|
||||||
|
"\n",
|
||||||
|
"Suppose we trained a model, some time passed, and now we want to apply the model without re-training. If the model \"looks back\" -- uses previous values of the target -- then we somehow need to provide those values to the model.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"The notion of forecast origin comes into play: the forecast origin is **the last period for which we have seen the target value**. This applies per time-series, so each time-series can have a different forecast origin. \n",
|
||||||
|
"\n",
|
||||||
|
"The part of data before the forecast origin is the **prediction context**. To provide the context values the model needs when it looks back, we pass definite values in `y_test` (aligned with corresponding times in `X_test`)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# generate the same kind of test data we trained on, \n",
|
||||||
|
"# but now make the train set much longer, so that the test set will be in the future\n",
|
||||||
|
"X_context, y_context, X_away, y_away = get_timeseries(train_len=42, # train data was 30 steps long\n",
|
||||||
|
" test_len=4,\n",
|
||||||
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
|
" target_column_name=TARGET_COLUMN_NAME,\n",
|
||||||
|
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
||||||
|
" time_series_number=2)\n",
|
||||||
|
"\n",
|
||||||
|
"# end of the data we trained on\n",
|
||||||
|
"print(X_train.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].max())\n",
|
||||||
|
"# start of the data we want to predict on\n",
|
||||||
|
"print(X_away.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].min())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"There is a gap of 12 hours between end of training and beginning of `X_away`. (It looks like 13 because all timestamps point to the start of the one hour periods.) Using only `X_away` will fail without adding context data for the model to consume."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"try: \n",
|
||||||
|
" y_pred_away, xy_away = fitted_model.forecast(X_away)\n",
|
||||||
|
" xy_away\n",
|
||||||
|
"except Exception as e:\n",
|
||||||
|
" print(e)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"How should we read that eror message? The forecast origin is at the last time the model saw an actual value of `y` (the target). That was at the end of the training data! The model is attempting to forecast from the end of training data. But the requested forecast periods are past the forecast horizon. We need to provide a define `y` value to establish the forecast origin.\n",
|
||||||
|
"\n",
|
||||||
|
"We will use this helper function to take the required amount of context from the data preceding the testing data. It's definition is intentionally simplified to keep the idea in the clear."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"def make_forecasting_query(fulldata, time_column_name, target_column_name, forecast_origin, horizon, lookback):\n",
|
||||||
|
"\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" This function will take the full dataset, and create the query\n",
|
||||||
|
" to predict all values of the time series from the `forecast_origin`\n",
|
||||||
|
" forward for the next `horizon` horizons. Context from previous\n",
|
||||||
|
" `lookback` periods will be included.\n",
|
||||||
|
"\n",
|
||||||
|
" \n",
|
||||||
|
"\n",
|
||||||
|
" fulldata: pandas.DataFrame a time series dataset. Needs to contain X and y.\n",
|
||||||
|
" time_column_name: string which column (must be in fulldata) is the time axis\n",
|
||||||
|
" target_column_name: string which column (must be in fulldata) is to be forecast\n",
|
||||||
|
" forecast_origin: datetime type the last time we (pretend to) have target values \n",
|
||||||
|
" horizon: timedelta how far forward, in time units (not periods)\n",
|
||||||
|
" lookback: timedelta how far back does the model look?\n",
|
||||||
|
"\n",
|
||||||
|
" Example:\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" ```\n",
|
||||||
|
"\n",
|
||||||
|
" forecast_origin = pd.to_datetime('2012-09-01') + pd.DateOffset(days=5) # forecast 5 days after end of training\n",
|
||||||
|
" print(forecast_origin)\n",
|
||||||
|
"\n",
|
||||||
|
" X_query, y_query = make_forecasting_query(data, \n",
|
||||||
|
" forecast_origin = forecast_origin,\n",
|
||||||
|
" horizon = pd.DateOffset(days=7), # 7 days into the future\n",
|
||||||
|
" lookback = pd.DateOffset(days=1), # model has lag 1 period (day)\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
" ```\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
"\n",
|
||||||
|
" X_past = fulldata[ (fulldata[ time_column_name ] > forecast_origin - lookback) &\n",
|
||||||
|
" (fulldata[ time_column_name ] <= forecast_origin)\n",
|
||||||
|
" ]\n",
|
||||||
|
"\n",
|
||||||
|
" X_future = fulldata[ (fulldata[ time_column_name ] > forecast_origin) &\n",
|
||||||
|
" (fulldata[ time_column_name ] <= forecast_origin + horizon)\n",
|
||||||
|
" ]\n",
|
||||||
|
"\n",
|
||||||
|
" y_past = X_past.pop(target_column_name).values.astype(np.float)\n",
|
||||||
|
" y_future = X_future.pop(target_column_name).values.astype(np.float)\n",
|
||||||
|
"\n",
|
||||||
|
" # Now take y_future and turn it into question marks\n",
|
||||||
|
" y_query = y_future.copy().astype(np.float) # because sometimes life hands you an int\n",
|
||||||
|
" y_query.fill(np.NaN)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" print(\"X_past is \" + str(X_past.shape) + \" - shaped\")\n",
|
||||||
|
" print(\"X_future is \" + str(X_future.shape) + \" - shaped\")\n",
|
||||||
|
" print(\"y_past is \" + str(y_past.shape) + \" - shaped\")\n",
|
||||||
|
" print(\"y_query is \" + str(y_query.shape) + \" - shaped\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" X_pred = pd.concat([X_past, X_future])\n",
|
||||||
|
" y_pred = np.concatenate([y_past, y_query])\n",
|
||||||
|
" return X_pred, y_pred"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's see where the context data ends - it ends, by construction, just before the testing data starts."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(X_context.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))\n",
|
||||||
|
"print(X_away.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))\n",
|
||||||
|
"X_context.tail(5)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Since the length of the lookback is 3, \n",
|
||||||
|
"# we need to add 3 periods from the context to the request\n",
|
||||||
|
"# so that the model has the data it needs\n",
|
||||||
|
"\n",
|
||||||
|
"# Put the X and y back together for a while. \n",
|
||||||
|
"# They like each other and it makes them happy.\n",
|
||||||
|
"X_context[TARGET_COLUMN_NAME] = y_context\n",
|
||||||
|
"X_away[TARGET_COLUMN_NAME] = y_away\n",
|
||||||
|
"fulldata = pd.concat([X_context, X_away])\n",
|
||||||
|
"\n",
|
||||||
|
"# forecast origin is the last point of data, which is one 1-hr period before test\n",
|
||||||
|
"forecast_origin = X_away[TIME_COLUMN_NAME].min() - pd.DateOffset(hours=1)\n",
|
||||||
|
"# it is indeed the last point of the context\n",
|
||||||
|
"assert forecast_origin == X_context[TIME_COLUMN_NAME].max()\n",
|
||||||
|
"print(\"Forecast origin: \" + str(forecast_origin))\n",
|
||||||
|
" \n",
|
||||||
|
"# the model uses lags and rolling windows to look back in time\n",
|
||||||
|
"n_lookback_periods = max(lags)\n",
|
||||||
|
"lookback = pd.DateOffset(hours=n_lookback_periods)\n",
|
||||||
|
"\n",
|
||||||
|
"horizon = pd.DateOffset(hours=forecast_horizon)\n",
|
||||||
|
"\n",
|
||||||
|
"# now make the forecast query from context (refer to figure)\n",
|
||||||
|
"X_pred, y_pred = make_forecasting_query(fulldata, TIME_COLUMN_NAME, TARGET_COLUMN_NAME,\n",
|
||||||
|
" forecast_origin, horizon, lookback)\n",
|
||||||
|
"\n",
|
||||||
|
"# show the forecast request aligned\n",
|
||||||
|
"X_show = X_pred.copy()\n",
|
||||||
|
"X_show[TARGET_COLUMN_NAME] = y_pred\n",
|
||||||
|
"X_show"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that the forecast origin is at 17:00 for both time-series, and periods from 18:00 are to be forecast."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Now everything works\n",
|
||||||
|
"y_pred_away, xy_away = fitted_model.forecast(X_pred, y_pred)\n",
|
||||||
|
"\n",
|
||||||
|
"# show the forecast aligned\n",
|
||||||
|
"X_show = xy_away.reset_index()\n",
|
||||||
|
"# without the generated features\n",
|
||||||
|
"X_show[['date', 'time_series_id', 'ext_predictor', '_automl_target_col']]\n",
|
||||||
|
"# prediction is in _automl_target_col"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Forecasting farther than the forecast horizon <a id=\"recursive forecasting\"></a>\n",
|
||||||
|
"When the forecast destination, or the latest date in the prediction data frame, is farther into the future than the specified forecast horizon, the `forecast()` function will still make point predictions out to the later date using a recursive operation mode. Internally, the method recursively applies the regular forecaster to generate context so that we can forecast further into the future. \n",
|
||||||
|
"\n",
|
||||||
|
"To illustrate the use-case and operation of recursive forecasting, we'll consider an example with a single time-series where the forecasting period directly follows the training period and is twice as long as the forecasting horizon given at training time.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"Internally, we apply the forecaster in an iterative manner and finish the forecast task in two interations. In the first iteration, we apply the forecaster and get the prediction for the first forecast-horizon periods (y_pred1). In the second iteraction, y_pred1 is used as the context to produce the prediction for the next forecast-horizon periods (y_pred2). The combination of (y_pred1 and y_pred2) gives the results for the total forecast periods. \n",
|
||||||
|
"\n",
|
||||||
|
"A caveat: forecast accuracy will likely be worse the farther we predict into the future since errors are compounded with recursive application of the forecaster.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# generate the same kind of test data we trained on, but with a single time-series and test period twice as long\n",
|
||||||
|
"# as the forecast_horizon.\n",
|
||||||
|
"_, _, X_test_long, y_test_long = get_timeseries(train_len=n_train_periods,\n",
|
||||||
|
" test_len=forecast_horizon*2,\n",
|
||||||
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
|
" target_column_name=TARGET_COLUMN_NAME,\n",
|
||||||
|
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
||||||
|
" time_series_number=1)\n",
|
||||||
|
"\n",
|
||||||
|
"print(X_test_long.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].min())\n",
|
||||||
|
"print(X_test_long.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].max())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# forecast() function will invoke the recursive forecast method internally.\n",
|
||||||
|
"y_pred_long, X_trans_long = fitted_model.forecast(X_test_long)\n",
|
||||||
|
"y_pred_long"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# What forecast() function does in this case is equivalent to iterating it twice over the test set as the following. \n",
|
||||||
|
"y_pred1, _ = fitted_model.forecast(X_test_long[:forecast_horizon])\n",
|
||||||
|
"y_pred_all, _ = fitted_model.forecast(X_test_long, np.concatenate((y_pred1, np.full(forecast_horizon, np.nan))))\n",
|
||||||
|
"np.array_equal(y_pred_all, y_pred_long)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Confidence interval and distributional forecasts\n",
|
||||||
|
"AutoML cannot currently estimate forecast errors beyond the forecast horizon set during training, so the `forecast_quantiles()` function will return missing values for quantiles not equal to 0.5 beyond the forecast horizon. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"fitted_model.forecast_quantiles(X_test_long)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Similarly with the simple senarios illustrated above, forecasting farther than the forecast horizon in other senarios like 'multiple time-series', 'Destination-date forecast', and 'forecast away from the training data' are also automatically handled by the `forecast()` function. "
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "erwright"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"Remote"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"framework": [
|
||||||
|
"Azure ML AutoML"
|
||||||
|
],
|
||||||
|
"friendly_name": "Forecasting away from training data",
|
||||||
|
"index_order": 3,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.8"
|
||||||
|
},
|
||||||
|
"tags": [
|
||||||
|
"Forecasting",
|
||||||
|
"Confidence Intervals"
|
||||||
|
],
|
||||||
|
"task": "Forecasting"
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-function
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -26,6 +26,7 @@
|
|||||||
"## Contents\n",
|
"## Contents\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#Introduction)\n",
|
||||||
"1. [Setup](#Setup)\n",
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Compute](#Compute)\n",
|
||||||
"1. [Data](#Data)\n",
|
"1. [Data](#Data)\n",
|
||||||
"1. [Train](#Train)\n",
|
"1. [Train](#Train)\n",
|
||||||
"1. [Predict](#Predict)\n",
|
"1. [Predict](#Predict)\n",
|
||||||
@@ -37,16 +38,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"In this example, we use AutoML to find and tune a time-series forecasting model.\n",
|
"In this example, we use AutoML to train, select, and operationalize a time-series forecasting model for multiple time-series.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook, you will:\n",
|
|
||||||
"1. Create an Experiment in an existing Workspace\n",
|
|
||||||
"2. Instantiate an AutoMLConfig \n",
|
|
||||||
"3. Find and train a forecasting model using local compute\n",
|
|
||||||
"4. Evaluate the performance of the model\n",
|
|
||||||
"\n",
|
|
||||||
"The examples in the follow code samples use the University of Chicago's Dominick's Finer Foods dataset to forecast orange juice sales. Dominick's was a grocery chain in the Chicago metropolitan area."
|
"The examples in the follow code samples use the University of Chicago's Dominick's Finer Foods dataset to forecast orange juice sales. Dominick's was a grocery chain in the Chicago metropolitan area."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -67,22 +62,35 @@
|
|||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"import warnings\n",
|
|
||||||
"# Squash warning messages for cleaner output in the notebook\n",
|
|
||||||
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"from sklearn.metrics import mean_absolute_error, mean_squared_error"
|
"from azureml.automl.core.featurization import FeaturizationConfig"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment is a named object in a Workspace which represents a predictive task, the output of which is a trained model and a set of evaluation metrics for the model. "
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem. "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -95,24 +103,56 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'automl-ojforecasting'\n",
|
"experiment_name = 'automl-ojforecasting'\n",
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-local-ojforecasting'\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['SKU'] = ws.sku\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output['Location'] = ws.location\n",
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output['Run History Name'] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
"outputDf.T"
|
"outputDf.T"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Compute\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read this article on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"amlcompute_cluster_name = \"oj-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=6)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -138,7 +178,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"Each row in the DataFrame holds a quantity of weekly sales for an OJ brand at a single store. The data also includes the sales price, a flag indicating if the OJ brand was advertised in the store that week, and some customer demographic information based on the store location. For historical reasons, the data also include the logarithm of the sales quantity. The Dominick's grocery data is commonly used to illustrate econometric modeling techniques where logarithms of quantities are generally preferred. \n",
|
"Each row in the DataFrame holds a quantity of weekly sales for an OJ brand at a single store. The data also includes the sales price, a flag indicating if the OJ brand was advertised in the store that week, and some customer demographic information based on the store location. For historical reasons, the data also include the logarithm of the sales quantity. The Dominick's grocery data is commonly used to illustrate econometric modeling techniques where logarithms of quantities are generally preferred. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"The task is now to build a time-series model for the _Quantity_ column. It is important to note that this dataset is comprised of many individual time-series - one for each unique combination of _Store_ and _Brand_. To distinguish the individual time-series, we thus define the **grain** - the columns whose values determine the boundaries between time-series: "
|
"The task is now to build a time-series model for the _Quantity_ column. It is important to note that this dataset is comprised of many individual time-series - one for each unique combination of _Store_ and _Brand_. To distinguish the individual time-series, we define the **time_series_id_column_names** - the columns whose values determine the boundaries between time-series: "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -147,8 +187,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"grain_column_names = ['Store', 'Brand']\n",
|
"time_series_id_column_names = ['Store', 'Brand']\n",
|
||||||
"nseries = data.groupby(grain_column_names).ngroups\n",
|
"nseries = data.groupby(time_series_id_column_names).ngroups\n",
|
||||||
"print('Data contains {0} individual time-series.'.format(nseries))"
|
"print('Data contains {0} individual time-series.'.format(nseries))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -167,7 +207,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"use_stores = [2, 5, 8]\n",
|
"use_stores = [2, 5, 8]\n",
|
||||||
"data_subset = data[data.Store.isin(use_stores)]\n",
|
"data_subset = data[data.Store.isin(use_stores)]\n",
|
||||||
"nseries = data_subset.groupby(grain_column_names).ngroups\n",
|
"nseries = data_subset.groupby(time_series_id_column_names).ngroups\n",
|
||||||
"print('Data subset contains {0} individual time-series.'.format(nseries))"
|
"print('Data subset contains {0} individual time-series.'.format(nseries))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -176,7 +216,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Data Splitting\n",
|
"### Data Splitting\n",
|
||||||
"We now split the data into a training and a testing set for later forecast evaluation. The test set will contain the final 20 weeks of observed sales for each time-series. The splits should be stratified by series, so we use a group-by statement on the grain columns."
|
"We now split the data into a training and a testing set for later forecast evaluation. The test set will contain the final 20 weeks of observed sales for each time-series. The splits should be stratified by series, so we use a group-by statement on the time series identifier columns."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -187,15 +227,69 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"n_test_periods = 20\n",
|
"n_test_periods = 20\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def split_last_n_by_grain(df, n):\n",
|
"def split_last_n_by_series_id(df, n):\n",
|
||||||
" \"\"\"Group df by grain and split on last n rows for each group.\"\"\"\n",
|
" \"\"\"Group df by series identifiers and split on last n rows for each group.\"\"\"\n",
|
||||||
" df_grouped = (df.sort_values(time_column_name) # Sort by ascending time\n",
|
" df_grouped = (df.sort_values(time_column_name) # Sort by ascending time\n",
|
||||||
" .groupby(grain_column_names, group_keys=False))\n",
|
" .groupby(time_series_id_column_names, group_keys=False))\n",
|
||||||
" df_head = df_grouped.apply(lambda dfg: dfg.iloc[:-n])\n",
|
" df_head = df_grouped.apply(lambda dfg: dfg.iloc[:-n])\n",
|
||||||
" df_tail = df_grouped.apply(lambda dfg: dfg.iloc[-n:])\n",
|
" df_tail = df_grouped.apply(lambda dfg: dfg.iloc[-n:])\n",
|
||||||
" return df_head, df_tail\n",
|
" return df_head, df_tail\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X_train, X_test = split_last_n_by_grain(data_subset, n_test_periods)"
|
"train, test = split_last_n_by_series_id(data_subset, n_test_periods)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Upload data to datastore\n",
|
||||||
|
"The [Machine Learning service workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace), is paired with the storage account, which contains the default data store. We will use it to upload the train and test data and create [tabular datasets](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) for training and testing. A tabular dataset defines a series of lazily-evaluated, immutable operations to load data from the data source into tabular representation."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"train.to_csv (r'./dominicks_OJ_train.csv', index = None, header=True)\n",
|
||||||
|
"test.to_csv (r'./dominicks_OJ_test.csv', index = None, header=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"datastore = ws.get_default_datastore()\n",
|
||||||
|
"datastore.upload_files(files = ['./dominicks_OJ_train.csv', './dominicks_OJ_test.csv'], target_path = 'dataset/', overwrite = True,show_progress = True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create dataset for training"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"train_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_train.csv'))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"train_dataset.to_pandas_dataframe().tail()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -207,11 +301,11 @@
|
|||||||
"For forecasting tasks, AutoML uses pre-processing and estimation steps that are specific to time-series. AutoML will undertake the following pre-processing steps:\n",
|
"For forecasting tasks, AutoML uses pre-processing and estimation steps that are specific to time-series. AutoML will undertake the following pre-processing steps:\n",
|
||||||
"* Detect time-series sample frequency (e.g. hourly, daily, weekly) and create new records for absent time points to make the series regular. A regular time series has a well-defined frequency and has a value at every sample point in a contiguous time span \n",
|
"* Detect time-series sample frequency (e.g. hourly, daily, weekly) and create new records for absent time points to make the series regular. A regular time series has a well-defined frequency and has a value at every sample point in a contiguous time span \n",
|
||||||
"* Impute missing values in the target (via forward-fill) and feature columns (using median column values) \n",
|
"* Impute missing values in the target (via forward-fill) and feature columns (using median column values) \n",
|
||||||
"* Create grain-based features to enable fixed effects across different series\n",
|
"* Create features based on time series identifiers to enable fixed effects across different series\n",
|
||||||
"* Create time-based features to assist in learning seasonal patterns\n",
|
"* Create time-based features to assist in learning seasonal patterns\n",
|
||||||
"* Encode categorical variables to numeric quantities\n",
|
"* Encode categorical variables to numeric quantities\n",
|
||||||
"\n",
|
"\n",
|
||||||
"AutoML will currently train a single, regression-type model across **all** time-series in a given training set. This allows the model to generalize across related series.\n",
|
"In this notebook, AutoML will train a single, regression-type model across **all** time-series in a given training set. This allows the model to generalize across related series. If you're looking for training multiple models for different time-series, please see the many-models notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"You are almost ready to start an AutoML training job. First, we need to separate the target column from the rest of the DataFrame: "
|
"You are almost ready to start an AutoML training job. First, we need to separate the target column from the rest of the DataFrame: "
|
||||||
]
|
]
|
||||||
@@ -222,8 +316,58 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"target_column_name = 'Quantity'\n",
|
"target_column_name = 'Quantity'"
|
||||||
"y_train = X_train.pop(target_column_name).values"
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Customization\n",
|
||||||
|
"\n",
|
||||||
|
"The featurization customization in forecasting is an advanced feature in AutoML which allows our customers to change the default forecasting featurization behaviors and column types through `FeaturizationConfig`. The supported scenarios include,\n",
|
||||||
|
"1. Column purposes update: Override feature type for the specified column. Currently supports DateTime, Categorical and Numeric. This customization can be used in the scenario that the type of the column cannot correctly reflect its purpose. Some numerical columns, for instance, can be treated as Categorical columns which need to be converted to categorical while some can be treated as epoch timestamp which need to be converted to datetime. To tell our SDK to correctly preprocess these columns, a configuration need to be add with the columns and their desired types.\n",
|
||||||
|
"2. Transformer parameters update: Currently supports parameter change for Imputer only. User can customize imputation methods. The supported imputing methods for target column are constant and ffill (forward fill). The supported imputing methods for feature columns are mean, median, most frequent, constant and ffill (forward fill). This customization can be used for the scenario that our customers know which imputation methods fit best to the input data. For instance, some datasets use NaN to represent 0 which the correct behavior should impute all the missing value with 0. To achieve this behavior, these columns need to be configured as constant imputation with `fill_value` 0.\n",
|
||||||
|
"3. Drop columns: Columns to drop from being featurized. These usually are the columns which are leaky or the columns contain no useful data.\n",
|
||||||
|
"\n",
|
||||||
|
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"sample-featurizationconfig-remarks"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"featurization_config = FeaturizationConfig()\n",
|
||||||
|
"featurization_config.drop_columns = ['logQuantity'] # 'logQuantity' is a leaky feature, so we remove it.\n",
|
||||||
|
"# Force the CPWVOL5 feature to be numeric type.\n",
|
||||||
|
"featurization_config.add_column_purpose('CPWVOL5', 'Numeric')\n",
|
||||||
|
"# Fill missing values in the target column, Quantity, with zeros.\n",
|
||||||
|
"featurization_config.add_transformer_params('Imputer', ['Quantity'], {\"strategy\": \"constant\", \"fill_value\": 0})\n",
|
||||||
|
"# Fill missing values in the INCOME column with median value.\n",
|
||||||
|
"featurization_config.add_transformer_params('Imputer', ['INCOME'], {\"strategy\": \"median\"})\n",
|
||||||
|
"# Fill missing values in the Price column with forward fill (last value carried forward).\n",
|
||||||
|
"featurization_config.add_transformer_params('Imputer', ['Price'], {\"strategy\": \"ffill\"})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Forecasting Parameters\n",
|
||||||
|
"To define forecasting parameters for your experiment training, you can leverage the ForecastingParameters class. The table below details the forecasting parameter we will be passing into our experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**time_column_name**|The name of your time column.|\n",
|
||||||
|
"|**forecast_horizon**|The forecast horizon is how many periods forward you would like to forecast. This integer horizon is in units of the timeseries frequency (e.g. daily, weekly).|\n",
|
||||||
|
"|**time_series_id_column_names**|The column names used to uniquely identify the time series in data that has multiple rows with the same timestamp. If the time series identifiers are not defined, the data set is assumed to be one time series.|"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -232,13 +376,20 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Train\n",
|
"## Train\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The AutoMLConfig object defines the settings and data for an AutoML training job. Here, we set necessary inputs like the task type, the number of AutoML iterations to try, the training data, and cross-validation parameters. \n",
|
"The [AutoMLConfig](https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.automlconfig.automlconfig?view=azure-ml-py) object defines the settings and data for an AutoML training job. Here, we set necessary inputs like the task type, the number of AutoML iterations to try, the training data, and cross-validation parameters.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"For forecasting tasks, there are some additional parameters that can be set: the name of the column holding the date/time, the grain column names, and the maximum forecast horizon. A time column is required for forecasting, while the grain is optional. If a grain is not given, AutoML assumes that the whole dataset is a single time-series. We also pass a list of columns to drop prior to modeling. The _logQuantity_ column is completely correlated with the target quantity, so it must be removed to prevent a target leak.\n",
|
"For forecasting tasks, there are some additional parameters that can be set in the `ForecastingParameters` class: the name of the column holding the date/time, the timeseries id column names, and the maximum forecast horizon. A time column is required for forecasting, while the time_series_id is optional. If time_series_id columns are not given, AutoML assumes that the whole dataset is a single time-series. We also pass a list of columns to drop prior to modeling. The _logQuantity_ column is completely correlated with the target quantity, so it must be removed to prevent a target leak.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The forecast horizon is given in units of the time-series frequency; for instance, the OJ series frequency is weekly, so a horizon of 20 means that a trained model will estimate sales up-to 20 weeks beyond the latest date in the training data for each series. In this example, we set the maximum horizon to the number of samples per series in the test set (n_test_periods). Generally, the value of this parameter will be dictated by business needs. For example, a demand planning organizaion that needs to estimate the next month of sales would set the horizon accordingly. \n",
|
"The forecast horizon is given in units of the time-series frequency; for instance, the OJ series frequency is weekly, so a horizon of 20 means that a trained model will estimate sales up to 20 weeks beyond the latest date in the training data for each series. In this example, we set the forecast horizon to the number of samples per series in the test set (n_test_periods). Generally, the value of this parameter will be dictated by business needs. For example, a demand planning application that estimates the next month of sales should set the horizon according to suitable planning time-scales. Please see the [energy_demand notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand) for more discussion of forecast horizon.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Finally, a note about the cross-validation (CV) procedure for time-series data. AutoML uses out-of-sample error estimates to select a best pipeline/model, so it is important that the CV fold splitting is done correctly. Time-series can violate the basic statistical assumptions of the canonical K-Fold CV strategy, so AutoML implements a [rolling origin validation](https://robjhyndman.com/hyndsight/tscv/) procedure to create CV folds for time-series data. To use this procedure, you just need to specify the desired number of CV folds in the AutoMLConfig object. It is also possible to bypass CV and use your own validation set by setting the *X_valid* and *y_valid* parameters of AutoMLConfig.\n",
|
"We note here that AutoML can sweep over two types of time-series models:\n",
|
||||||
|
"* Models that are trained for each series such as ARIMA and Facebook's Prophet. Note that these models are only available for [Enterprise Edition Workspaces](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-manage-workspace#upgrade).\n",
|
||||||
|
"* Models trained across multiple time-series using a regression approach.\n",
|
||||||
|
"\n",
|
||||||
|
"In the first case, AutoML loops over all time-series in your dataset and trains one model (e.g. AutoArima or Prophet, as the case may be) for each series. This can result in long runtimes to train these models if there are a lot of series in the data. One way to mitigate this problem is to fit models for different series in parallel if you have multiple compute cores available. To enable this behavior, set the `max_cores_per_iteration` parameter in your AutoMLConfig as shown in the example in the next cell. \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"Finally, a note about the cross-validation (CV) procedure for time-series data. AutoML uses out-of-sample error estimates to select a best pipeline/model, so it is important that the CV fold splitting is done correctly. Time-series can violate the basic statistical assumptions of the canonical K-Fold CV strategy, so AutoML implements a [rolling origin validation](https://robjhyndman.com/hyndsight/tscv/) procedure to create CV folds for time-series data. To use this procedure, you just need to specify the desired number of CV folds in the AutoMLConfig object. It is also possible to bypass CV and use your own validation set by setting the *validation_data* parameter of AutoMLConfig.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Here is a summary of AutoMLConfig parameters used for training the OJ model:\n",
|
"Here is a summary of AutoMLConfig parameters used for training the OJ model:\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -246,17 +397,17 @@
|
|||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
"|**task**|forecasting|\n",
|
"|**task**|forecasting|\n",
|
||||||
"|**primary_metric**|This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>\n",
|
"|**primary_metric**|This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>\n",
|
||||||
"|**iterations**|Number of iterations. In each iteration, Auto ML trains a specific pipeline on the given data|\n",
|
"|**experiment_timeout_hours**|Experimentation timeout in hours.|\n",
|
||||||
"|**X**|Training matrix of features as a pandas DataFrame, shape = [n_training_samples, n_features]|\n",
|
"|**enable_early_stopping**|If early stopping is on, training will stop when the primary metric is no longer improving.|\n",
|
||||||
"|**y**|Target values as a numpy.ndarray, shape = [n_training_samples, ]|\n",
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
|
"|**compute_target**|The remote compute for training.|\n",
|
||||||
"|**n_cross_validations**|Number of cross-validation folds to use for model/pipeline selection|\n",
|
"|**n_cross_validations**|Number of cross-validation folds to use for model/pipeline selection|\n",
|
||||||
"|**enable_ensembling**|Allow AutoML to create ensembles of the best performing models\n",
|
"|**enable_voting_ensemble**|Allow AutoML to create a Voting ensemble of the best performing models|\n",
|
||||||
"|**debug_log**|Log file path for writing debugging information\n",
|
"|**enable_stack_ensemble**|Allow AutoML to create a Stack ensemble of the best performing models|\n",
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n",
|
"|**debug_log**|Log file path for writing debugging information|\n",
|
||||||
"|**time_column_name**|Name of the datetime column in the input data|\n",
|
"|**featurization**| 'auto' / 'off' / FeaturizationConfig Indicator for whether featurization step should be done automatically or not, or whether customized featurization should be used. Setting this enables AutoML to perform featurization on the input to handle *missing data*, and to perform some common *feature extraction*.|\n",
|
||||||
"|**grain_column_names**|Name(s) of the columns defining individual series in the input data|\n",
|
"|**max_cores_per_iteration**|Maximum number of cores to utilize per iteration. A value of -1 indicates all available cores should be used"
|
||||||
"|**drop_column_names**|Name(s) of columns to drop prior to modeling|\n",
|
|
||||||
"|**max_horizon**|Maximum desired forecast horizon in units of time-series frequency|"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -265,32 +416,34 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"time_series_settings = {\n",
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
" 'time_column_name': time_column_name,\n",
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
" 'grain_column_names': grain_column_names,\n",
|
" time_column_name=time_column_name,\n",
|
||||||
" 'drop_column_names': ['logQuantity'],\n",
|
" forecast_horizon=n_test_periods,\n",
|
||||||
" 'max_horizon': n_test_periods # optional\n",
|
" time_series_id_column_names=time_series_id_column_names\n",
|
||||||
"}\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting',\n",
|
"automl_config = AutoMLConfig(task='forecasting',\n",
|
||||||
" debug_log='automl_oj_sales_errors.log',\n",
|
" debug_log='automl_oj_sales_errors.log',\n",
|
||||||
" primary_metric='normalized_mean_absolute_error',\n",
|
" primary_metric='normalized_mean_absolute_error',\n",
|
||||||
" iterations=10,\n",
|
" experiment_timeout_hours=0.25,\n",
|
||||||
" X=X_train,\n",
|
" training_data=train_dataset,\n",
|
||||||
" y=y_train,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" n_cross_validations=5,\n",
|
" compute_target=compute_target,\n",
|
||||||
" enable_ensembling=False,\n",
|
" enable_early_stopping=True,\n",
|
||||||
" path=project_folder,\n",
|
" featurization=featurization_config,\n",
|
||||||
|
" n_cross_validations=3,\n",
|
||||||
" verbosity=logging.INFO,\n",
|
" verbosity=logging.INFO,\n",
|
||||||
" **time_series_settings)"
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"You can now submit a new training run. For local runs, the execution is synchronous. Depending on the data and number of iterations this operation may take several minutes.\n",
|
"You can now submit a new training run. Depending on the data and number of iterations this operation may take several minutes.\n",
|
||||||
"Information from each iteration will be printed to the console."
|
"Information from each iteration will be printed to the console. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -299,7 +452,17 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run = experiment.submit(automl_config, show_output=True)"
|
"remote_run = experiment.submit(automl_config, show_output=False)\n",
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -316,15 +479,44 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_pipeline = local_run.get_output()\n",
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
"fitted_pipeline.steps"
|
"print(fitted_model.steps)\n",
|
||||||
|
"model_name = best_run.properties['model_name']"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Predict\n",
|
"## Transparency\n",
|
||||||
|
"\n",
|
||||||
|
"View updated featurization summary"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"custom_featurizer = fitted_model.named_steps['timeseriestransformer']"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"custom_featurizer.get_featurization_summary()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Forecasting\n",
|
||||||
|
"\n",
|
||||||
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
|
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -334,6 +526,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"X_test = test\n",
|
||||||
"y_test = X_test.pop(target_column_name).values"
|
"y_test = X_test.pop(target_column_name).values"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -350,9 +543,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"To produce predictions on the test set, we need to know the feature values at all dates in the test set. This requirement is somewhat reasonable for the OJ sales data since the features mainly consist of price, which is usually set in advance, and customer demographics which are approximately constant for each store over the 20 week forecast horizon in the testing data. \n",
|
"To produce predictions on the test set, we need to know the feature values at all dates in the test set. This requirement is somewhat reasonable for the OJ sales data since the features mainly consist of price, which is usually set in advance, and customer demographics which are approximately constant for each store over the 20 week forecast horizon in the testing data."
|
||||||
"\n",
|
|
||||||
"We will first create a query `y_query`, which is aligned index-for-index to `X_test`. This is a vector of target values where each `NaN` serves the function of the question mark to be replaced by forecast. Passing definite values in the `y` argument allows the `forecast` function to make predictions on data that does not immediately follow the train data which contains `y`. In each grain, the last time point where the model sees a definite value of `y` is that grain's _forecast origin_."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -361,15 +552,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Replace ALL values in y_pred by NaN.\n",
|
"# forecast returns the predictions and the featurized data, aligned to X_test.\n",
|
||||||
"# The forecast origin will be at the beginning of the first forecast period.\n",
|
|
||||||
"# (Which is the same time as the end of the last training period.)\n",
|
|
||||||
"y_query = y_test.copy().astype(np.float)\n",
|
|
||||||
"y_query.fill(np.nan)\n",
|
|
||||||
"# The featurized data, aligned to y, will also be returned.\n",
|
|
||||||
"# This contains the assumptions that were made in the forecast\n",
|
"# This contains the assumptions that were made in the forecast\n",
|
||||||
"# and helps align the forecast to the original data\n",
|
"y_predictions, X_trans = fitted_model.forecast(X_test)"
|
||||||
"y_pred, X_trans = fitted_pipeline.forecast(X_test, y_query)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -378,7 +563,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"If you are used to scikit pipelines, perhaps you expected `predict(X_test)`. However, forecasting requires a more general interface that also supplies the past target `y` values. Please use `forecast(X,y)` as `predict(X)` is reserved for internal purposes on forecasting models.\n",
|
"If you are used to scikit pipelines, perhaps you expected `predict(X_test)`. However, forecasting requires a more general interface that also supplies the past target `y` values. Please use `forecast(X,y)` as `predict(X)` is reserved for internal purposes on forecasting models.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The [energy demand forecasting notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand) demonstrates the use of the forecast function in more detail in the context of using lags and rolling window features. "
|
"The [forecast function notebook](../forecasting-forecast-function/auto-ml-forecasting-function.ipynb)."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -389,7 +574,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). \n",
|
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). \n",
|
||||||
"\n",
|
"\n",
|
||||||
"It is a good practice to always align the output explicitly to the input, as the count and order of the rows may have changed during transformations that span multiple rows."
|
"We'll add predictions and actuals into a single dataframe for convenience in calculating the metrics."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -398,39 +583,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def align_outputs(y_predicted, X_trans, X_test, y_test, predicted_column_name = 'predicted'):\n",
|
"assign_dict = {'predicted': y_predictions, target_column_name: y_test}\n",
|
||||||
" \"\"\"\n",
|
"df_all = X_test.assign(**assign_dict)"
|
||||||
" Demonstrates how to get the output aligned to the inputs\n",
|
|
||||||
" using pandas indexes. Helps understand what happened if\n",
|
|
||||||
" the output's shape differs from the input shape, or if\n",
|
|
||||||
" the data got re-sorted by time and grain during forecasting.\n",
|
|
||||||
" \n",
|
|
||||||
" Typical causes of misalignment are:\n",
|
|
||||||
" * we predicted some periods that were missing in actuals -> drop from eval\n",
|
|
||||||
" * model was asked to predict past max_horizon -> increase max horizon\n",
|
|
||||||
" * data at start of X_test was needed for lags -> provide previous periods in y\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" \n",
|
|
||||||
" df_fcst = pd.DataFrame({predicted_column_name : y_predicted})\n",
|
|
||||||
" # y and X outputs are aligned by forecast() function contract\n",
|
|
||||||
" df_fcst.index = X_trans.index\n",
|
|
||||||
" \n",
|
|
||||||
" # align original X_test to y_test \n",
|
|
||||||
" X_test_full = X_test.copy()\n",
|
|
||||||
" X_test_full[target_column_name] = y_test\n",
|
|
||||||
"\n",
|
|
||||||
" # X_test_full's index does not include origin, so reset for merge\n",
|
|
||||||
" df_fcst.reset_index(inplace=True)\n",
|
|
||||||
" X_test_full = X_test_full.reset_index().drop(columns='index')\n",
|
|
||||||
" together = df_fcst.merge(X_test_full, how='right')\n",
|
|
||||||
" \n",
|
|
||||||
" # drop rows where prediction or actuals are nan \n",
|
|
||||||
" # happens because of missing actuals \n",
|
|
||||||
" # or at edges of time due to lags/rolling windows\n",
|
|
||||||
" clean = together[together[[target_column_name, predicted_column_name]].notnull().all(axis=1)]\n",
|
|
||||||
" return(clean)\n",
|
|
||||||
"\n",
|
|
||||||
"df_all = align_outputs(y_pred, X_trans, X_test, y_test)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -439,38 +593,24 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def MAPE(actual, pred):\n",
|
"from azureml.automl.core.shared import constants\n",
|
||||||
" \"\"\"\n",
|
"from azureml.automl.runtime.shared.score import scoring\n",
|
||||||
" Calculate mean absolute percentage error.\n",
|
"from matplotlib import pyplot as plt\n",
|
||||||
" Remove NA and values where actual is close to zero\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" not_na = ~(np.isnan(actual) | np.isnan(pred))\n",
|
|
||||||
" not_zero = ~np.isclose(actual, 0.0)\n",
|
|
||||||
" actual_safe = actual[not_na & not_zero]\n",
|
|
||||||
" pred_safe = pred[not_na & not_zero]\n",
|
|
||||||
" APE = 100*np.abs((actual_safe - pred_safe)/actual_safe)\n",
|
|
||||||
" return np.mean(APE)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print(\"Simple forecasting model\")\n",
|
|
||||||
"rmse = np.sqrt(mean_squared_error(df_all[target_column_name], df_all['predicted']))\n",
|
|
||||||
"print(\"[Test Data] \\nRoot Mean squared error: %.2f\" % rmse)\n",
|
|
||||||
"mae = mean_absolute_error(df_all[target_column_name], df_all['predicted'])\n",
|
|
||||||
"print('mean_absolute_error score: %.2f' % mae)\n",
|
|
||||||
"print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
|
"# use automl scoring module\n",
|
||||||
|
"scores = scoring.score_regression(\n",
|
||||||
|
" y_test=df_all[target_column_name],\n",
|
||||||
|
" y_pred=df_all['predicted'],\n",
|
||||||
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
|
"for key, value in scores.items(): \n",
|
||||||
|
" print('{}: {:.3f}'.format(key, value))\n",
|
||||||
|
" \n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"%matplotlib inline\n",
|
||||||
"\n",
|
|
||||||
"%matplotlib notebook\n",
|
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -497,9 +637,9 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"description = 'AutoML OJ forecaster'\n",
|
"description = 'AutoML OJ forecaster'\n",
|
||||||
"tags = None\n",
|
"tags = None\n",
|
||||||
"model = local_run.register_model(description = description, tags = tags)\n",
|
"model = remote_run.register_model(model_name = model_name, description = description, tags = tags)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(local_run.model_id)"
|
"print(remote_run.model_id)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -508,7 +648,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"### Develop the scoring script\n",
|
"### Develop the scoring script\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Serializing and deserializing complex data frames may be tricky. We first develop the `run()` function of the scoring script locally, then write it into a scoring script. It is much easier to debug any quirks of the scoring function without crossing two compute environments. For this exercise, we handle a common quirk of how pandas dataframes serialize time stamp values."
|
"For the deployment we need a function which will run the forecast on serialized data. It can be obtained from the best_run."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -517,70 +657,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# this is where we test the run function of the scoring script interactively\n",
|
"script_file_name = 'score_fcast.py'\n",
|
||||||
"# before putting it in the scoring script\n",
|
"best_run.download_file('outputs/scoring_file_v_1_0_0.py', script_file_name)"
|
||||||
"\n",
|
|
||||||
"timestamp_columns = ['WeekStarting']\n",
|
|
||||||
"\n",
|
|
||||||
"def run(rawdata, test_model = None):\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" Intended to process 'rawdata' string produced by\n",
|
|
||||||
" \n",
|
|
||||||
" {'X': X_test.to_json(), y' : y_test.to_json()}\n",
|
|
||||||
" \n",
|
|
||||||
" Don't convert the X payload to numpy.array, use it as pandas.DataFrame\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" try:\n",
|
|
||||||
" # unpack the data frame with timestamp \n",
|
|
||||||
" rawobj = json.loads(rawdata) # rawobj is now a dict of strings \n",
|
|
||||||
" X_pred = pd.read_json(rawobj['X'], convert_dates=False) # load the pandas DF from a json string\n",
|
|
||||||
" for col in timestamp_columns: # fix timestamps\n",
|
|
||||||
" X_pred[col] = pd.to_datetime(X_pred[col], unit='ms') \n",
|
|
||||||
" \n",
|
|
||||||
" y_pred = np.array(rawobj['y']) # reconstitute numpy array from serialized list\n",
|
|
||||||
" \n",
|
|
||||||
" if test_model is None:\n",
|
|
||||||
" result = model.forecast(X_pred, y_pred) # use the global model from init function\n",
|
|
||||||
" else:\n",
|
|
||||||
" result = test_model.forecast(X_pred, y_pred) # use the model on which we are testing\n",
|
|
||||||
" \n",
|
|
||||||
" except Exception as e:\n",
|
|
||||||
" result = str(e)\n",
|
|
||||||
" return json.dumps({\"error\": result})\n",
|
|
||||||
" \n",
|
|
||||||
" forecast_as_list = result[0].tolist()\n",
|
|
||||||
" index_as_df = result[1].index.to_frame().reset_index(drop=True)\n",
|
|
||||||
" \n",
|
|
||||||
" return json.dumps({\"forecast\": forecast_as_list, # return the minimum over the wire: \n",
|
|
||||||
" \"index\": index_as_df.to_json() # no forecast and its featurized values\n",
|
|
||||||
" })"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# test the run function here before putting in the scoring script\n",
|
|
||||||
"import json\n",
|
|
||||||
"\n",
|
|
||||||
"test_sample = json.dumps({'X': X_test.to_json(), 'y' : y_query.tolist()})\n",
|
|
||||||
"response = run(test_sample, fitted_pipeline)\n",
|
|
||||||
"\n",
|
|
||||||
"# unpack the response, dealing with the timestamp serialization again\n",
|
|
||||||
"res_dict = json.loads(response)\n",
|
|
||||||
"y_fcst_all = pd.read_json(res_dict['index'])\n",
|
|
||||||
"y_fcst_all[time_column_name] = pd.to_datetime(y_fcst_all[time_column_name], unit = 'ms')\n",
|
|
||||||
"y_fcst_all['forecast'] = res_dict['forecast']\n",
|
|
||||||
"y_fcst_all.head()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Now that the function works locally in the notebook, let's write it down into the scoring script. The scoring script is authored by the data scientist. Adjust it to taste, adding inputs, outputs and processing as needed."
|
"### Deploy the model as a Web Service on Azure Container Instance"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -589,173 +674,24 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%writefile score_fcast.py\n",
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
"import pickle\n",
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
"import json\n",
|
"from azureml.core.webservice import Webservice\n",
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"import azureml.train.automl\n",
|
|
||||||
"from sklearn.externals import joblib\n",
|
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"inference_config = InferenceConfig(environment = best_run.get_environment(), \n",
|
||||||
"def init():\n",
|
" entry_script = script_file_name)\n",
|
||||||
" global model\n",
|
|
||||||
" model_path = Model.get_model_path(model_name = '<<modelid>>') # this name is model.id of model that we want to deploy\n",
|
|
||||||
" # deserialize the model file back into a sklearn model\n",
|
|
||||||
" model = joblib.load(model_path)\n",
|
|
||||||
"\n",
|
|
||||||
"timestamp_columns = ['WeekStarting']\n",
|
|
||||||
"\n",
|
|
||||||
"def run(rawdata, test_model = None):\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" Intended to process 'rawdata' string produced by\n",
|
|
||||||
" \n",
|
|
||||||
" {'X': X_test.to_json(), y' : y_test.to_json()}\n",
|
|
||||||
" \n",
|
|
||||||
" Don't convert the X payload to numpy.array, use it as pandas.DataFrame\n",
|
|
||||||
" \"\"\"\n",
|
|
||||||
" try:\n",
|
|
||||||
" # unpack the data frame with timestamp \n",
|
|
||||||
" rawobj = json.loads(rawdata) # rawobj is now a dict of strings \n",
|
|
||||||
" X_pred = pd.read_json(rawobj['X'], convert_dates=False) # load the pandas DF from a json string\n",
|
|
||||||
" for col in timestamp_columns: # fix timestamps\n",
|
|
||||||
" X_pred[col] = pd.to_datetime(X_pred[col], unit='ms') \n",
|
|
||||||
" \n",
|
|
||||||
" y_pred = np.array(rawobj['y']) # reconstitute numpy array from serialized list\n",
|
|
||||||
" \n",
|
|
||||||
" if test_model is None:\n",
|
|
||||||
" result = model.forecast(X_pred, y_pred) # use the global model from init function\n",
|
|
||||||
" else:\n",
|
|
||||||
" result = test_model.forecast(X_pred, y_pred) # use the model on which we are testing\n",
|
|
||||||
" \n",
|
|
||||||
" except Exception as e:\n",
|
|
||||||
" result = str(e)\n",
|
|
||||||
" return json.dumps({\"error\": result})\n",
|
|
||||||
" \n",
|
|
||||||
" # prepare to send over wire as json\n",
|
|
||||||
" forecast_as_list = result[0].tolist()\n",
|
|
||||||
" index_as_df = result[1].index.to_frame().reset_index(drop=True)\n",
|
|
||||||
" \n",
|
|
||||||
" return json.dumps({\"forecast\": forecast_as_list, # return the minimum over the wire: \n",
|
|
||||||
" \"index\": index_as_df.to_json() # no forecast and its featurized values\n",
|
|
||||||
" })"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# get the model\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"ml_run = AutoMLRun(experiment = experiment, run_id = local_run.id)\n",
|
|
||||||
"best_iteration = int(str.split(best_run.id,'_')[-1]) # the iteration number is a postfix of the run ID."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# get the best model's dependencies and write them into this file\n",
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"\n",
|
|
||||||
"conda_env_file_name = 'fcast_env.yml'\n",
|
|
||||||
"\n",
|
|
||||||
"dependencies = ml_run.get_run_sdk_dependencies(iteration = best_iteration)\n",
|
|
||||||
"for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n",
|
|
||||||
" print('{}\\t{}'.format(p, dependencies[p]))\n",
|
|
||||||
"\n",
|
|
||||||
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn'], pip_packages=['azureml-sdk[automl]'])\n",
|
|
||||||
"\n",
|
|
||||||
"myenv.save_to_file('.', conda_env_file_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# this is the script file name we wrote a few cells above\n",
|
|
||||||
"script_file_name = 'score_fcast.py'\n",
|
|
||||||
"\n",
|
|
||||||
"# Substitute the actual version number in the environment file.\n",
|
|
||||||
"# This is not strictly needed in this notebook because the model should have been generated using the current SDK version.\n",
|
|
||||||
"# However, we include this in case this code is used on an experiment from a previous SDK version.\n",
|
|
||||||
"\n",
|
|
||||||
"with open(conda_env_file_name, 'r') as cefr:\n",
|
|
||||||
" content = cefr.read()\n",
|
|
||||||
"\n",
|
|
||||||
"with open(conda_env_file_name, 'w') as cefw:\n",
|
|
||||||
" cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n",
|
|
||||||
"\n",
|
|
||||||
"# Substitute the actual model id in the script file.\n",
|
|
||||||
"\n",
|
|
||||||
"with open(script_file_name, 'r') as cefr:\n",
|
|
||||||
" content = cefr.read()\n",
|
|
||||||
"\n",
|
|
||||||
"with open(script_file_name, 'w') as cefw:\n",
|
|
||||||
" cefw.write(content.replace('<<modelid>>', local_run.model_id))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create a Container Image"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.image import Image, ContainerImage\n",
|
|
||||||
"\n",
|
|
||||||
"image_config = ContainerImage.image_configuration(runtime= \"python\",\n",
|
|
||||||
" execution_script = script_file_name,\n",
|
|
||||||
" conda_file = conda_env_file_name,\n",
|
|
||||||
" tags = {'type': \"automl-forecasting\"},\n",
|
|
||||||
" description = \"Image for automl forecasting sample\")\n",
|
|
||||||
"\n",
|
|
||||||
"image = Image.create(name = \"automl-fcast-image\",\n",
|
|
||||||
" # this is the model object \n",
|
|
||||||
" models = [model],\n",
|
|
||||||
" image_config = image_config, \n",
|
|
||||||
" workspace = ws)\n",
|
|
||||||
"\n",
|
|
||||||
"image.wait_for_creation(show_output = True)\n",
|
|
||||||
"\n",
|
|
||||||
"if image.creation_state == 'Failed':\n",
|
|
||||||
" print(\"Image build log at: \" + image.image_build_log_uri)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Deploy the Image as a Web Service on Azure Container Instance"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.webservice import AciWebservice\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
||||||
" memory_gb = 2, \n",
|
" memory_gb = 2, \n",
|
||||||
" tags = {'type': \"automl-forecasting\"},\n",
|
" tags = {'type': \"automl-forecasting\"},\n",
|
||||||
" description = \"Automl forecasting sample service\")"
|
" description = \"Automl forecasting sample service\")\n",
|
||||||
|
"\n",
|
||||||
|
"aci_service_name = 'automl-oj-forecast-01'\n",
|
||||||
|
"print(aci_service_name)\n",
|
||||||
|
"aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig)\n",
|
||||||
|
"aci_service.wait_for_deployment(True)\n",
|
||||||
|
"print(aci_service.state)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -764,17 +700,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.webservice import Webservice\n",
|
"aci_service.get_logs()"
|
||||||
"\n",
|
|
||||||
"aci_service_name = 'automl-forecast-01'\n",
|
|
||||||
"print(aci_service_name)\n",
|
|
||||||
"\n",
|
|
||||||
"aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n",
|
|
||||||
" image = image,\n",
|
|
||||||
" name = aci_service_name,\n",
|
|
||||||
" workspace = ws)\n",
|
|
||||||
"aci_service.wait_for_deployment(True)\n",
|
|
||||||
"print(aci_service.state)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -790,14 +716,18 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# we send the data to the service serialized into a json string\n",
|
"import json\n",
|
||||||
"test_sample = json.dumps({'X':X_test.to_json(), 'y' : y_query.tolist()})\n",
|
"X_query = X_test.copy()\n",
|
||||||
|
"# We have to convert datetime to string, because Timestamps cannot be serialized to JSON.\n",
|
||||||
|
"X_query[time_column_name] = X_query[time_column_name].astype(str)\n",
|
||||||
|
"# The Service object accept the complex dictionary, which is internally converted to JSON string.\n",
|
||||||
|
"# The section 'data' contains the data frame in the form of dictionary.\n",
|
||||||
|
"test_sample = json.dumps({'data': X_query.to_dict(orient='records')})\n",
|
||||||
"response = aci_service.run(input_data = test_sample)\n",
|
"response = aci_service.run(input_data = test_sample)\n",
|
||||||
"\n",
|
|
||||||
"# translate from networkese to datascientese\n",
|
"# translate from networkese to datascientese\n",
|
||||||
"try: \n",
|
"try: \n",
|
||||||
" res_dict = json.loads(response)\n",
|
" res_dict = json.loads(response)\n",
|
||||||
" y_fcst_all = pd.read_json(res_dict['index'])\n",
|
" y_fcst_all = pd.DataFrame(res_dict['index'])\n",
|
||||||
" y_fcst_all[time_column_name] = pd.to_datetime(y_fcst_all[time_column_name], unit = 'ms')\n",
|
" y_fcst_all[time_column_name] = pd.to_datetime(y_fcst_all[time_column_name], unit = 'ms')\n",
|
||||||
" y_fcst_all['forecast'] = res_dict['forecast'] \n",
|
" y_fcst_all['forecast'] = res_dict['forecast'] \n",
|
||||||
"except:\n",
|
"except:\n",
|
||||||
@@ -826,17 +756,34 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"serv = Webservice(ws, 'automl-forecast-01')\n",
|
"serv = Webservice(ws, 'automl-oj-forecast-01')\n",
|
||||||
"# serv.delete() # don't do it accidentally"
|
"serv.delete() # don't do it accidentally"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "erwright, tosingli"
|
"name": "erwright"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"celltoolbar": "Raw Cell Format",
|
||||||
|
"compute": [
|
||||||
|
"Remote"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"Orange Juice Sales"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"Azure Container Instance"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"framework": [
|
||||||
|
"Azure ML AutoML"
|
||||||
|
],
|
||||||
|
"friendly_name": "Forecasting orange juice sales with deployment",
|
||||||
|
"index_order": 1,
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
"display_name": "Python 3.6",
|
"display_name": "Python 3.6",
|
||||||
"language": "python",
|
"language": "python",
|
||||||
@@ -852,9 +799,13 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.7"
|
"version": "3.6.8"
|
||||||
}
|
},
|
||||||
|
"tags": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"task": "Forecasting"
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 2
|
"nbformat_minor": 4
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-orange-juice-sales
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,826 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Classification of credit card fraudulent transactions with local run **_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Tests)\n",
|
||||||
|
"1. [Explanation](#Explanation)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"In this example we use the associated credit card dataset to showcase how you can use AutoML for a simple classification problem. The goal is to predict if a credit card transaction is considered a fraudulent charge.\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook is using the local machine compute to train the model.\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"1. Create an experiment using an existing workspace.\n",
|
||||||
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"3. Train the model.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Test the fitted model.\n",
|
||||||
|
"6. Explore any model's explanation and explore feature importance in azure portal.\n",
|
||||||
|
"7. Create an AKS cluster, deploy the webservice of AutoML scoring model and the explainer model to the AKS and consume the web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"from azureml.interpret import ExplanationClient"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a name for experiment\n",
|
||||||
|
"experiment_name = 'automl-classification-ccard-local'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment=Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Experiment Name'] = experiment.name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"\n",
|
||||||
|
"Load the credit card dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/creditcard.csv\"\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
|
||||||
|
"training_data, validation_data = dataset.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"label_column_name = 'Class'"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification or regression|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
||||||
|
"|**enable_early_stopping**|Stop the run if the metric score is not showing improvement.|\n",
|
||||||
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
|
"\n",
|
||||||
|
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"primary_metric\": 'average_precision_score_weighted',\n",
|
||||||
|
" \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ability to find the best model possible\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
" \"enable_stack_ensemble\": False\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'classification',\n",
|
||||||
|
" debug_log = 'automl_errors.log',\n",
|
||||||
|
" training_data = training_data,\n",
|
||||||
|
" label_column_name = label_column_name,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Call the `submit` method on the experiment object and pass the run configuration. Depending on the data and the number of iterations this can run for a while.\n",
|
||||||
|
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"local_run = experiment.submit(automl_config, show_output = True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# If you need to retrieve a run that already started, use the following code\n",
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#local_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"local_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Widget for Monitoring Runs\n",
|
||||||
|
"\n",
|
||||||
|
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
||||||
|
"\n",
|
||||||
|
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.widgets import RunDetails\n",
|
||||||
|
"RunDetails(local_run).show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Analyze results\n",
|
||||||
|
"\n",
|
||||||
|
"#### Retrieve the Best Model\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, fitted_model = local_run.get_output()\n",
|
||||||
|
"fitted_model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Print the properties of the model\n",
|
||||||
|
"The fitted_model is a python object and you can read the different properties of the object.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Tests\n",
|
||||||
|
"\n",
|
||||||
|
"Now that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# convert the test data to dataframe\n",
|
||||||
|
"X_test_df = validation_data.drop_columns(columns=[label_column_name]).to_pandas_dataframe()\n",
|
||||||
|
"y_test_df = validation_data.keep_columns(columns=[label_column_name], validate=True).to_pandas_dataframe()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# call the predict functions on the model\n",
|
||||||
|
"y_pred = fitted_model.predict(X_test_df)\n",
|
||||||
|
"y_pred"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Calculate metrics for the prediction\n",
|
||||||
|
"\n",
|
||||||
|
"Now visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values \n",
|
||||||
|
"from the trained model that was returned."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.metrics import confusion_matrix\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import itertools\n",
|
||||||
|
"\n",
|
||||||
|
"cf =confusion_matrix(y_test_df.values,y_pred)\n",
|
||||||
|
"plt.imshow(cf,cmap=plt.cm.Blues,interpolation='nearest')\n",
|
||||||
|
"plt.colorbar()\n",
|
||||||
|
"plt.title('Confusion Matrix')\n",
|
||||||
|
"plt.xlabel('Predicted')\n",
|
||||||
|
"plt.ylabel('Actual')\n",
|
||||||
|
"class_labels = ['False','True']\n",
|
||||||
|
"tick_marks = np.arange(len(class_labels))\n",
|
||||||
|
"plt.xticks(tick_marks,class_labels)\n",
|
||||||
|
"plt.yticks([-0.5,0,1,1.5],['','False','True',''])\n",
|
||||||
|
"# plotting text value inside cells\n",
|
||||||
|
"thresh = cf.max() / 2.\n",
|
||||||
|
"for i,j in itertools.product(range(cf.shape[0]),range(cf.shape[1])):\n",
|
||||||
|
" plt.text(j,i,format(cf[i,j],'d'),horizontalalignment='center',color='white' if cf[i,j] >thresh else 'black')\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Explanation\n",
|
||||||
|
"In this section, we will show how to compute model explanations and visualize the explanations using azureml-interpret package. We will also show how to run the automl model and the explainer model through deploying an AKS web service.\n",
|
||||||
|
"\n",
|
||||||
|
"Besides retrieving an existing model explanation for an AutoML model, you can also explain your AutoML model with different test data. The following steps will allow you to compute and visualize engineered feature importance based on your test data.\n",
|
||||||
|
"\n",
|
||||||
|
"### Run the explanation\n",
|
||||||
|
"#### Download engineered feature importance from artifact store\n",
|
||||||
|
"You can use ExplanationClient to download the engineered feature explanations from the artifact store of the best_run. You can also use azure portal url to view the dash board visualization of the feature importance values of the engineered features."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"client = ExplanationClient.from_run(best_run)\n",
|
||||||
|
"engineered_explanations = client.download_model_explanation(raw=False)\n",
|
||||||
|
"print(engineered_explanations.get_feature_importance_dict())\n",
|
||||||
|
"print(\"You can visualize the engineered explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + best_run.get_portal_url())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Retrieve any other AutoML model from training"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_run, fitted_model = local_run.get_output(metric='accuracy')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Setup the model explanations for AutoML models\n",
|
||||||
|
"The fitted_model can generate the following which will be used for getting the engineered explanations using automl_setup_model_explanations:-\n",
|
||||||
|
"\n",
|
||||||
|
"1. Featurized data from train samples/test samples\n",
|
||||||
|
"2. Gather engineered name lists\n",
|
||||||
|
"3. Find the classes in your labeled column in classification scenarios\n",
|
||||||
|
"\n",
|
||||||
|
"The automl_explainer_setup_obj contains all the structures from above list."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_train = training_data.drop_columns(columns=[label_column_name])\n",
|
||||||
|
"y_train = training_data.keep_columns(columns=[label_column_name], validate=True)\n",
|
||||||
|
"X_test = validation_data.drop_columns(columns=[label_column_name])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations\n",
|
||||||
|
"\n",
|
||||||
|
"automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, X=X_train, \n",
|
||||||
|
" X_test=X_test, y=y_train, \n",
|
||||||
|
" task='classification')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Initialize the Mimic Explainer for feature importance\n",
|
||||||
|
"For explaining the AutoML models, use the MimicWrapper from azureml-interpret package. The MimicWrapper can be initialized with fields in automl_explainer_setup_obj, your workspace and a surrogate model to explain the AutoML model (fitted_model here). The MimicWrapper also takes the automl_run object where engineered explanations will be uploaded."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from interpret.ext.glassbox import LGBMExplainableModel\n",
|
||||||
|
"from azureml.interpret.mimic_wrapper import MimicWrapper\n",
|
||||||
|
"explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator,\n",
|
||||||
|
" explainable_model=automl_explainer_setup_obj.surrogate_model, \n",
|
||||||
|
" init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,\n",
|
||||||
|
" features=automl_explainer_setup_obj.engineered_feature_names, \n",
|
||||||
|
" feature_maps=[automl_explainer_setup_obj.feature_map],\n",
|
||||||
|
" classes=automl_explainer_setup_obj.classes,\n",
|
||||||
|
" explainer_kwargs=automl_explainer_setup_obj.surrogate_model_params)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Use Mimic Explainer for computing and visualizing engineered feature importance\n",
|
||||||
|
"The explain() method in MimicWrapper can be called with the transformed test samples to get the feature importance for the generated engineered features. You can also use azure portal url to view the dash board visualization of the feature importance values of the engineered features."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Compute the engineered explanations\n",
|
||||||
|
"engineered_explanations = explainer.explain(['local', 'global'], eval_dataset=automl_explainer_setup_obj.X_test_transform)\n",
|
||||||
|
"print(engineered_explanations.get_feature_importance_dict())\n",
|
||||||
|
"print(\"You can visualize the engineered explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + automl_run.get_portal_url())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Initialize the scoring Explainer, save and upload it for later use in scoring explanation"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.interpret.scoring.scoring_explainer import TreeScoringExplainer\n",
|
||||||
|
"import joblib\n",
|
||||||
|
"\n",
|
||||||
|
"# Initialize the ScoringExplainer\n",
|
||||||
|
"scoring_explainer = TreeScoringExplainer(explainer.explainer, feature_maps=[automl_explainer_setup_obj.feature_map])\n",
|
||||||
|
"\n",
|
||||||
|
"# Pickle scoring explainer locally to './scoring_explainer.pkl'\n",
|
||||||
|
"scoring_explainer_file_name = 'scoring_explainer.pkl'\n",
|
||||||
|
"with open(scoring_explainer_file_name, 'wb') as stream:\n",
|
||||||
|
" joblib.dump(scoring_explainer, stream)\n",
|
||||||
|
"\n",
|
||||||
|
"# Upload the scoring explainer to the automl run\n",
|
||||||
|
"automl_run.upload_file('outputs/scoring_explainer.pkl', scoring_explainer_file_name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Deploying the scoring and explainer models to a web service to Azure Kubernetes Service (AKS)\n",
|
||||||
|
"\n",
|
||||||
|
"We use the TreeScoringExplainer from azureml.interpret package to create the scoring explainer which will be used to compute the raw and engineered feature importances at the inference time. In the cell below, we register the AutoML model and the scoring explainer with the Model Management Service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Register trained automl model present in the 'outputs' folder in the artifacts\n",
|
||||||
|
"original_model = automl_run.register_model(model_name='automl_model', \n",
|
||||||
|
" model_path='outputs/model.pkl')\n",
|
||||||
|
"scoring_explainer_model = automl_run.register_model(model_name='scoring_explainer',\n",
|
||||||
|
" model_path='outputs/scoring_explainer.pkl')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Create the conda dependencies for setting up the service\n",
|
||||||
|
"\n",
|
||||||
|
"We need to download the conda dependencies using the automl_run object."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.core.shared import constants\n",
|
||||||
|
"from azureml.core.environment import Environment\n",
|
||||||
|
"\n",
|
||||||
|
"automl_run.download_file(constants.CONDA_ENV_FILE_PATH, 'myenv.yml')\n",
|
||||||
|
"myenv = Environment.from_conda_specification(name=\"myenv\", file_path=\"myenv.yml\")\n",
|
||||||
|
"myenv"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Write the Entry Script\n",
|
||||||
|
"Write the script that will be used to predict on your model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%%writefile score.py\n",
|
||||||
|
"import joblib\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def init():\n",
|
||||||
|
" global automl_model\n",
|
||||||
|
" global scoring_explainer\n",
|
||||||
|
"\n",
|
||||||
|
" # Retrieve the path to the model file using the model name\n",
|
||||||
|
" # Assume original model is named original_prediction_model\n",
|
||||||
|
" automl_model_path = Model.get_model_path('automl_model')\n",
|
||||||
|
" scoring_explainer_path = Model.get_model_path('scoring_explainer')\n",
|
||||||
|
"\n",
|
||||||
|
" automl_model = joblib.load(automl_model_path)\n",
|
||||||
|
" scoring_explainer = joblib.load(scoring_explainer_path)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def run(raw_data):\n",
|
||||||
|
" data = pd.read_json(raw_data, orient='records') \n",
|
||||||
|
" # Make prediction\n",
|
||||||
|
" predictions = automl_model.predict(data)\n",
|
||||||
|
" # Setup for inferencing explanations\n",
|
||||||
|
" automl_explainer_setup_obj = automl_setup_model_explanations(automl_model,\n",
|
||||||
|
" X_test=data, task='classification')\n",
|
||||||
|
" # Retrieve model explanations for engineered explanations\n",
|
||||||
|
" engineered_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform) \n",
|
||||||
|
" # You can return any data type as long as it is JSON-serializable\n",
|
||||||
|
" return {'predictions': predictions.tolist(),\n",
|
||||||
|
" 'engineered_local_importance_values': engineered_local_importance_values}\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Create the InferenceConfig \n",
|
||||||
|
"Create the inference config that will be used when deploying the model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
|
"\n",
|
||||||
|
"inf_config = InferenceConfig(entry_script='score.py', environment=myenv)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Provision the AKS Cluster\n",
|
||||||
|
"This is a one time setup. You can reuse this cluster for multiple deployments after it has been created. If you delete the cluster or the resource group that contains it, then you would have to recreate it."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AksCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your cluster.\n",
|
||||||
|
"aks_name = 'scoring-explain'\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" aks_target = ComputeTarget(workspace=ws, name=aks_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" prov_config = AksCompute.provisioning_configuration(vm_size='STANDARD_D3_V2')\n",
|
||||||
|
" aks_target = ComputeTarget.create(workspace=ws, \n",
|
||||||
|
" name=aks_name,\n",
|
||||||
|
" provisioning_configuration=prov_config)\n",
|
||||||
|
"aks_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Deploy web service to AKS"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Set the web service configuration (using default here)\n",
|
||||||
|
"from azureml.core.webservice import AksWebservice\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"\n",
|
||||||
|
"aks_config = AksWebservice.deploy_configuration()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"aks_service_name ='model-scoring-local-aks'\n",
|
||||||
|
"\n",
|
||||||
|
"aks_service = Model.deploy(workspace=ws,\n",
|
||||||
|
" name=aks_service_name,\n",
|
||||||
|
" models=[scoring_explainer_model, original_model],\n",
|
||||||
|
" inference_config=inf_config,\n",
|
||||||
|
" deployment_config=aks_config,\n",
|
||||||
|
" deployment_target=aks_target)\n",
|
||||||
|
"\n",
|
||||||
|
"aks_service.wait_for_deployment(show_output = True)\n",
|
||||||
|
"print(aks_service.state)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### View the service logs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"aks_service.get_logs()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Consume the web service using run method to do the scoring and explanation of scoring.\n",
|
||||||
|
"We test the web sevice by passing data. Run() method retrieves API keys behind the scenes to make sure that call is authenticated."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Serialize the first row of the test data into json\n",
|
||||||
|
"X_test_json = X_test_df[:1].to_json(orient='records')\n",
|
||||||
|
"print(X_test_json)\n",
|
||||||
|
"\n",
|
||||||
|
"# Call the service to get the predictions and the engineered and raw explanations\n",
|
||||||
|
"output = aks_service.run(X_test_json)\n",
|
||||||
|
"\n",
|
||||||
|
"# Print the predicted value\n",
|
||||||
|
"print('predictions:\\n{}\\n'.format(output['predictions']))\n",
|
||||||
|
"# Print the engineered feature importances for the predicted value\n",
|
||||||
|
"print('engineered_local_importance_values:\\n{}\\n'.format(output['engineered_local_importance_values']))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Clean up\n",
|
||||||
|
"Delete the service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"aks_service.delete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Acknowledgements"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This Credit Card fraud Detection dataset is made available under the Open Database License: http://opendatacommons.org/licenses/odbl/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: http://opendatacommons.org/licenses/dbcl/1.0/ and is available at: https://www.kaggle.com/mlg-ulb/creditcardfraud\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u0192\u00c2\u00a9 Libre de Bruxelles) on big data mining and fraud detection. More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
|
||||||
|
"Please cite the following works: \n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tAndrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
|
||||||
|
"o\tDal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "anumamah"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"Local"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"creditcard"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"exclude_from_index": true,
|
||||||
|
"file_extension": ".py",
|
||||||
|
"framework": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"friendly_name": "Classification of credit card fraudulent transactions using Automated ML",
|
||||||
|
"index_order": 5,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.7"
|
||||||
|
},
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"tags": [
|
||||||
|
"local_run",
|
||||||
|
"AutomatedML"
|
||||||
|
],
|
||||||
|
"task": "Classification",
|
||||||
|
"version": "3.6.7"
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-classification-credit-card-fraud-local
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -1,424 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Blacklisting Models, Early Termination, and Handling Missing Data**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for handling missing values in data. We also provide a stopping metric indicating a target for the primary metrics so that AutoML can terminate the run without necessarly going through all the iterations. Finally, if you want to avoid a certain pipeline, we allow you to specify a blacklist of algorithms that AutoML will ignore for this run.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"3. Train the model.\n",
|
|
||||||
"4. Explore the results.\n",
|
|
||||||
"5. Viewing the engineered names for featurized data and featurization summary for all raw features.\n",
|
|
||||||
"6. Test the best fitted model.\n",
|
|
||||||
"\n",
|
|
||||||
"In addition this notebook showcases the following features\n",
|
|
||||||
"- **Blacklisting** certain pipelines\n",
|
|
||||||
"- Specifying **target metrics** to indicate stopping criteria\n",
|
|
||||||
"- Handling **missing data** in the input"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for the experiment.\n",
|
|
||||||
"experiment_name = 'automl-local-missing-data'\n",
|
|
||||||
"project_folder = './sample_projects/automl-local-missing-data'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_train = digits.data[10:,:]\n",
|
|
||||||
"y_train = digits.target[10:]\n",
|
|
||||||
"\n",
|
|
||||||
"# Add missing values in 75% of the lines.\n",
|
|
||||||
"missing_rate = 0.75\n",
|
|
||||||
"n_missing_samples = int(np.floor(X_train.shape[0] * missing_rate))\n",
|
|
||||||
"missing_samples = np.hstack((np.zeros(X_train.shape[0] - n_missing_samples, dtype=np.bool), np.ones(n_missing_samples, dtype=np.bool)))\n",
|
|
||||||
"rng = np.random.RandomState(0)\n",
|
|
||||||
"rng.shuffle(missing_samples)\n",
|
|
||||||
"missing_features = rng.randint(0, X_train.shape[1], n_missing_samples)\n",
|
|
||||||
"X_train[np.where(missing_samples)[0], missing_features] = np.nan"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"df = pd.DataFrame(data = X_train)\n",
|
|
||||||
"df['Label'] = pd.Series(y_train, index=df.index)\n",
|
|
||||||
"df.head()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment. This includes setting `experiment_exit_score`, which should cause the run to complete before the `iterations` count is reached.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**preprocess**|Setting this to *True* enables AutoML to perform preprocessing on the input to handle *missing data*, and to perform some common *feature extraction*.|\n",
|
|
||||||
"|**experiment_exit_score**|*double* value indicating the target for *primary_metric*. <br>Once the target is surpassed the run terminates.|\n",
|
|
||||||
"|**blacklist_models**|*List* of *strings* indicating machine learning algorithms for AutoML to avoid in this run.<br><br> Allowed values for **Classification**<br><i>LogisticRegression</i><br><i>SGD</i><br><i>MultinomialNaiveBayes</i><br><i>BernoulliNaiveBayes</i><br><i>SVM</i><br><i>LinearSVM</i><br><i>KNN</i><br><i>DecisionTree</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>GradientBoosting</i><br><i>TensorFlowDNN</i><br><i>TensorFlowLinearClassifier</i><br><br>Allowed values for **Regression**<br><i>ElasticNet</i><br><i>GradientBoosting</i><br><i>DecisionTree</i><br><i>KNN</i><br><i>LassoLars</i><br><i>SGD</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>TensorFlowLinearRegressor</i><br><i>TensorFlowDNN</i>|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 60,\n",
|
|
||||||
" iterations = 20,\n",
|
|
||||||
" preprocess = True,\n",
|
|
||||||
" experiment_exit_score = 0.9984,\n",
|
|
||||||
" blacklist_models = ['KNN','LinearSVM'],\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(local_run).show() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"\n",
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model which has the smallest `accuracy` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# lookup_metric = \"accuracy\"\n",
|
|
||||||
"# best_run, fitted_model = local_run.get_output(metric = lookup_metric)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the third iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# iteration = 3\n",
|
|
||||||
"# best_run, fitted_model = local_run.get_output(iteration = iteration)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View the engineered names for featurized data\n",
|
|
||||||
"Below we display the engineered feature names generated for the featurized data using the preprocessing featurization."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"fitted_model.named_steps['datatransformer'].get_engineered_feature_names()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View the featurization summary\n",
|
|
||||||
"Below we display the featurization that was performed on different raw features in the user data. For each raw feature in the user data, the following information is displayed:-\n",
|
|
||||||
"- Raw feature name\n",
|
|
||||||
"- Number of engineered features formed out of this raw feature\n",
|
|
||||||
"- Type detected\n",
|
|
||||||
"- If feature was dropped\n",
|
|
||||||
"- List of feature transformations for the raw feature"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"fitted_model.named_steps['datatransformer'].get_featurization_summary()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_test = digits.data[:10, :]\n",
|
|
||||||
"y_test = digits.target[:10]\n",
|
|
||||||
"images = digits.images[:10]\n",
|
|
||||||
"\n",
|
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
|
|
||||||
" fig = plt.figure(1, figsize=(3,3))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" plt.show()\n"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1,357 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Explain classification model and visualize the explanation**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we use the sklearn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) to showcase how you can use the AutoML Classifier for a simple classification problem.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you would see\n",
|
|
||||||
"1. Creating an Experiment in an existing Workspace\n",
|
|
||||||
"2. Instantiating AutoMLConfig\n",
|
|
||||||
"3. Training the Model using local compute and explain the model\n",
|
|
||||||
"4. Visualization model's feature importance in widget\n",
|
|
||||||
"5. Explore best model's explanation"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created a <b>Workspace</b>. For AutoML you would need to create an <b>Experiment</b>. An <b>Experiment</b> is a named object in a <b>Workspace</b>, which is used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# choose a name for experiment\n",
|
|
||||||
"experiment_name = 'automl-model-explanation'\n",
|
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-model-explanation'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment=Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"iris = datasets.load_iris()\n",
|
|
||||||
"y = iris.target\n",
|
|
||||||
"X = iris.data\n",
|
|
||||||
"\n",
|
|
||||||
"features = iris.feature_names\n",
|
|
||||||
"\n",
|
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
|
||||||
"X_train, X_test, y_train, y_test = train_test_split(X,\n",
|
|
||||||
" y,\n",
|
|
||||||
" test_size=0.1,\n",
|
|
||||||
" random_state=100,\n",
|
|
||||||
" stratify=y)\n",
|
|
||||||
"\n",
|
|
||||||
"X_train = pd.DataFrame(X_train, columns=features)\n",
|
|
||||||
"X_test = pd.DataFrame(X_test, columns=features)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**max_time_sec**|Time limit in minutes for each iterations|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration Auto ML trains the data with a specific pipeline|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**X_valid**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**model_explainability**|Indicate to explain each trained pipeline or not |\n",
|
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder. |"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 200,\n",
|
|
||||||
" iterations = 10,\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" X_valid = X_test,\n",
|
|
||||||
" y_valid = y_test,\n",
|
|
||||||
" model_explainability=True,\n",
|
|
||||||
" path=project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"You can call the submit method on the experiment object and pass the run configuration. For Local runs the execution is synchronous. Depending on the data and number of iterations this can run for while.\n",
|
|
||||||
"You will see the currently running iterations printing to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Widget for monitoring runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will sit on \"loading\" until the first iteration completed, then you will see an auto-updating graph and table show up. It refreshed once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"NOTE: The widget displays a link at the bottom. This links to a web-ui to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(local_run).show() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The *get_output* method on automl_classifier returns the best run and the fitted model for the last *fit* invocation. There are overloads on *get_output* that allow you to retrieve the best run and fitted model for *any* logged metric or a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Best Model 's explanation\n",
|
|
||||||
"\n",
|
|
||||||
"Retrieve the explanation from the best_run. And explanation information includes:\n",
|
|
||||||
"\n",
|
|
||||||
"1.\tshap_values: The explanation information generated by shap lib\n",
|
|
||||||
"2.\texpected_values: The expected value of the model applied to set of X_train data.\n",
|
|
||||||
"3.\toverall_summary: The model level feature importance values sorted in descending order\n",
|
|
||||||
"4.\toverall_imp: The feature names sorted in the same order as in overall_summary\n",
|
|
||||||
"5.\tper_class_summary: The class level feature importance values sorted in descending order. Only available for the classification case\n",
|
|
||||||
"6.\tper_class_imp: The feature names sorted in the same order as in per_class_summary. Only available for the classification case\n",
|
|
||||||
"\n",
|
|
||||||
"Note:- The **retrieve_model_explanation()** API only works in case AutoML has been configured with **'model_explainability'** flag set to **True**. "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.train.automl.automlexplainer import retrieve_model_explanation\n",
|
|
||||||
"\n",
|
|
||||||
"shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \\\n",
|
|
||||||
" retrieve_model_explanation(best_run)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print(overall_summary)\n",
|
|
||||||
"print(overall_imp)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print(per_class_summary)\n",
|
|
||||||
"print(per_class_imp)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Beside retrieve the existed model explanation information, explain the model with different train/test data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.train.automl.automlexplainer import explain_model\n",
|
|
||||||
"\n",
|
|
||||||
"shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \\\n",
|
|
||||||
" explain_model(fitted_model, X_train, X_test, features=features)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print(overall_summary)\n",
|
|
||||||
"print(overall_imp)"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "xif"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,958 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Regression with Aml Compute**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Data](#Data)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Test)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"In this example we use the Hardware Performance Dataset to showcase how you can use AutoML for a simple regression problem. The Regression goal is to predict the performance of certain combinations of hardware parts.\n",
|
||||||
|
"After training AutoML models for this regression data set, we show how you can compute model explanations on your remote compute using a sample explainer script.\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade) \n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
|
"2. Instantiating AutoMLConfig with FeaturizationConfig for customization\n",
|
||||||
|
"3. Train the model using remote compute.\n",
|
||||||
|
"4. Explore the results and featurization transparency options\n",
|
||||||
|
"5. Setup remote compute for computing the model explanations for a given AutoML model.\n",
|
||||||
|
"6. Start an AzureML experiment on your remote compute to compute explanations for an AutoML model.\n",
|
||||||
|
"7. Download the feature importance for engineered features and visualize the explanations for engineered features on azure portal. \n",
|
||||||
|
"8. Download the feature importance for raw features and visualize the explanations for raw features on azure portal. \n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"from matplotlib import pyplot as plt\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"import azureml.dataprep as dprep\n",
|
||||||
|
"from azureml.automl.core.featurization import FeaturizationConfig\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"from azureml.core.dataset import Dataset"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for the experiment.\n",
|
||||||
|
"experiment_name = 'automl-regression-hardware-explain'\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace Name'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Experiment Name'] = experiment.name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create or Attach existing AmlCompute\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
|
"\n",
|
||||||
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your cluster.\n",
|
||||||
|
"amlcompute_cluster_name = \"hardware-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Setup Training and Test Data for AutoML experiment\n",
|
||||||
|
"\n",
|
||||||
|
"Load the hardware dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model. We also register the datasets in your workspace using a name so that these datasets may be accessed from the remote compute."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = 'https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv'\n",
|
||||||
|
"\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
|
||||||
|
"\n",
|
||||||
|
"# Split the dataset into train and test datasets\n",
|
||||||
|
"train_data, test_data = dataset.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Register the train dataset with your workspace\n",
|
||||||
|
"train_data.register(workspace = ws, name = 'machineData_train_dataset',\n",
|
||||||
|
" description = 'hardware performance training data',\n",
|
||||||
|
" create_new_version=True)\n",
|
||||||
|
"\n",
|
||||||
|
"# Register the test dataset with your workspace\n",
|
||||||
|
"test_data.register(workspace = ws, name = 'machineData_test_dataset', description = 'hardware performance test data', create_new_version=True)\n",
|
||||||
|
"\n",
|
||||||
|
"label =\"ERP\"\n",
|
||||||
|
"\n",
|
||||||
|
"train_data.to_pandas_dataframe().head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification, regression or forecasting|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
||||||
|
"|**experiment_timeout_hours**| Maximum amount of time in hours that all iterations combined can take before the experiment terminates.|\n",
|
||||||
|
"|**enable_early_stopping**| Flag to enble early termination if the score is not improving in the short term.|\n",
|
||||||
|
"|**featurization**| 'auto' / 'off' / FeaturizationConfig Indicator for whether featurization step should be done automatically or not, or whether customized featurization should be used. Setting this enables AutoML to perform featurization on the input to handle *missing data*, and to perform some common *feature extraction*. Note: If the input data is sparse, featurization cannot be turned on.|\n",
|
||||||
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
|
"|**training_data**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
||||||
|
"|**label_column_name**|(sparse) array-like, shape = [n_samples, ], targets values.|"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Customization\n",
|
||||||
|
"\n",
|
||||||
|
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade). \n",
|
||||||
|
"\n",
|
||||||
|
"Supported customization includes:\n",
|
||||||
|
"1. Column purpose update: Override feature type for the specified column.\n",
|
||||||
|
"2. Transformer parameter update: Update parameters for the specified transformer. Currently supports Imputer and HashOneHotEncoder.\n",
|
||||||
|
"3. Drop columns: Columns to drop from being featurized.\n",
|
||||||
|
"4. Block transformers: Allow/Block transformers to be used on featurization process."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Create FeaturizationConfig object using API calls"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"sample-featurizationconfig-remarks2"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"featurization_config = FeaturizationConfig()\n",
|
||||||
|
"featurization_config.blocked_transformers = ['LabelEncoder']\n",
|
||||||
|
"#featurization_config.drop_columns = ['MMIN']\n",
|
||||||
|
"featurization_config.add_column_purpose('MYCT', 'Numeric')\n",
|
||||||
|
"featurization_config.add_column_purpose('VendorName', 'CategoricalHash')\n",
|
||||||
|
"#default strategy mean, add transformer param for for 3 columns\n",
|
||||||
|
"featurization_config.add_transformer_params('Imputer', ['CACH'], {\"strategy\": \"median\"})\n",
|
||||||
|
"featurization_config.add_transformer_params('Imputer', ['CHMIN'], {\"strategy\": \"median\"})\n",
|
||||||
|
"featurization_config.add_transformer_params('Imputer', ['PRP'], {\"strategy\": \"most_frequent\"})\n",
|
||||||
|
"#featurization_config.add_transformer_params('HashOneHotEncoder', [], {\"number_of_bits\": 3})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"sample-featurizationconfig-remarks3"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"enable_early_stopping\": True, \n",
|
||||||
|
" \"experiment_timeout_hours\" : 0.25,\n",
|
||||||
|
" \"max_concurrent_iterations\": 4,\n",
|
||||||
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
|
" \"n_cross_validations\": 5,\n",
|
||||||
|
" \"primary_metric\": 'normalized_root_mean_squared_error',\n",
|
||||||
|
" \"verbosity\": logging.INFO\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'regression',\n",
|
||||||
|
" debug_log = 'automl_errors.log',\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" featurization=featurization_config,\n",
|
||||||
|
" training_data = train_data,\n",
|
||||||
|
" label_column_name = label,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
||||||
|
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Run the following cell to access previous runs. Uncomment the cell below and update the run_id."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#remote_run = AutoMLRun(experiment=experiment, run_id='<run_ID_goes_here')\n",
|
||||||
|
"#remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, fitted_model = remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run_customized, fitted_model_customized = remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Transparency\n",
|
||||||
|
"\n",
|
||||||
|
"View updated featurization summary"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"custom_featurizer = fitted_model_customized.named_steps['datatransformer']"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"custom_featurizer.get_featurization_summary()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"is_user_friendly=False allows for more detailed summary for transforms being applied"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"custom_featurizer.get_featurization_summary(is_user_friendly=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"custom_featurizer.get_stats_feature_type_summary()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Widget for Monitoring Runs\n",
|
||||||
|
"\n",
|
||||||
|
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
||||||
|
"\n",
|
||||||
|
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.widgets import RunDetails\n",
|
||||||
|
"RunDetails(remote_run).show() "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Explanations\n",
|
||||||
|
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade). \n",
|
||||||
|
"This section will walk you through the workflow to compute model explanations for an AutoML model on your remote compute.\n",
|
||||||
|
"\n",
|
||||||
|
"### Retrieve any AutoML Model for explanations\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the some AutoML pipeline from our iterations. The `get_output` method returns the a AutoML run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_run, fitted_model = remote_run.get_output(metric='r2_score')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Setup model explanation run on the remote compute\n",
|
||||||
|
"The following section provides details on how to setup an AzureML experiment to run model explanations for an AutoML model on your remote compute."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Sample script used for computing explanations\n",
|
||||||
|
"View the sample script for computing the model explanations for your AutoML model on remote compute."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"with open('train_explainer.py', 'r') as cefr:\n",
|
||||||
|
" print(cefr.read())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Substitute values in your sample script\n",
|
||||||
|
"The following cell shows how you change the values in the sample script so that you can change the sample script according to your experiment and dataset."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import shutil\n",
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"# create script folder\n",
|
||||||
|
"script_folder = './sample_projects/automl-regression-hardware'\n",
|
||||||
|
"if not os.path.exists(script_folder):\n",
|
||||||
|
" os.makedirs(script_folder)\n",
|
||||||
|
"\n",
|
||||||
|
"# Copy the sample script to script folder.\n",
|
||||||
|
"shutil.copy('train_explainer.py', script_folder)\n",
|
||||||
|
"\n",
|
||||||
|
"# Create the explainer script that will run on the remote compute.\n",
|
||||||
|
"script_file_name = script_folder + '/train_explainer.py'\n",
|
||||||
|
"\n",
|
||||||
|
"# Open the sample script for modification\n",
|
||||||
|
"with open(script_file_name, 'r') as cefr:\n",
|
||||||
|
" content = cefr.read()\n",
|
||||||
|
"\n",
|
||||||
|
"# Replace the values in train_explainer.py file with the appropriate values\n",
|
||||||
|
"content = content.replace('<<experiment_name>>', automl_run.experiment.name) # your experiment name.\n",
|
||||||
|
"content = content.replace('<<run_id>>', automl_run.id) # Run-id of the AutoML run for which you want to explain the model.\n",
|
||||||
|
"content = content.replace('<<target_column_name>>', 'ERP') # Your target column name\n",
|
||||||
|
"content = content.replace('<<task>>', 'regression') # Training task type\n",
|
||||||
|
"# Name of your training dataset register with your workspace\n",
|
||||||
|
"content = content.replace('<<train_dataset_name>>', 'machineData_train_dataset') \n",
|
||||||
|
"# Name of your test dataset register with your workspace\n",
|
||||||
|
"content = content.replace('<<test_dataset_name>>', 'machineData_test_dataset')\n",
|
||||||
|
"\n",
|
||||||
|
"# Write sample file into your script folder.\n",
|
||||||
|
"with open(script_file_name, 'w') as cefw:\n",
|
||||||
|
" cefw.write(content)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Create conda configuration for model explanations experiment from automl_run object"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.runconfig import RunConfiguration\n",
|
||||||
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"import pkg_resources\n",
|
||||||
|
"\n",
|
||||||
|
"# create a new RunConfig object\n",
|
||||||
|
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Set compute target to AmlCompute\n",
|
||||||
|
"conda_run_config.target = compute_target\n",
|
||||||
|
"conda_run_config.environment.docker.enabled = True\n",
|
||||||
|
"\n",
|
||||||
|
"# specify CondaDependencies obj\n",
|
||||||
|
"conda_run_config.environment.python.conda_dependencies = automl_run.get_environment().python.conda_dependencies"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Submit the experiment for model explanations\n",
|
||||||
|
"Submit the experiment with the above `run_config` and the sample script for computing explanations."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Now submit a run on AmlCompute for model explanations\n",
|
||||||
|
"from azureml.core.script_run_config import ScriptRunConfig\n",
|
||||||
|
"\n",
|
||||||
|
"script_run_config = ScriptRunConfig(source_directory=script_folder,\n",
|
||||||
|
" script='train_explainer.py',\n",
|
||||||
|
" run_config=conda_run_config)\n",
|
||||||
|
"\n",
|
||||||
|
"run = experiment.submit(script_run_config)\n",
|
||||||
|
"\n",
|
||||||
|
"# Show run details\n",
|
||||||
|
"run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%%time\n",
|
||||||
|
"# Shows output of the run on stdout.\n",
|
||||||
|
"run.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Feature importance and visualizing explanation dashboard\n",
|
||||||
|
"In this section we describe how you can download the explanation results from the explanations experiment and visualize the feature importance for your AutoML model on the azure portal."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Download engineered feature importance from artifact store\n",
|
||||||
|
"You can use *ExplanationClient* to download the engineered feature explanations from the artifact store of the *automl_run*. You can also use azure portal url to view the dash board visualization of the feature importance values of the engineered features."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.interpret import ExplanationClient\n",
|
||||||
|
"client = ExplanationClient.from_run(automl_run)\n",
|
||||||
|
"engineered_explanations = client.download_model_explanation(raw=False, comment='engineered explanations')\n",
|
||||||
|
"print(engineered_explanations.get_feature_importance_dict())\n",
|
||||||
|
"print(\"You can visualize the engineered explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + automl_run.get_portal_url())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Download raw feature importance from artifact store\n",
|
||||||
|
"You can use *ExplanationClient* to download the raw feature explanations from the artifact store of the *automl_run*. You can also use azure portal url to view the dash board visualization of the feature importance values of the raw features."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"raw_explanations = client.download_model_explanation(raw=True, comment='raw explanations')\n",
|
||||||
|
"print(raw_explanations.get_feature_importance_dict())\n",
|
||||||
|
"print(\"You can visualize the raw explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + automl_run.get_portal_url())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Operationailze\n",
|
||||||
|
"In this section we will show how you can operationalize an AutoML model and the explainer which was used to compute the explanations in the previous section.\n",
|
||||||
|
"\n",
|
||||||
|
"### Register the AutoML model and the scoring explainer\n",
|
||||||
|
"We use the *TreeScoringExplainer* from *azureml-interpret* package to create the scoring explainer which will be used to compute the raw and engineered feature importances at the inference time. \n",
|
||||||
|
"In the cell below, we register the AutoML model and the scoring explainer with the Model Management Service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Register trained automl model present in the 'outputs' folder in the artifacts\n",
|
||||||
|
"original_model = automl_run.register_model(model_name='automl_model', \n",
|
||||||
|
" model_path='outputs/model.pkl')\n",
|
||||||
|
"scoring_explainer_model = automl_run.register_model(model_name='scoring_explainer',\n",
|
||||||
|
" model_path='outputs/scoring_explainer.pkl')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create the conda dependencies for setting up the service\n",
|
||||||
|
"We need to create the conda dependencies comprising of the *azureml* packages using the training environment from the *automl_run*."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"conda_dep = automl_run.get_environment().python.conda_dependencies\n",
|
||||||
|
"\n",
|
||||||
|
"with open(\"myenv.yml\",\"w\") as f:\n",
|
||||||
|
" f.write(conda_dep.serialize_to_string())\n",
|
||||||
|
"\n",
|
||||||
|
"with open(\"myenv.yml\",\"r\") as f:\n",
|
||||||
|
" print(f.read())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### View your scoring file"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"with open(\"score_explain.py\",\"r\") as f:\n",
|
||||||
|
" print(f.read())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Deploy the service\n",
|
||||||
|
"In the cell below, we deploy the service using the conda file and the scoring file from the previous steps. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import Webservice\n",
|
||||||
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"from azureml.core.environment import Environment\n",
|
||||||
|
"\n",
|
||||||
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
||||||
|
" memory_gb=1, \n",
|
||||||
|
" tags={\"data\": \"Machine Data\", \n",
|
||||||
|
" \"method\" : \"local_explanation\"}, \n",
|
||||||
|
" description='Get local explanations for Machine test data')\n",
|
||||||
|
"\n",
|
||||||
|
"myenv = Environment.from_conda_specification(name=\"myenv\", file_path=\"myenv.yml\")\n",
|
||||||
|
"inference_config = InferenceConfig(entry_script=\"score_explain.py\", environment=myenv)\n",
|
||||||
|
"\n",
|
||||||
|
"# Use configs and models generated above\n",
|
||||||
|
"service = Model.deploy(ws, 'model-scoring', [scoring_explainer_model, original_model], inference_config, aciconfig)\n",
|
||||||
|
"service.wait_for_deployment(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### View the service logs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"service.get_logs()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Inference using some test data\n",
|
||||||
|
"Inference using some test data to see the predicted value from autml model, view the engineered feature importance for the predicted value and raw feature importance for the predicted value."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if service.state == 'Healthy':\n",
|
||||||
|
" X_test = test_data.drop_columns([label]).to_pandas_dataframe()\n",
|
||||||
|
" # Serialize the first row of the test data into json\n",
|
||||||
|
" X_test_json = X_test[:1].to_json(orient='records')\n",
|
||||||
|
" print(X_test_json)\n",
|
||||||
|
" # Call the service to get the predictions and the engineered and raw explanations\n",
|
||||||
|
" output = service.run(X_test_json)\n",
|
||||||
|
" # Print the predicted value\n",
|
||||||
|
" print(output['predictions'])\n",
|
||||||
|
" # Print the engineered feature importances for the predicted value\n",
|
||||||
|
" print(output['engineered_local_importance_values'])\n",
|
||||||
|
" # Print the raw feature importances for the predicted value\n",
|
||||||
|
" print(output['raw_local_importance_values'])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Delete the service\n",
|
||||||
|
"Delete the service once you have finished inferencing."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"service.delete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# preview the first 3 rows of the dataset\n",
|
||||||
|
"\n",
|
||||||
|
"test_data = test_data.to_pandas_dataframe()\n",
|
||||||
|
"y_test = test_data['ERP'].fillna(0)\n",
|
||||||
|
"test_data = test_data.drop('ERP', 1)\n",
|
||||||
|
"test_data = test_data.fillna(0)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"train_data = train_data.to_pandas_dataframe()\n",
|
||||||
|
"y_train = train_data['ERP'].fillna(0)\n",
|
||||||
|
"train_data = train_data.drop('ERP', 1)\n",
|
||||||
|
"train_data = train_data.fillna(0)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_pred_train = fitted_model.predict(train_data)\n",
|
||||||
|
"y_residual_train = y_train - y_pred_train\n",
|
||||||
|
"\n",
|
||||||
|
"y_pred_test = fitted_model.predict(test_data)\n",
|
||||||
|
"y_residual_test = y_test - y_pred_test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"from sklearn.metrics import mean_squared_error, r2_score\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up a multi-plot chart.\n",
|
||||||
|
"f, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})\n",
|
||||||
|
"f.suptitle('Regression Residual Values', fontsize = 18)\n",
|
||||||
|
"f.set_figheight(6)\n",
|
||||||
|
"f.set_figwidth(16)\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of training set.\n",
|
||||||
|
"a0.axis([0, 360, -100, 100])\n",
|
||||||
|
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
|
||||||
|
"a0.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
||||||
|
"a0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\n",
|
||||||
|
"a0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)),fontsize = 12)\n",
|
||||||
|
"a0.set_xlabel('Training samples', fontsize = 12)\n",
|
||||||
|
"a0.set_ylabel('Residual Values', fontsize = 12)\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of test set.\n",
|
||||||
|
"a1.axis([0, 90, -100, 100])\n",
|
||||||
|
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
|
||||||
|
"a1.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
||||||
|
"a1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\n",
|
||||||
|
"a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)),fontsize = 12)\n",
|
||||||
|
"a1.set_xlabel('Test samples', fontsize = 12)\n",
|
||||||
|
"a1.set_yticklabels([])\n",
|
||||||
|
"\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"test_pred = plt.scatter(y_test, y_pred_test, color='')\n",
|
||||||
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "anumamah"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"AML"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"MachineData"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"ACI"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"framework": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"friendly_name": "Automated ML run with featurization and model explainability.",
|
||||||
|
"index_order": 5,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"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.6.7"
|
||||||
|
},
|
||||||
|
"tags": [
|
||||||
|
"featurization",
|
||||||
|
"explainability",
|
||||||
|
"remote_run",
|
||||||
|
"AutomatedML"
|
||||||
|
],
|
||||||
|
"task": "Regression"
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-regression-explanation-featurization
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import joblib
|
||||||
|
from azureml.core.model import Model
|
||||||
|
from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations
|
||||||
|
|
||||||
|
|
||||||
|
def init():
|
||||||
|
|
||||||
|
global automl_model
|
||||||
|
global scoring_explainer
|
||||||
|
|
||||||
|
# Retrieve the path to the model file using the model name
|
||||||
|
# Assume original model is named original_prediction_model
|
||||||
|
automl_model_path = Model.get_model_path('automl_model')
|
||||||
|
scoring_explainer_path = Model.get_model_path('scoring_explainer')
|
||||||
|
|
||||||
|
automl_model = joblib.load(automl_model_path)
|
||||||
|
scoring_explainer = joblib.load(scoring_explainer_path)
|
||||||
|
|
||||||
|
|
||||||
|
def run(raw_data):
|
||||||
|
# Get predictions and explanations for each data point
|
||||||
|
data = pd.read_json(raw_data, orient='records')
|
||||||
|
# Make prediction
|
||||||
|
predictions = automl_model.predict(data)
|
||||||
|
# Setup for inferencing explanations
|
||||||
|
automl_explainer_setup_obj = automl_setup_model_explanations(automl_model,
|
||||||
|
X_test=data, task='regression')
|
||||||
|
# Retrieve model explanations for engineered explanations
|
||||||
|
engineered_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform)
|
||||||
|
# Retrieve model explanations for raw explanations
|
||||||
|
raw_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform, get_raw=True)
|
||||||
|
# You can return any data type as long as it is JSON-serializable
|
||||||
|
return {'predictions': predictions.tolist(),
|
||||||
|
'engineered_local_importance_values': engineered_local_importance_values,
|
||||||
|
'raw_local_importance_values': raw_local_importance_values}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Copyright (c) Microsoft. All rights reserved.
|
||||||
|
# Licensed under the MIT license.
|
||||||
|
import os
|
||||||
|
import joblib
|
||||||
|
|
||||||
|
from interpret.ext.glassbox import LGBMExplainableModel
|
||||||
|
from automl.client.core.common.constants import MODEL_PATH
|
||||||
|
from azureml.core.experiment import Experiment
|
||||||
|
from azureml.core.dataset import Dataset
|
||||||
|
from azureml.core.run import Run
|
||||||
|
from azureml.interpret.mimic_wrapper import MimicWrapper
|
||||||
|
from azureml.interpret.scoring.scoring_explainer import TreeScoringExplainer
|
||||||
|
from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations, \
|
||||||
|
automl_check_model_if_explainable
|
||||||
|
|
||||||
|
|
||||||
|
OUTPUT_DIR = './outputs/'
|
||||||
|
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
# Get workspace from the run context
|
||||||
|
run = Run.get_context()
|
||||||
|
ws = run.experiment.workspace
|
||||||
|
|
||||||
|
# Get the AutoML run object from the experiment name and the workspace
|
||||||
|
experiment = Experiment(ws, '<<experiment_name>>')
|
||||||
|
automl_run = Run(experiment=experiment, run_id='<<run_id>>')
|
||||||
|
|
||||||
|
# Check if this AutoML model is explainable
|
||||||
|
if not automl_check_model_if_explainable(automl_run):
|
||||||
|
raise Exception("Model explanations is currently not supported for " + automl_run.get_properties().get(
|
||||||
|
'run_algorithm'))
|
||||||
|
|
||||||
|
# Download the best model from the artifact store
|
||||||
|
automl_run.download_file(name=MODEL_PATH, output_file_path='model.pkl')
|
||||||
|
|
||||||
|
# Load the AutoML model into memory
|
||||||
|
fitted_model = joblib.load('model.pkl')
|
||||||
|
|
||||||
|
# Get the train dataset from the workspace
|
||||||
|
train_dataset = Dataset.get_by_name(workspace=ws, name='<<train_dataset_name>>')
|
||||||
|
# Drop the lablled column to get the training set.
|
||||||
|
X_train = train_dataset.drop_columns(columns=['<<target_column_name>>'])
|
||||||
|
y_train = train_dataset.keep_columns(columns=['<<target_column_name>>'], validate=True)
|
||||||
|
|
||||||
|
# Get the train dataset from the workspace
|
||||||
|
test_dataset = Dataset.get_by_name(workspace=ws, name='<<test_dataset_name>>')
|
||||||
|
# Drop the lablled column to get the testing set.
|
||||||
|
X_test = test_dataset.drop_columns(columns=['<<target_column_name>>'])
|
||||||
|
|
||||||
|
# Setup the class for explaining the AtuoML models
|
||||||
|
automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, '<<task>>',
|
||||||
|
X=X_train, X_test=X_test,
|
||||||
|
y=y_train)
|
||||||
|
|
||||||
|
# Initialize the Mimic Explainer
|
||||||
|
explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator, LGBMExplainableModel,
|
||||||
|
init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,
|
||||||
|
features=automl_explainer_setup_obj.engineered_feature_names,
|
||||||
|
feature_maps=[automl_explainer_setup_obj.feature_map],
|
||||||
|
classes=automl_explainer_setup_obj.classes)
|
||||||
|
|
||||||
|
# Compute the engineered explanations
|
||||||
|
engineered_explanations = explainer.explain(['local', 'global'], tag='engineered explanations',
|
||||||
|
eval_dataset=automl_explainer_setup_obj.X_test_transform)
|
||||||
|
|
||||||
|
# Compute the raw explanations
|
||||||
|
raw_explanations = explainer.explain(['local', 'global'], get_raw=True, tag='raw explanations',
|
||||||
|
raw_feature_names=automl_explainer_setup_obj.raw_feature_names,
|
||||||
|
eval_dataset=automl_explainer_setup_obj.X_test_transform)
|
||||||
|
|
||||||
|
print("Engineered and raw explanations computed successfully")
|
||||||
|
|
||||||
|
# Initialize the ScoringExplainer
|
||||||
|
scoring_explainer = TreeScoringExplainer(explainer.explainer, feature_maps=[automl_explainer_setup_obj.feature_map])
|
||||||
|
|
||||||
|
# Pickle scoring explainer locally
|
||||||
|
with open('scoring_explainer.pkl', 'wb') as stream:
|
||||||
|
joblib.dump(scoring_explainer, stream)
|
||||||
|
|
||||||
|
# Upload the scoring explainer to the automl run
|
||||||
|
automl_run.upload_file('outputs/scoring_explainer.pkl', 'scoring_explainer.pkl')
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Automated Machine Learning\n",
|
"# Automated Machine Learning\n",
|
||||||
"_**Regression with Local Compute**_\n",
|
"_**Regression with Aml Compute**_\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Contents\n",
|
"## Contents\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#Introduction)\n",
|
||||||
@@ -29,7 +29,8 @@
|
|||||||
"1. [Data](#Data)\n",
|
"1. [Data](#Data)\n",
|
||||||
"1. [Train](#Train)\n",
|
"1. [Train](#Train)\n",
|
||||||
"1. [Results](#Results)\n",
|
"1. [Results](#Results)\n",
|
||||||
"1. [Test](#Test)\n"
|
"1. [Test](#Test)\n",
|
||||||
|
"\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -37,9 +38,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"In this example we use the scikit-learn's [diabetes dataset](http://scikit-learn.org/stable/datasets/index.html#diabetes-dataset) to showcase how you can use AutoML for a simple regression problem.\n",
|
"In this example we use the Hardware Performance Dataset to showcase how you can use AutoML for a simple regression problem. The Regression goal is to predict the performance of certain combinations of hardware parts.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you will learn how to:\n",
|
"In this notebook you will learn how to:\n",
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
@@ -55,7 +56,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Setup\n",
|
"## Setup\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -69,13 +70,32 @@
|
|||||||
"from matplotlib import pyplot as plt\n",
|
"from matplotlib import pyplot as plt\n",
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
|
" \n",
|
||||||
"\n",
|
"\n",
|
||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
"from azureml.train.automl import AutoMLConfig"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
@@ -84,20 +104,17 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
"# Choose a name for the experiment.\n",
|
||||||
"experiment_name = 'automl-local-regression'\n",
|
"experiment_name = 'automl-regression'\n",
|
||||||
"project_folder = './sample_projects/automl-local-regression'\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
"output['Workspace Name'] = ws.name\n",
|
"output['Workspace'] = ws.name\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output['Location'] = ws.location\n",
|
||||||
"output['Project Directory'] = project_folder\n",
|
"output['Run History Name'] = experiment_name\n",
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
"outputDf.T"
|
"outputDf.T"
|
||||||
@@ -107,8 +124,8 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Data\n",
|
"### Using AmlCompute\n",
|
||||||
"This uses scikit-learn's [load_diabetes](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html) method."
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -117,15 +134,52 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Load the diabetes dataset, a well-known built-in small dataset that comes with scikit-learn.\n",
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
"from sklearn.datasets import load_diabetes\n",
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"X, y = load_diabetes(return_X_y = True)\n",
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"cpu_cluster_name = \"reg-cluster\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"columns = ['age', 'gender', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n",
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Data\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"Load the hardware dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv\"\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
|
||||||
|
"\n",
|
||||||
|
"# Split the dataset into train and test datasets\n",
|
||||||
|
"train_data, test_data = dataset.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"\n",
|
||||||
|
"label = \"ERP\"\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -138,40 +192,48 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"|Property|Description|\n",
|
"|Property|Description|\n",
|
||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
"|**task**|classification or regression|\n",
|
"|**task**|classification, regression or forecasting|\n",
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
"|**training_data**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
"|**label_column_name**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
|
"\n",
|
||||||
|
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"automlconfig-remarks-sample"
|
||||||
|
]
|
||||||
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"primary_metric\": 'r2_score',\n",
|
||||||
|
" \"enable_early_stopping\": True, \n",
|
||||||
|
" \"experiment_timeout_hours\": 0.3, #for real scenarios we reccommend a timeout of at least one hour \n",
|
||||||
|
" \"max_concurrent_iterations\": 4,\n",
|
||||||
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task = 'regression',\n",
|
"automl_config = AutoMLConfig(task = 'regression',\n",
|
||||||
" iteration_timeout_minutes = 10,\n",
|
" compute_target = compute_target,\n",
|
||||||
" iterations = 10,\n",
|
" training_data = train_data,\n",
|
||||||
" primary_metric = 'spearman_correlation',\n",
|
" label_column_name = label,\n",
|
||||||
" n_cross_validations = 5,\n",
|
" **automl_settings\n",
|
||||||
" debug_log = 'automl.log',\n",
|
" )"
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
"Call the `submit` method on the experiment object and pass the run configuration. Execution of remote runs is asynchronous. Depending on the data and the number of iterations this can run for a while. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -180,7 +242,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -189,7 +251,18 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"local_run"
|
"# If you need to retrieve a run that already started, use the following code\n",
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -217,16 +290,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.widgets import RunDetails\n",
|
"from azureml.widgets import RunDetails\n",
|
||||||
"RunDetails(local_run).show() "
|
"RunDetails(remote_run).show() "
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"\n",
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -235,15 +299,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"children = list(local_run.get_children())\n",
|
"remote_run.wait_for_completion()"
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -261,7 +317,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
"print(best_run)\n",
|
"print(best_run)\n",
|
||||||
"print(fitted_model)"
|
"print(fitted_model)"
|
||||||
]
|
]
|
||||||
@@ -281,7 +337,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"lookup_metric = \"root_mean_squared_error\"\n",
|
"lookup_metric = \"root_mean_squared_error\"\n",
|
||||||
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
|
"best_run, fitted_model = remote_run.get_output(metric = lookup_metric)\n",
|
||||||
"print(best_run)\n",
|
"print(best_run)\n",
|
||||||
"print(fitted_model)"
|
"print(fitted_model)"
|
||||||
]
|
]
|
||||||
@@ -301,7 +357,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"iteration = 3\n",
|
"iteration = 3\n",
|
||||||
"third_run, third_model = local_run.get_output(iteration = iteration)\n",
|
"third_run, third_model = remote_run.get_output(iteration = iteration)\n",
|
||||||
"print(third_run)\n",
|
"print(third_run)\n",
|
||||||
"print(third_model)"
|
"print(third_model)"
|
||||||
]
|
]
|
||||||
@@ -314,10 +370,23 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"Predict on training and test set, and calculate residual values."
|
"# preview the first 3 rows of the dataset\n",
|
||||||
|
"\n",
|
||||||
|
"test_data = test_data.to_pandas_dataframe()\n",
|
||||||
|
"y_test = test_data['ERP'].fillna(0)\n",
|
||||||
|
"test_data = test_data.drop('ERP', 1)\n",
|
||||||
|
"test_data = test_data.fillna(0)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"train_data = train_data.to_pandas_dataframe()\n",
|
||||||
|
"y_train = train_data['ERP'].fillna(0)\n",
|
||||||
|
"train_data = train_data.drop('ERP', 1)\n",
|
||||||
|
"train_data = train_data.fillna(0)\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -326,10 +395,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"y_pred_train = fitted_model.predict(X_train)\n",
|
"y_pred_train = fitted_model.predict(train_data)\n",
|
||||||
"y_residual_train = y_train - y_pred_train\n",
|
"y_residual_train = y_train - y_pred_train\n",
|
||||||
"\n",
|
"\n",
|
||||||
"y_pred_test = fitted_model.predict(X_test)\n",
|
"y_pred_test = fitted_model.predict(test_data)\n",
|
||||||
"y_residual_test = y_test - y_pred_test"
|
"y_residual_test = y_test - y_pred_test"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -349,41 +418,57 @@
|
|||||||
"f.set_figwidth(16)\n",
|
"f.set_figwidth(16)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot residual values of training set.\n",
|
"# Plot residual values of training set.\n",
|
||||||
"a0.axis([0, 360, -200, 200])\n",
|
"a0.axis([0, 360, -100, 100])\n",
|
||||||
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
|
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
|
||||||
"a0.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
"a0.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
||||||
"a0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\n",
|
"a0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\n",
|
||||||
"a0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)), fontsize = 12)\n",
|
"a0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)),fontsize = 12)\n",
|
||||||
"a0.set_xlabel('Training samples', fontsize = 12)\n",
|
"a0.set_xlabel('Training samples', fontsize = 12)\n",
|
||||||
"a0.set_ylabel('Residual Values', fontsize = 12)\n",
|
"a0.set_ylabel('Residual Values', fontsize = 12)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot a histogram.\n",
|
|
||||||
"a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n",
|
|
||||||
"a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n",
|
|
||||||
"\n",
|
|
||||||
"# Plot residual values of test set.\n",
|
"# Plot residual values of test set.\n",
|
||||||
"a1.axis([0, 90, -200, 200])\n",
|
"a1.axis([0, 90, -100, 100])\n",
|
||||||
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
|
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
|
||||||
"a1.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
"a1.plot([-10,360],[0,0], 'r-', lw = 3)\n",
|
||||||
"a1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\n",
|
"a1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\n",
|
||||||
"a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)), fontsize = 12)\n",
|
"a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)),fontsize = 12)\n",
|
||||||
"a1.set_xlabel('Test samples', fontsize = 12)\n",
|
"a1.set_xlabel('Test samples', fontsize = 12)\n",
|
||||||
"a1.set_yticklabels([])\n",
|
"a1.set_yticklabels([])\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot a histogram.\n",
|
|
||||||
"a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n",
|
|
||||||
"a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n",
|
|
||||||
"\n",
|
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"test_pred = plt.scatter(y_test, y_pred_test, color='')\n",
|
||||||
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "savitam"
|
"name": "rakellam"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
"display_name": "Python 3.6",
|
"display_name": "Python 3.6",
|
||||||
"language": "python",
|
"language": "python",
|
||||||
@@ -399,7 +484,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.6"
|
"version": "3.6.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-regression
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -1,555 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Remote Execution using AmlCompute**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you would see\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Create or Attach existing AmlCompute to a workspace.\n",
|
|
||||||
"3. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"4. Train the model using AmlCompute\n",
|
|
||||||
"5. Explore the results.\n",
|
|
||||||
"6. Test the best fitted model.\n",
|
|
||||||
"\n",
|
|
||||||
"In addition this notebook showcases the following features\n",
|
|
||||||
"- **Parallel** executions for iterations\n",
|
|
||||||
"- **Asynchronous** tracking of progress\n",
|
|
||||||
"- **Cancellation** of individual iterations or the entire run\n",
|
|
||||||
"- Retrieving models for any iteration or logged metric\n",
|
|
||||||
"- Specifying AutoML settings as `**kwargs`"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"import os\n",
|
|
||||||
"import csv\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for the run history container in the workspace.\n",
|
|
||||||
"experiment_name = 'automl-remote-amlcompute'\n",
|
|
||||||
"project_folder = './project'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create or Attach existing AmlCompute\n",
|
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
|
||||||
"\n",
|
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.compute import AmlCompute\n",
|
|
||||||
"from azureml.core.compute import ComputeTarget\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for your cluster.\n",
|
|
||||||
"amlcompute_cluster_name = \"cpu-cluster\"\n",
|
|
||||||
"\n",
|
|
||||||
"found = False\n",
|
|
||||||
"# Check if this compute target already exists in the workspace.\n",
|
|
||||||
"cts = ws.compute_targets\n",
|
|
||||||
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n",
|
|
||||||
" found = True\n",
|
|
||||||
" print('Found existing compute target.')\n",
|
|
||||||
" compute_target = cts[amlcompute_cluster_name]\n",
|
|
||||||
"\n",
|
|
||||||
"if not found:\n",
|
|
||||||
" print('Creating a new compute target...')\n",
|
|
||||||
" provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # for GPU, use \"STANDARD_NC6\"\n",
|
|
||||||
" #vm_priority = 'lowpriority', # optional\n",
|
|
||||||
" max_nodes = 6)\n",
|
|
||||||
"\n",
|
|
||||||
" # Create the cluster.\\n\",\n",
|
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n",
|
|
||||||
"\n",
|
|
||||||
" # Can poll for a minimum number of nodes and for a specific timeout.\n",
|
|
||||||
" # If no min_node_count is provided, it will use the scale settings for the cluster.\n",
|
|
||||||
" compute_target.wait_for_completion(show_output = True, min_node_count = None, timeout_in_minutes = 20)\n",
|
|
||||||
"\n",
|
|
||||||
" # For a more detailed view of current AmlCompute status, use get_status()."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data\n",
|
|
||||||
"For remote executions, you need to make the data accessible from the remote compute.\n",
|
|
||||||
"This can be done by uploading the data to DataStore.\n",
|
|
||||||
"In this example, we upload scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) data."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"data_train = datasets.load_digits()\n",
|
|
||||||
"\n",
|
|
||||||
"if not os.path.isdir('data'):\n",
|
|
||||||
" os.mkdir('data')\n",
|
|
||||||
" \n",
|
|
||||||
"if not os.path.exists(project_folder):\n",
|
|
||||||
" os.makedirs(project_folder)\n",
|
|
||||||
" \n",
|
|
||||||
"pd.DataFrame(data_train.data).to_csv(\"data/X_train.tsv\", index=False, header=False, quoting=csv.QUOTE_ALL, sep=\"\\t\")\n",
|
|
||||||
"pd.DataFrame(data_train.target).to_csv(\"data/y_train.tsv\", index=False, header=False, sep=\"\\t\")\n",
|
|
||||||
"\n",
|
|
||||||
"ds = ws.get_default_datastore()\n",
|
|
||||||
"ds.upload(src_dir='./data', target_path='bai_data', overwrite=True, show_progress=True)\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.core.runconfig import DataReferenceConfiguration\n",
|
|
||||||
"dr = DataReferenceConfiguration(datastore_name=ds.name, \n",
|
|
||||||
" path_on_datastore='bai_data', \n",
|
|
||||||
" path_on_compute='/tmp/azureml_runs',\n",
|
|
||||||
" mode='download', # download files from datastore to compute target\n",
|
|
||||||
" overwrite=False)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"\n",
|
|
||||||
"# create a new RunConfig object\n",
|
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Set compute target to AmlCompute\n",
|
|
||||||
"conda_run_config.target = compute_target\n",
|
|
||||||
"conda_run_config.environment.docker.enabled = True\n",
|
|
||||||
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
|
||||||
"\n",
|
|
||||||
"# set the data reference of the run coonfiguration\n",
|
|
||||||
"conda_run_config.data_references = {ds.name: dr}\n",
|
|
||||||
"\n",
|
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"%%writefile $project_folder/get_data.py\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"def get_data():\n",
|
|
||||||
" X_train = pd.read_csv(\"/tmp/azureml_runs/bai_data/X_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
" y_train = pd.read_csv(\"/tmp/azureml_runs/bai_data/y_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
"\n",
|
|
||||||
" return { \"X\" : X_train.values, \"y\" : y_train[0].values }\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"You can specify `automl_settings` as `**kwargs` as well. Also note that you can use a `get_data()` function for local excutions too.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** When using AmlCompute, you can't pass Numpy arrays directly to the fit method.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
|
||||||
"|**max_concurrent_iterations**|Maximum number of iterations that would be executed in parallel. This should be less than the number of cores on the DSVM.|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_settings = {\n",
|
|
||||||
" \"iteration_timeout_minutes\": 10,\n",
|
|
||||||
" \"iterations\": 20,\n",
|
|
||||||
" \"n_cross_validations\": 5,\n",
|
|
||||||
" \"primary_metric\": 'AUC_weighted',\n",
|
|
||||||
" \"preprocess\": False,\n",
|
|
||||||
" \"max_concurrent_iterations\": 5,\n",
|
|
||||||
" \"verbosity\": logging.INFO\n",
|
|
||||||
"}\n",
|
|
||||||
"\n",
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" path = project_folder,\n",
|
|
||||||
" run_configuration=conda_run_config,\n",
|
|
||||||
" data_script = project_folder + \"/get_data.py\",\n",
|
|
||||||
" **automl_settings\n",
|
|
||||||
" )\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. For remote runs the execution is asynchronous, so you will see the iterations get populated as they complete. You can interact with the widgets and models even when the experiment is running to retrieve the best model up to that point. Once you are satisfied with the model, you can cancel a particular iteration or the whole run.\n",
|
|
||||||
"In this example, we specify `show_output = False` to suppress console output while the run is in progress."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run = experiment.submit(automl_config, show_output = False)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results\n",
|
|
||||||
"\n",
|
|
||||||
"#### Loading executed runs\n",
|
|
||||||
"In case you need to load a previously executed run, enable the cell below and replace the `run_id` value."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "raw",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"remote_run = AutoMLRun(experiment = experiment, run_id = 'AutoML_5db13491-c92a-4f1d-b622-8ab8d973a058')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"You can click on a pipeline to see run properties and output logs. Logs are also available on the DSVM under `/tmp/azureml_run/{iterationid}/azureml-logs`\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(remote_run).show() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Wait until the run finishes.\n",
|
|
||||||
"remote_run.wait_for_completion(show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"\n",
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(remote_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Cancelling Runs\n",
|
|
||||||
"\n",
|
|
||||||
"You can cancel ongoing remote runs using the `cancel` and `cancel_iteration` functions."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Cancel the ongoing experiment and stop scheduling new iterations.\n",
|
|
||||||
"# remote_run.cancel()\n",
|
|
||||||
"\n",
|
|
||||||
"# Cancel iteration 1 and move onto iteration 2.\n",
|
|
||||||
"# remote_run.cancel_iteration(1)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = remote_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model which has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = remote_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the third iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 3\n",
|
|
||||||
"third_run, third_model = remote_run.get_output(iteration=iteration)\n",
|
|
||||||
"print(third_run)\n",
|
|
||||||
"print(third_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_test = digits.data[:10, :]\n",
|
|
||||||
"y_test = digits.target[:10]\n",
|
|
||||||
"images = digits.images[:10]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Testing Our Best Fitted Model"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
|
|
||||||
" fig = plt.figure(1, figsize=(3,3))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" plt.show()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1,247 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Sample Weight**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Test](#Test)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use sample weight with AutoML. Sample weight is used where some sample values are more important than others.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to configure AutoML to use `sample_weight` and you will see the difference sample weight makes to the test results."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose names for the regular and the sample weight experiments.\n",
|
|
||||||
"experiment_name = 'non_sample_weight_experiment'\n",
|
|
||||||
"sample_weight_experiment_name = 'sample_weight_experiment'\n",
|
|
||||||
"\n",
|
|
||||||
"project_folder = './sample_projects/sample_weight'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"sample_weight_experiment=Experiment(ws, sample_weight_experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate two `AutoMLConfig` objects. One will be used with `sample_weight` and one without."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_train = digits.data[100:,:]\n",
|
|
||||||
"y_train = digits.target[100:]\n",
|
|
||||||
"\n",
|
|
||||||
"# The example makes the sample weight 0.9 for the digit 4 and 0.1 for all other digits.\n",
|
|
||||||
"# This makes the model more likely to classify as 4 if the image it not clear.\n",
|
|
||||||
"sample_weight = np.array([(0.9 if x == 4 else 0.01) for x in y_train])\n",
|
|
||||||
"\n",
|
|
||||||
"automl_classifier = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 60,\n",
|
|
||||||
" iterations = 10,\n",
|
|
||||||
" n_cross_validations = 2,\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" path = project_folder)\n",
|
|
||||||
"\n",
|
|
||||||
"automl_sample_weight = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 60,\n",
|
|
||||||
" iterations = 10,\n",
|
|
||||||
" n_cross_validations = 2,\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" sample_weight = sample_weight,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment objects and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_classifier, show_output = True)\n",
|
|
||||||
"sample_weight_run = sample_weight_experiment.submit(automl_sample_weight, show_output = True)\n",
|
|
||||||
"\n",
|
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
|
||||||
"best_run_sample_weight, fitted_model_sample_weight = sample_weight_run.get_output()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_test = digits.data[:100, :]\n",
|
|
||||||
"y_test = digits.target[:100]\n",
|
|
||||||
"images = digits.images[:100]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Compare the Models\n",
|
|
||||||
"The prediction from the sample weight model is more likely to correctly predict 4's. However, it is also more likely to predict 4 for some images that are not labelled as 4."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in range(0,len(y_test)):\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" predicted_sample_weight = fitted_model_sample_weight.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" if predicted == 4 or predicted_sample_weight == 4 or label == 4:\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d Prediced with sample weight = %d\" % (label, predicted, predicted_sample_weight)\n",
|
|
||||||
" fig = plt.figure(1, figsize=(3,3))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" plt.show()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.5"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1,387 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Train Test Split and Handling Sparse Data**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"In this example we use the scikit-learn's [20newsgroup](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_20newsgroups.html) to showcase how you can use AutoML for handling sparse data and how to specify custom cross validations splits.\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"4. Train the model.\n",
|
|
||||||
"5. Explore the results.\n",
|
|
||||||
"6. Test the best fitted model.\n",
|
|
||||||
"\n",
|
|
||||||
"In addition this notebook showcases the following features\n",
|
|
||||||
"- Explicit train test splits \n",
|
|
||||||
"- Handling **sparse data** in the input"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# choose a name for the experiment\n",
|
|
||||||
"experiment_name = 'sparse-data-train-test-split'\n",
|
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/sparse-data-train-test-split'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from sklearn.datasets import fetch_20newsgroups\n",
|
|
||||||
"from sklearn.feature_extraction.text import HashingVectorizer\n",
|
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
|
||||||
"\n",
|
|
||||||
"remove = ('headers', 'footers', 'quotes')\n",
|
|
||||||
"categories = [\n",
|
|
||||||
" 'alt.atheism',\n",
|
|
||||||
" 'talk.religion.misc',\n",
|
|
||||||
" 'comp.graphics',\n",
|
|
||||||
" 'sci.space',\n",
|
|
||||||
"]\n",
|
|
||||||
"data_train = fetch_20newsgroups(subset = 'train', categories = categories,\n",
|
|
||||||
" shuffle = True, random_state = 42,\n",
|
|
||||||
" remove = remove)\n",
|
|
||||||
"\n",
|
|
||||||
"X_train, X_valid, y_train, y_valid = train_test_split(data_train.data, data_train.target, test_size = 0.33, random_state = 42)\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"vectorizer = HashingVectorizer(stop_words = 'english', alternate_sign = False,\n",
|
|
||||||
" n_features = 2**16)\n",
|
|
||||||
"X_train = vectorizer.transform(X_train)\n",
|
|
||||||
"X_valid = vectorizer.transform(X_valid)\n",
|
|
||||||
"\n",
|
|
||||||
"summary_df = pd.DataFrame(index = ['No of Samples', 'No of Features'])\n",
|
|
||||||
"summary_df['Train Set'] = [X_train.shape[0], X_train.shape[1]]\n",
|
|
||||||
"summary_df['Validation Set'] = [X_valid.shape[0], X_valid.shape[1]]\n",
|
|
||||||
"summary_df"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**preprocess**|Setting this to *True* enables AutoML to perform preprocessing on the input to handle *missing data*, and to perform some common *feature extraction*.<br>**Note:** If input data is sparse, you cannot use *True*.|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**X_valid**|(sparse) array-like, shape = [n_samples, n_features] for the custom validation set.|\n",
|
|
||||||
"|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
|
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 60,\n",
|
|
||||||
" iterations = 5,\n",
|
|
||||||
" preprocess = False,\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" X_valid = X_valid, \n",
|
|
||||||
" y_valid = y_valid, \n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Widget for Monitoring Runs\n",
|
|
||||||
"\n",
|
|
||||||
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(local_run).show() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"\n",
|
|
||||||
"#### Retrieve All Child Runs\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
" \n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model\n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model which has the smallest `accuracy` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# lookup_metric = \"accuracy\"\n",
|
|
||||||
"# best_run, fitted_model = local_run.get_output(metric = lookup_metric)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the third iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# iteration = 3\n",
|
|
||||||
"# best_run, fitted_model = local_run.get_output(iteration = iteration)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Load test data.\n",
|
|
||||||
"from pandas_ml import ConfusionMatrix\n",
|
|
||||||
"\n",
|
|
||||||
"data_test = fetch_20newsgroups(subset = 'test', categories = categories,\n",
|
|
||||||
" shuffle = True, random_state = 42,\n",
|
|
||||||
" remove = remove)\n",
|
|
||||||
"\n",
|
|
||||||
"X_test = vectorizer.transform(data_test.data)\n",
|
|
||||||
"y_test = data_test.target\n",
|
|
||||||
"\n",
|
|
||||||
"# Test our best pipeline.\n",
|
|
||||||
"\n",
|
|
||||||
"y_pred = fitted_model.predict(X_test)\n",
|
|
||||||
"y_pred_strings = [data_test.target_names[i] for i in y_pred]\n",
|
|
||||||
"y_test_strings = [data_test.target_names[i] for i in y_test]\n",
|
|
||||||
"\n",
|
|
||||||
"cm = ConfusionMatrix(y_test_strings, y_pred_strings)\n",
|
|
||||||
"print(cm)\n",
|
|
||||||
"cm.plot()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
# Table of Contents
|
||||||
|
1. [Introduction](#introduction)
|
||||||
|
1. [Setup using Azure Data Studio](#azuredatastudiosetup)
|
||||||
|
1. [Energy demand example using Azure Data Studio](#azuredatastudioenergydemand)
|
||||||
|
1. [Set using SQL Server Management Studio for SQL Server 2017 on Windows](#ssms2017)
|
||||||
|
1. [Set using SQL Server Management Studio for SQL Server 2019 on Linux](#ssms2019)
|
||||||
|
1. [Energy demand example using SQL Server Management Studio](#ssmsenergydemand)
|
||||||
|
|
||||||
|
|
||||||
|
<a name="introduction"></a>
|
||||||
|
# Introduction
|
||||||
|
SQL Server 2017 or 2019 can call Azure ML automated machine learning to create models trained on data from SQL Server.
|
||||||
|
This uses the sp_execute_external_script stored procedure, which can call Python scripts.
|
||||||
|
SQL Server 2017 and SQL Server 2019 can both run on Windows or Linux.
|
||||||
|
However, this integration is not available for SQL Server 2017 on Linux.
|
||||||
|
|
||||||
|
This folder shows how to setup the integration and has a sample that uses the integration to train and predict based on an energy demand dataset.
|
||||||
|
|
||||||
|
This integration is part of SQL Server and so can be used from any SQL client.
|
||||||
|
These instructions show using it from Azure Data Studio or SQL Server Managment Studio.
|
||||||
|
|
||||||
|
<a name="azuredatastudiosetup"></a>
|
||||||
|
## Setup using Azure Data Studio
|
||||||
|
|
||||||
|
These step show setting up the integration using Azure Data Studio.
|
||||||
|
|
||||||
|
1. If you don't already have SQL Server, you can install it from [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
|
||||||
|
1. Install Azure Data Studio from [https://docs.microsoft.com/en-us/sql/azure-data-studio/download?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/azure-data-studio/download?view=sql-server-2017)
|
||||||
|
1. Start Azure Data Studio and connect to SQL Server. [https://docs.microsoft.com/en-us/sql/azure-data-studio/sql-notebooks?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/azure-data-studio/sql-notebooks?view=sql-server-2017)
|
||||||
|
1. Create a database named "automl".
|
||||||
|
1. Open the notebook how-to-use-azureml\automated-machine-learning\sql-server\setup\auto-ml-sql-setup.ipynb and follow the instructions in it.
|
||||||
|
|
||||||
|
<a name="azuredatastudioenergydemand"></a>
|
||||||
|
## Energy demand example using Azure Data Studio
|
||||||
|
|
||||||
|
Once you have completed the setup, you can try the energy demand sample in the notebook energy-demand\auto-ml-sql-energy-demand.ipynb.
|
||||||
|
This has cells to train a model, predict based on the model and show metrics for each pipeline run in training the model.
|
||||||
|
|
||||||
|
<a name="ssms2017"></a>
|
||||||
|
## Setup using SQL Server Management Studio for SQL Server 2017 on Windows
|
||||||
|
|
||||||
|
These instruction setup the integration for SQL Server 2017 on Windows.
|
||||||
|
|
||||||
|
1. If you don't already have SQL Server, you can install it from [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
|
||||||
|
2. Enable external scripts with the following commands:
|
||||||
|
```sh
|
||||||
|
sp_configure 'external scripts enabled',1
|
||||||
|
reconfigure with override
|
||||||
|
```
|
||||||
|
3. Stop SQL Server.
|
||||||
|
4. Install the automated machine learning libraries using the following commands from Administrator command prompt (If you are using a non-default SQL Server instance name, replace MSSQLSERVER in the second command with the instance name)
|
||||||
|
```sh
|
||||||
|
cd "C:\Program Files\Microsoft SQL Server"
|
||||||
|
cd "MSSQL14.MSSQLSERVER\PYTHON_SERVICES"
|
||||||
|
python.exe -m pip install azureml-sdk[automl]
|
||||||
|
python.exe -m pip install --upgrade numpy
|
||||||
|
python.exe -m pip install --upgrade sklearn
|
||||||
|
```
|
||||||
|
5. Start SQL Server and the service "SQL Server Launchpad service".
|
||||||
|
6. In Windows Firewall, click on advanced settings and in Outbound Rules, disable "Block network access for R local user accounts in SQL Server instance xxxx".
|
||||||
|
7. Execute the files in the setup folder in SQL Server Management Studio: aml_model.sql, aml_connection.sql, AutoMLGetMetrics.sql, AutoMLPredict.sql and AutoMLTrain.sql
|
||||||
|
8. Create an Azure Machine Learning Workspace. You can use the instructions at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace ](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace)
|
||||||
|
9. Create a config.json file file using the subscription id, resource group name and workspace name that you used to create the workspace. The file is described at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace)
|
||||||
|
10. Create an Azure service principal. You can do this with the commands:
|
||||||
|
```sh
|
||||||
|
az login
|
||||||
|
az account set --subscription subscriptionid
|
||||||
|
az ad sp create-for-rbac --name principlename --password password
|
||||||
|
```
|
||||||
|
11. Insert the values \<tenant\>, \<AppId\> and \<password\> returned by create-for-rbac above into the aml_connection table. Set \<path\> as the absolute path to your config.json file. Set the name to <20>Default<6C>.
|
||||||
|
|
||||||
|
<a name="ssms2019"></a>
|
||||||
|
## Setup using SQL Server Management Studio for SQL Server 2019 on Linux
|
||||||
|
1. Install SQL Server 2019 from: [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
|
||||||
|
2. Install machine learning support from: [https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-machine-learning?view=sqlallproducts-allversions#ubuntu](https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-machine-learning?view=sqlallproducts-allversions#ubuntu)
|
||||||
|
3. Then install SQL Server management Studio from [https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017)
|
||||||
|
4. Enable external scripts with the following commands:
|
||||||
|
```sh
|
||||||
|
sp_configure 'external scripts enabled',1
|
||||||
|
reconfigure with override
|
||||||
|
```
|
||||||
|
5. Stop SQL Server.
|
||||||
|
6. Install the automated machine learning libraries using the following commands from Administrator command (If you are using a non-default SQL Server instance name, replace MSSQLSERVER in the second command with the instance name):
|
||||||
|
```sh
|
||||||
|
sudo /opt/mssql/mlservices/bin/python/python -m pip install azureml-sdk[automl]
|
||||||
|
sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade numpy
|
||||||
|
sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade sklearn
|
||||||
|
```
|
||||||
|
7. Start SQL Server.
|
||||||
|
8. Execute the files aml_model.sql, aml_connection.sql, AutoMLGetMetrics.sql, AutoMLPredict.sql, AutoMLForecast.sql and AutoMLTrain.sql in SQL Server Management Studio.
|
||||||
|
9. Create an Azure Machine Learning Workspace. You can use the instructions at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace)
|
||||||
|
10. Create a config.json file file using the subscription id, resource group name and workspace name that you use to create the workspace. The file is described at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace)
|
||||||
|
11. Create an Azure service principal. You can do this with the commands:
|
||||||
|
```sh
|
||||||
|
az login
|
||||||
|
az account set --subscription subscriptionid
|
||||||
|
az ad sp create-for-rbac --name principlename --password password
|
||||||
|
```
|
||||||
|
12. Insert the values \<tenant\>, \<AppId\> and \<password\> returned by create-for-rbac above into the aml_connection table. Set \<path\> as the absolute path to your config.json file. Set the name to <20>Default<6C>.
|
||||||
|
|
||||||
|
<a name="ssmsenergydemand"></a>
|
||||||
|
## Energy demand example using SQL Server Management Studio
|
||||||
|
|
||||||
|
Once you have completed the setup, you can try the energy demand sample queries.
|
||||||
|
First you need to load the sample data in the database.
|
||||||
|
1. In SQL Server Management Studio, you can right-click the database, select Tasks, then Import Flat file.
|
||||||
|
1. Select the file MachineLearningNotebooks\notebooks\how-to-use-azureml\automated-machine-learning\forecasting-energy-demand\nyc_energy.csv.
|
||||||
|
1. When you get to the column definition page, allow nulls for all columns.
|
||||||
|
|
||||||
|
You can then run the queries in the energy-demand folder:
|
||||||
|
* TrainEnergyDemand.sql runs AutoML, trains multiple models on data and selects the best model.
|
||||||
|
* ForecastEnergyDemand.sql forecasts based on the most recent training run.
|
||||||
|
* GetMetrics.sql returns all the metrics for each model in the most recent training run.
|
||||||
@@ -1,208 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Classification with Local Compute**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"\n",
|
|
||||||
"In this example we will explore AutoML's subsampling feature. This is useful for training on large datasets to speed up the convergence.\n",
|
|
||||||
"\n",
|
|
||||||
"The setup is quiet similar to a normal classification, with the exception of the `enable_subsampling` option. Keep in mind that even with the `enable_subsampling` flag set, subsampling will only be run for large datasets (>= 50k rows) and large (>= 85) or no iteration restrictions.\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
|
||||||
"experiment_name = 'automl-subsampling'\n",
|
|
||||||
"project_folder = './sample_projects/automl-subsampling'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"pd.DataFrame(data = output, index = ['']).T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data\n",
|
|
||||||
"\n",
|
|
||||||
"We will create a simple dataset using the numpy sin function just for this example. We need just over 50k rows."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"base = np.arange(60000)\n",
|
|
||||||
"cos = np.cos(base)\n",
|
|
||||||
"y = np.round(np.sin(base)).astype('int')\n",
|
|
||||||
"\n",
|
|
||||||
"# Exclude the first 100 rows from training so that they can be used for test.\n",
|
|
||||||
"X_train = np.hstack((base.reshape(-1, 1), cos.reshape(-1, 1)))\n",
|
|
||||||
"y_train = y"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**enable_subsampling**|This enables subsampling as an option. However it does not guarantee subsampling will be used. It also depends on how large the dataset is and how many iterations it's expected to run at a minimum.|\n",
|
|
||||||
"|**iterations**|Number of iterations. Subsampling requires a lot of iterations at smaller percent so in order for subsampling to be used we need to set iterations to be a high number.|\n",
|
|
||||||
"|**experiment_timeout_minutes**|The experiment timeout, it's set to 5 right now to shorten the demo but it should probably be higher if we want to finish all the iterations.|\n",
|
|
||||||
"\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'accuracy',\n",
|
|
||||||
" iterations = 85,\n",
|
|
||||||
" experiment_timeout_minutes = 5,\n",
|
|
||||||
" n_cross_validations = 2,\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" enable_subsampling=True,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
|
|
||||||
"In this example, we specify `show_output = True` to print currently running iterations to the console."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": []
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "rogehe"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
Binary file not shown.
@@ -1,33 +0,0 @@
|
|||||||
Azure Databricks is a managed Spark offering on Azure and customers already use it for advanced analytics. It provides a collaborative Notebook based environment with CPU or GPU based compute cluster.
|
|
||||||
|
|
||||||
In this section, you will find sample notebooks on how to use Azure Machine Learning SDK with Azure Databricks. You can train a model using Spark MLlib and then deploy the model to ACI/AKS from within Azure Databricks. You can also use Automated ML capability (**public preview**) of Azure ML SDK with Azure Databricks.
|
|
||||||
|
|
||||||
- Customers who use Azure Databricks for advanced analytics can now use the same cluster to run experiments with or without automated machine learning.
|
|
||||||
- You can keep the data within the same cluster.
|
|
||||||
- You can leverage the local worker nodes with autoscale and auto termination capabilities.
|
|
||||||
- You can use multiple cores of your Azure Databricks cluster to perform simultenous training.
|
|
||||||
- You can further tune the model generated by automated machine learning if you chose to.
|
|
||||||
- Every run (including the best run) is available as a pipeline, which you can tune further if needed.
|
|
||||||
- The model trained using Azure Databricks can be registered in Azure ML SDK workspace and then deployed to Azure managed compute (ACI or AKS) using the Azure Machine learning SDK.
|
|
||||||
|
|
||||||
Please follow our [Azure doc](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#azure-databricks) to install the sdk in your Azure Databricks cluster before trying any of the sample notebooks.
|
|
||||||
|
|
||||||
**Single file** -
|
|
||||||
The following archive contains all the sample notebooks. You can the run notebooks after importing [DBC](Databricks_AMLSDK_1-4_6.dbc) in your Databricks workspace instead of downloading individually.
|
|
||||||
|
|
||||||
Notebooks 1-4 have to be run sequentially & are related to Income prediction experiment based on this [dataset](https://archive.ics.uci.edu/ml/datasets/adult) and demonstrate how to data prep, train and operationalize a Spark ML model with Azure ML Python SDK from within Azure Databricks.
|
|
||||||
|
|
||||||
Notebook 6 is an Automated ML sample notebook for Classification.
|
|
||||||
|
|
||||||
Learn more about [how to use Azure Databricks as a development environment](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment#azure-databricks) for Azure Machine Learning service.
|
|
||||||
|
|
||||||
**Databricks as a Compute Target from AML Pipelines**
|
|
||||||
You can use Azure Databricks as a compute target from [Azure Machine Learning Pipelines](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines). Take a look at this notebook for details: [aml-pipelines-use-databricks-as-compute-target.ipynb](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks/databricks-as-remote-compute-target/aml-pipelines-use-databricks-as-compute-target.ipynb).
|
|
||||||
|
|
||||||
For more on SDK concepts, please refer to [notebooks](https://github.com/Azure/MachineLearningNotebooks).
|
|
||||||
|
|
||||||
**Please let us know your feedback.**
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||

|
|
||||||
@@ -1,380 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Model Building"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"import pprint\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"\n",
|
|
||||||
"from pyspark.ml import Pipeline, PipelineModel\n",
|
|
||||||
"from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler\n",
|
|
||||||
"from pyspark.ml.classification import LogisticRegression\n",
|
|
||||||
"from pyspark.ml.evaluation import BinaryClassificationEvaluator\n",
|
|
||||||
"from pyspark.ml.tuning import CrossValidator, ParamGridBuilder"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Set auth to be used by workspace related APIs.\n",
|
|
||||||
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
|
|
||||||
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
|
|
||||||
"auth = None"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# import the Workspace class and check the azureml SDK version\n",
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
|
||||||
" 'Azure region: ' + ws.location, \n",
|
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
|
||||||
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#get the train and test datasets\n",
|
|
||||||
"train_data_path = \"AdultCensusIncomeTrain\"\n",
|
|
||||||
"test_data_path = \"AdultCensusIncomeTest\"\n",
|
|
||||||
"\n",
|
|
||||||
"train = spark.read.parquet(train_data_path)\n",
|
|
||||||
"test = spark.read.parquet(test_data_path)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"train: ({}, {})\".format(train.count(), len(train.columns)))\n",
|
|
||||||
"print(\"test: ({}, {})\".format(test.count(), len(test.columns)))\n",
|
|
||||||
"\n",
|
|
||||||
"train.printSchema()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Define Model"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"label = \"income\"\n",
|
|
||||||
"dtypes = dict(train.dtypes)\n",
|
|
||||||
"dtypes.pop(label)\n",
|
|
||||||
"\n",
|
|
||||||
"si_xvars = []\n",
|
|
||||||
"ohe_xvars = []\n",
|
|
||||||
"featureCols = []\n",
|
|
||||||
"for idx,key in enumerate(dtypes):\n",
|
|
||||||
" if dtypes[key] == \"string\":\n",
|
|
||||||
" featureCol = \"-\".join([key, \"encoded\"])\n",
|
|
||||||
" featureCols.append(featureCol)\n",
|
|
||||||
" \n",
|
|
||||||
" tmpCol = \"-\".join([key, \"tmp\"])\n",
|
|
||||||
" # string-index and one-hot encode the string column\n",
|
|
||||||
" #https://spark.apache.org/docs/2.3.0/api/java/org/apache/spark/ml/feature/StringIndexer.html\n",
|
|
||||||
" #handleInvalid: Param for how to handle invalid data (unseen labels or NULL values). \n",
|
|
||||||
" #Options are 'skip' (filter out rows with invalid data), 'error' (throw an error), \n",
|
|
||||||
" #or 'keep' (put invalid data in a special additional bucket, at index numLabels). Default: \"error\"\n",
|
|
||||||
" si_xvars.append(StringIndexer(inputCol=key, outputCol=tmpCol, handleInvalid=\"skip\"))\n",
|
|
||||||
" ohe_xvars.append(OneHotEncoder(inputCol=tmpCol, outputCol=featureCol))\n",
|
|
||||||
" else:\n",
|
|
||||||
" featureCols.append(key)\n",
|
|
||||||
"\n",
|
|
||||||
"# string-index the label column into a column named \"label\"\n",
|
|
||||||
"si_label = StringIndexer(inputCol=label, outputCol='label')\n",
|
|
||||||
"\n",
|
|
||||||
"# assemble the encoded feature columns in to a column named \"features\"\n",
|
|
||||||
"assembler = VectorAssembler(inputCols=featureCols, outputCol=\"features\")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.run import Run\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import os\n",
|
|
||||||
"import shutil\n",
|
|
||||||
"\n",
|
|
||||||
"model_name = \"AdultCensus_runHistory.mml\"\n",
|
|
||||||
"model_dbfs = os.path.join(\"/dbfs\", model_name)\n",
|
|
||||||
"run_history_name = 'spark-ml-notebook'\n",
|
|
||||||
"\n",
|
|
||||||
"# start a training run by defining an experiment\n",
|
|
||||||
"myexperiment = Experiment(ws, \"Ignite_AI_Talk\")\n",
|
|
||||||
"root_run = myexperiment.start_logging()\n",
|
|
||||||
"\n",
|
|
||||||
"# Regularization Rates - \n",
|
|
||||||
"regs = [0.0001, 0.001, 0.01, 0.1]\n",
|
|
||||||
" \n",
|
|
||||||
"# try a bunch of regularization rate in a Logistic Regression model\n",
|
|
||||||
"for reg in regs:\n",
|
|
||||||
" print(\"Regularization rate: {}\".format(reg))\n",
|
|
||||||
" # create a bunch of child runs\n",
|
|
||||||
" with root_run.child_run(\"reg-\" + str(reg)) as run:\n",
|
|
||||||
" # create a new Logistic Regression model.\n",
|
|
||||||
" lr = LogisticRegression(regParam=reg)\n",
|
|
||||||
" \n",
|
|
||||||
" # put together the pipeline\n",
|
|
||||||
" pipe = Pipeline(stages=[*si_xvars, *ohe_xvars, si_label, assembler, lr])\n",
|
|
||||||
"\n",
|
|
||||||
" # train the model\n",
|
|
||||||
" model_p = pipe.fit(train)\n",
|
|
||||||
" \n",
|
|
||||||
" # make prediction\n",
|
|
||||||
" pred = model_p.transform(test)\n",
|
|
||||||
" \n",
|
|
||||||
" # evaluate. note only 2 metrics are supported out of the box by Spark ML.\n",
|
|
||||||
" bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n",
|
|
||||||
" au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n",
|
|
||||||
" au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
|
|
||||||
"\n",
|
|
||||||
" print(\"Area under ROC: {}\".format(au_roc))\n",
|
|
||||||
" print(\"Area Under PR: {}\".format(au_prc))\n",
|
|
||||||
" \n",
|
|
||||||
" # log reg, au_roc, au_prc and feature names in run history\n",
|
|
||||||
" run.log(\"reg\", reg)\n",
|
|
||||||
" run.log(\"au_roc\", au_roc)\n",
|
|
||||||
" run.log(\"au_prc\", au_prc)\n",
|
|
||||||
" run.log_list(\"columns\", train.columns)\n",
|
|
||||||
"\n",
|
|
||||||
" # save model\n",
|
|
||||||
" model_p.write().overwrite().save(model_name)\n",
|
|
||||||
" \n",
|
|
||||||
" # upload the serialized model into run history record\n",
|
|
||||||
" mdl, ext = model_name.split(\".\")\n",
|
|
||||||
" model_zip = mdl + \".zip\"\n",
|
|
||||||
" shutil.make_archive(mdl, 'zip', model_dbfs)\n",
|
|
||||||
" run.upload_file(\"outputs/\" + model_name, model_zip) \n",
|
|
||||||
" #run.upload_file(\"outputs/\" + model_name, path_or_stream = model_dbfs) #cannot deal with folders\n",
|
|
||||||
"\n",
|
|
||||||
" # now delete the serialized model from local folder since it is already uploaded to run history \n",
|
|
||||||
" shutil.rmtree(model_dbfs)\n",
|
|
||||||
" os.remove(model_zip)\n",
|
|
||||||
" \n",
|
|
||||||
"# Declare run completed\n",
|
|
||||||
"root_run.complete()\n",
|
|
||||||
"root_run_id = root_run.id\n",
|
|
||||||
"print (\"run id:\", root_run.id)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"metrics = root_run.get_metrics(recursive=True)\n",
|
|
||||||
"best_run_id = max(metrics, key = lambda k: metrics[k]['au_roc'])\n",
|
|
||||||
"print(best_run_id, metrics[best_run_id]['au_roc'], metrics[best_run_id]['reg'])"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Get the best run\n",
|
|
||||||
"child_runs = {}\n",
|
|
||||||
"\n",
|
|
||||||
"for r in root_run.get_children():\n",
|
|
||||||
" child_runs[r.id] = r\n",
|
|
||||||
" \n",
|
|
||||||
"best_run = child_runs[best_run_id]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Download the model from the best run to a local folder\n",
|
|
||||||
"best_model_file_name = \"best_model.zip\"\n",
|
|
||||||
"best_run.download_file(name = 'outputs/' + model_name, output_file_path = best_model_file_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Model Evaluation"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"##unzip the model to dbfs (as load() seems to require that) and load it.\n",
|
|
||||||
"if os.path.isfile(model_dbfs) or os.path.isdir(model_dbfs):\n",
|
|
||||||
" shutil.rmtree(model_dbfs)\n",
|
|
||||||
"shutil.unpack_archive(best_model_file_name, model_dbfs)\n",
|
|
||||||
"\n",
|
|
||||||
"model_p_best = PipelineModel.load(model_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# make prediction\n",
|
|
||||||
"pred = model_p_best.transform(test)\n",
|
|
||||||
"output = pred[['hours_per_week','age','workclass','marital_status','income','prediction']]\n",
|
|
||||||
"display(output.limit(5))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# evaluate. note only 2 metrics are supported out of the box by Spark ML.\n",
|
|
||||||
"bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n",
|
|
||||||
"au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n",
|
|
||||||
"au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"Area under ROC: {}\".format(au_roc))\n",
|
|
||||||
"print(\"Area Under PR: {}\".format(au_prc))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Model Persistence"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"##NOTE: by default the model is saved to and loaded from /dbfs/ instead of cwd!\n",
|
|
||||||
"model_p_best.write().overwrite().save(model_name)\n",
|
|
||||||
"print(\"saved model to {}\".format(model_dbfs))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"%sh\n",
|
|
||||||
"\n",
|
|
||||||
"ls -la /dbfs/AdultCensus_runHistory.mml/*"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"dbutils.notebook.exit(\"success\")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
},
|
|
||||||
"name": "build-model-run-history-03",
|
|
||||||
"notebookId": 3836944406456339
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
@@ -1,324 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Please ensure you have run all previous notebooks in sequence before running this.\n",
|
|
||||||
"\n",
|
|
||||||
"Please Register Azure Container Instance(ACI) using Azure Portal: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services#portal in your subscription before using the SDK to deploy your ML model to ACI."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Set auth to be used by workspace related APIs.\n",
|
|
||||||
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
|
|
||||||
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
|
|
||||||
"auth = None"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
|
||||||
" 'Azure region: ' + ws.location, \n",
|
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
|
||||||
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"##NOTE: service deployment always gets the model from the current working dir.\n",
|
|
||||||
"import os\n",
|
|
||||||
"\n",
|
|
||||||
"model_name = \"AdultCensus_runHistory.mml\" # \n",
|
|
||||||
"model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"copy model from dbfs to local\")\n",
|
|
||||||
"model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n",
|
|
||||||
"dbutils.fs.cp(model_name, model_local, True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Register the model\n",
|
|
||||||
"from azureml.core.model import Model\n",
|
|
||||||
"mymodel = Model.register(model_path = model_name, # this points to a local file\n",
|
|
||||||
" model_name = model_name, # this is the name the model is registered as, am using same name for both path and name. \n",
|
|
||||||
" description = \"ADB trained model by Parashar\",\n",
|
|
||||||
" workspace = ws)\n",
|
|
||||||
"\n",
|
|
||||||
"print(mymodel.name, mymodel.description, mymodel.version)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#%%writefile score_sparkml.py\n",
|
|
||||||
"score_sparkml = \"\"\"\n",
|
|
||||||
" \n",
|
|
||||||
"import json\n",
|
|
||||||
" \n",
|
|
||||||
"def init():\n",
|
|
||||||
" # One-time initialization of PySpark and predictive model\n",
|
|
||||||
" import pyspark\n",
|
|
||||||
" from azureml.core.model import Model\n",
|
|
||||||
" from pyspark.ml import PipelineModel\n",
|
|
||||||
" \n",
|
|
||||||
" global trainedModel\n",
|
|
||||||
" global spark\n",
|
|
||||||
" \n",
|
|
||||||
" spark = pyspark.sql.SparkSession.builder.appName(\"ADB and AML notebook by Parashar\").getOrCreate()\n",
|
|
||||||
" model_name = \"{model_name}\" #interpolated\n",
|
|
||||||
" model_path = Model.get_model_path(model_name)\n",
|
|
||||||
" trainedModel = PipelineModel.load(model_path)\n",
|
|
||||||
" \n",
|
|
||||||
"def run(input_json):\n",
|
|
||||||
" if isinstance(trainedModel, Exception):\n",
|
|
||||||
" return json.dumps({{\"trainedModel\":str(trainedModel)}})\n",
|
|
||||||
" \n",
|
|
||||||
" try:\n",
|
|
||||||
" sc = spark.sparkContext\n",
|
|
||||||
" input_list = json.loads(input_json)\n",
|
|
||||||
" input_rdd = sc.parallelize(input_list)\n",
|
|
||||||
" input_df = spark.read.json(input_rdd)\n",
|
|
||||||
" \n",
|
|
||||||
" # Compute prediction\n",
|
|
||||||
" prediction = trainedModel.transform(input_df)\n",
|
|
||||||
" #result = prediction.first().prediction\n",
|
|
||||||
" predictions = prediction.collect()\n",
|
|
||||||
" \n",
|
|
||||||
" #Get each scored result\n",
|
|
||||||
" preds = [str(x['prediction']) for x in predictions]\n",
|
|
||||||
" result = \",\".join(preds)\n",
|
|
||||||
" # you can return any data type as long as it is JSON-serializable\n",
|
|
||||||
" return result.tolist()\n",
|
|
||||||
" except Exception as e:\n",
|
|
||||||
" result = str(e)\n",
|
|
||||||
" return result\n",
|
|
||||||
" \n",
|
|
||||||
"\"\"\".format(model_name=model_name)\n",
|
|
||||||
" \n",
|
|
||||||
"exec(score_sparkml)\n",
|
|
||||||
" \n",
|
|
||||||
"with open(\"score_sparkml.py\", \"w\") as file:\n",
|
|
||||||
" file.write(score_sparkml)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies \n",
|
|
||||||
"\n",
|
|
||||||
"myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) #showing how to add libs as an eg. - not needed for this model.\n",
|
|
||||||
"\n",
|
|
||||||
"with open(\"mydeployenv.yml\",\"w\") as f:\n",
|
|
||||||
" f.write(myacienv.serialize_to_string())"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#deploy to ACI\n",
|
|
||||||
"from azureml.core.webservice import AciWebservice, Webservice\n",
|
|
||||||
"\n",
|
|
||||||
"myaci_config = AciWebservice.deploy_configuration(\n",
|
|
||||||
" cpu_cores = 2, \n",
|
|
||||||
" memory_gb = 2, \n",
|
|
||||||
" tags = {'name':'Databricks Azure ML ACI'}, \n",
|
|
||||||
" description = 'This is for ADB and AML example. Azure Databricks & Azure ML SDK demo with ACI by Parashar.')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# this will take 10-15 minutes to finish\n",
|
|
||||||
"\n",
|
|
||||||
"service_name = \"aciws\"\n",
|
|
||||||
"runtime = \"spark-py\" \n",
|
|
||||||
"driver_file = \"score_sparkml.py\"\n",
|
|
||||||
"my_conda_file = \"mydeployenv.yml\"\n",
|
|
||||||
"\n",
|
|
||||||
"# image creation\n",
|
|
||||||
"from azureml.core.image import ContainerImage\n",
|
|
||||||
"myimage_config = ContainerImage.image_configuration(execution_script = driver_file, \n",
|
|
||||||
" runtime = runtime, \n",
|
|
||||||
" conda_file = my_conda_file)\n",
|
|
||||||
"\n",
|
|
||||||
"# Webservice creation\n",
|
|
||||||
"myservice = Webservice.deploy_from_model(\n",
|
|
||||||
" workspace=ws, \n",
|
|
||||||
" name=service_name,\n",
|
|
||||||
" deployment_config = myaci_config,\n",
|
|
||||||
" models = [mymodel],\n",
|
|
||||||
" image_config = myimage_config\n",
|
|
||||||
" )\n",
|
|
||||||
"\n",
|
|
||||||
"myservice.wait_for_deployment(show_output=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"help(Webservice)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# List images by ws\n",
|
|
||||||
"\n",
|
|
||||||
"for i in ContainerImage.list(workspace = ws):\n",
|
|
||||||
" print('{}(v.{} [{}]) stored at {} with build log {}'.format(i.name, i.version, i.creation_state, i.image_location, i.image_build_log_uri))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#for using the Web HTTP API \n",
|
|
||||||
"print(myservice.scoring_uri)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import json\n",
|
|
||||||
"\n",
|
|
||||||
"#get the some sample data\n",
|
|
||||||
"test_data_path = \"AdultCensusIncomeTest\"\n",
|
|
||||||
"test = spark.read.parquet(test_data_path).limit(5)\n",
|
|
||||||
"\n",
|
|
||||||
"test_json = json.dumps(test.toJSON().collect())\n",
|
|
||||||
"\n",
|
|
||||||
"print(test_json)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#using data defined above predict if income is >50K (1) or <=50K (0)\n",
|
|
||||||
"myservice.run(input_data=test_json)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#comment to not delete the web service\n",
|
|
||||||
"myservice.delete()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
},
|
|
||||||
"name": "deploy-to-aci-04",
|
|
||||||
"notebookId": 3836944406456376
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
@@ -1,250 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"This notebook uses image from ACI notebook for deploying to AKS."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Set auth to be used by workspace related APIs.\n",
|
|
||||||
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
|
|
||||||
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
|
|
||||||
"auth = None"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
|
||||||
" 'Azure region: ' + ws.location, \n",
|
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
|
||||||
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# List images by ws\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.core.image import ContainerImage\n",
|
|
||||||
"for i in ContainerImage.list(workspace = ws):\n",
|
|
||||||
" print('{}(v.{} [{}]) stored at {} with build log {}'.format(i.name, i.version, i.creation_state, i.image_location, i.image_build_log_uri))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.image import Image\n",
|
|
||||||
"myimage = Image(workspace=ws, name=\"aciws\")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#create AKS compute\n",
|
|
||||||
"#it may take 20-25 minutes to create a new cluster\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.core.compute import AksCompute, ComputeTarget\n",
|
|
||||||
"\n",
|
|
||||||
"# Use the default configuration (can also provide parameters to customize)\n",
|
|
||||||
"prov_config = AksCompute.provisioning_configuration()\n",
|
|
||||||
"\n",
|
|
||||||
"aks_name = 'ps-aks-demo2' \n",
|
|
||||||
"\n",
|
|
||||||
"# Create the cluster\n",
|
|
||||||
"aks_target = ComputeTarget.create(workspace = ws, \n",
|
|
||||||
" name = aks_name, \n",
|
|
||||||
" provisioning_configuration = prov_config)\n",
|
|
||||||
"\n",
|
|
||||||
"aks_target.wait_for_completion(show_output = True)\n",
|
|
||||||
"\n",
|
|
||||||
"print(aks_target.provisioning_state)\n",
|
|
||||||
"print(aks_target.provisioning_errors)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.webservice import Webservice\n",
|
|
||||||
"help( Webservice.deploy_from_image)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.webservice import Webservice, AksWebservice\n",
|
|
||||||
"from azureml.core.image import ContainerImage\n",
|
|
||||||
"\n",
|
|
||||||
"#Set the web service configuration (using default here with app insights)\n",
|
|
||||||
"aks_config = AksWebservice.deploy_configuration(enable_app_insights=True)\n",
|
|
||||||
"\n",
|
|
||||||
"#unique service name\n",
|
|
||||||
"service_name ='ps-aks-service'\n",
|
|
||||||
"\n",
|
|
||||||
"# Webservice creation using single command, there is a variant to use image directly as well.\n",
|
|
||||||
"aks_service = Webservice.deploy_from_image(\n",
|
|
||||||
" workspace=ws, \n",
|
|
||||||
" name=service_name,\n",
|
|
||||||
" deployment_config = aks_config,\n",
|
|
||||||
" image = myimage,\n",
|
|
||||||
" deployment_target = aks_target\n",
|
|
||||||
" )\n",
|
|
||||||
"\n",
|
|
||||||
"aks_service.wait_for_deployment(show_output=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"aks_service.deployment_status"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#for using the Web HTTP API \n",
|
|
||||||
"print(aks_service.scoring_uri)\n",
|
|
||||||
"print(aks_service.get_keys())"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import json\n",
|
|
||||||
"\n",
|
|
||||||
"#get the some sample data\n",
|
|
||||||
"test_data_path = \"AdultCensusIncomeTest\"\n",
|
|
||||||
"test = spark.read.parquet(test_data_path).limit(5)\n",
|
|
||||||
"\n",
|
|
||||||
"test_json = json.dumps(test.toJSON().collect())\n",
|
|
||||||
"\n",
|
|
||||||
"print(test_json)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#using data defined above predict if income is >50K (1) or <=50K (0)\n",
|
|
||||||
"aks_service.run(input_data=test_json)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#comment to not delete the web service\n",
|
|
||||||
"aks_service.delete()\n",
|
|
||||||
"#image.delete()\n",
|
|
||||||
"#model.delete()\n",
|
|
||||||
"aks_target.delete() "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
},
|
|
||||||
"name": "deploy-to-aks-existingimage-05",
|
|
||||||
"notebookId": 1030695628045968
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Data Ingestion"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"import urllib"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Download AdultCensusIncome.csv from Azure CDN. This file has 32,561 rows.\n",
|
|
||||||
"dataurl = \"https://amldockerdatasets.azureedge.net/AdultCensusIncome.csv\"\n",
|
|
||||||
"datafile = \"AdultCensusIncome.csv\"\n",
|
|
||||||
"datafile_dbfs = os.path.join(\"/dbfs\", datafile)\n",
|
|
||||||
"\n",
|
|
||||||
"if os.path.isfile(datafile_dbfs):\n",
|
|
||||||
" print(\"found {} at {}\".format(datafile, datafile_dbfs))\n",
|
|
||||||
"else:\n",
|
|
||||||
" print(\"downloading {} to {}\".format(datafile, datafile_dbfs))\n",
|
|
||||||
" urllib.request.urlretrieve(dataurl, datafile_dbfs)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Create a Spark dataframe out of the csv file.\n",
|
|
||||||
"data_all = sqlContext.read.format('csv').options(header='true', inferSchema='true', ignoreLeadingWhiteSpace='true', ignoreTrailingWhiteSpace='true').load(datafile)\n",
|
|
||||||
"print(\"({}, {})\".format(data_all.count(), len(data_all.columns)))\n",
|
|
||||||
"data_all.printSchema()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#renaming columns\n",
|
|
||||||
"columns_new = [col.replace(\"-\", \"_\") for col in data_all.columns]\n",
|
|
||||||
"data_all = data_all.toDF(*columns_new)\n",
|
|
||||||
"data_all.printSchema()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"display(data_all.limit(5))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Data Preparation"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Choose feature columns and the label column.\n",
|
|
||||||
"label = \"income\"\n",
|
|
||||||
"xvars = set(data_all.columns) - {label}\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"label = {}\".format(label))\n",
|
|
||||||
"print(\"features = {}\".format(xvars))\n",
|
|
||||||
"\n",
|
|
||||||
"data = data_all.select([*xvars, label])\n",
|
|
||||||
"\n",
|
|
||||||
"# Split data into train and test.\n",
|
|
||||||
"train, test = data.randomSplit([0.75, 0.25], seed=123)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"train ({}, {})\".format(train.count(), len(train.columns)))\n",
|
|
||||||
"print(\"test ({}, {})\".format(test.count(), len(test.columns)))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Data Persistence"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Write the train and test data sets to intermediate storage\n",
|
|
||||||
"train_data_path = \"AdultCensusIncomeTrain\"\n",
|
|
||||||
"test_data_path = \"AdultCensusIncomeTest\"\n",
|
|
||||||
"\n",
|
|
||||||
"train_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTrain\")\n",
|
|
||||||
"test_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTest\")\n",
|
|
||||||
"\n",
|
|
||||||
"train.write.mode('overwrite').parquet(train_data_path)\n",
|
|
||||||
"test.write.mode('overwrite').parquet(test_data_path)\n",
|
|
||||||
"print(\"train and test datasets saved to {} and {}\".format(train_data_path_dbfs, test_data_path_dbfs))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": []
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
},
|
|
||||||
"name": "ingest-data-02",
|
|
||||||
"notebookId": 3836944406456362
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
@@ -1,190 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n",
|
|
||||||
"\n",
|
|
||||||
"**install azureml-sdk**\n",
|
|
||||||
"* Source: Upload Python Egg or PyPi\n",
|
|
||||||
"* PyPi Name: `azureml-sdk[databricks]`\n",
|
|
||||||
"* Select Install Library"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number - based on build number of preview/master.\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Please specify the Azure subscription Id, resource group name, workspace name, and the region in which you want to create the Azure Machine Learning Workspace.\n",
|
|
||||||
"\n",
|
|
||||||
"You can get the value of your Azure subscription ID from the Azure Portal, and then selecting Subscriptions from the menu on the left.\n",
|
|
||||||
"\n",
|
|
||||||
"For the resource_group, use the name of the resource group that contains your Azure Databricks Workspace.\n",
|
|
||||||
"\n",
|
|
||||||
"NOTE: If you provide a resource group name that does not exist, the resource group will be automatically created. This may or may not succeed in your environment, depending on the permissions you have on your Azure Subscription."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# subscription_id = \"<your-subscription-id>\"\n",
|
|
||||||
"# resource_group = \"<your-existing-resource-group>\"\n",
|
|
||||||
"# workspace_name = \"<a-new-or-existing-workspace; it is unrelated to Databricks workspace>\"\n",
|
|
||||||
"# workspace_region = \"<your-resource group-region>\""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Set auth to be used by workspace related APIs.\n",
|
|
||||||
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
|
|
||||||
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
|
|
||||||
"auth = None"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# import the Workspace class and check the azureml SDK version\n",
|
|
||||||
"# exist_ok checks if workspace exists or not.\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.create(name = workspace_name,\n",
|
|
||||||
" subscription_id = subscription_id,\n",
|
|
||||||
" resource_group = resource_group, \n",
|
|
||||||
" location = workspace_region,\n",
|
|
||||||
" auth = auth,\n",
|
|
||||||
" exist_ok=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#get workspace details\n",
|
|
||||||
"ws.get_details()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace(workspace_name = workspace_name,\n",
|
|
||||||
" subscription_id = subscription_id,\n",
|
|
||||||
" resource_group = resource_group,\n",
|
|
||||||
" auth = auth)\n",
|
|
||||||
"\n",
|
|
||||||
"# persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n",
|
|
||||||
"ws.write_config()\n",
|
|
||||||
"#if you need to give a different path/filename please use this\n",
|
|
||||||
"#write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"help(Workspace)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# import the Workspace class and check the azureml SDK version\n",
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"#ws = Workspace.from_config(<full path>)\n",
|
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
|
||||||
" 'Azure region: ' + ws.location, \n",
|
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
|
||||||
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.6"
|
|
||||||
},
|
|
||||||
"name": "installation-and-configuration-01",
|
|
||||||
"notebookId": 3688394266452835
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
70
how-to-use-azureml/azure-databricks/automl/README.md
Normal file
70
how-to-use-azureml/azure-databricks/automl/README.md
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
# Automated ML introduction
|
||||||
|
Automated machine learning (automated ML) builds high quality machine learning models for you by automating model and hyperparameter selection. Bring a labelled dataset that you want to build a model for, automated ML will give you a high quality machine learning model that you can use for predictions.
|
||||||
|
|
||||||
|
|
||||||
|
If you are new to Data Science, automated ML will help you get jumpstarted by simplifying machine learning model building. It abstracts you from needing to perform model selection, hyperparameter selection and in one step creates a high quality trained model for you to use.
|
||||||
|
|
||||||
|
If you are an experienced data scientist, automated ML will help increase your productivity by intelligently performing the model and hyperparameter selection for your training and generates high quality models much quicker than manually specifying several combinations of the parameters and running training jobs. Automated ML provides visibility and access to all the training jobs and the performance characteristics of the models to help you further tune the pipeline if you desire.
|
||||||
|
|
||||||
|
# Install Instructions using Azure Databricks :
|
||||||
|
|
||||||
|
#### For Databricks non ML runtime 7.1(scala 2.21, spark 3.0.0) and up, Install Automated Machine Learning sdk by adding and running the following command as the first cell of your notebook. This will install AutoML dependencies specific for your notebook.
|
||||||
|
|
||||||
|
%pip install --upgrade --force-reinstall -r https://aka.ms/automl_linux_requirements.txt
|
||||||
|
|
||||||
|
|
||||||
|
#### For Databricks non ML runtime 7.0 and lower, Install Automated Machine Learning sdk using init script as shown below before running the notebook.**
|
||||||
|
|
||||||
|
**Create the Azure Databricks cluster-scoped init script 'azureml-cluster-init.sh' as below
|
||||||
|
|
||||||
|
1. Create the base directory you want to store the init script in if it does not exist.
|
||||||
|
```
|
||||||
|
dbutils.fs.mkdirs("dbfs:/databricks/init/")
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create the script azureml-cluster-init.sh
|
||||||
|
```
|
||||||
|
dbutils.fs.put("/databricks/init/azureml-cluster-init.sh","""
|
||||||
|
#!/bin/bash
|
||||||
|
set -ex
|
||||||
|
/databricks/python/bin/pip install --upgrade --force-reinstall -r https://aka.ms/automl_linux_requirements.txt
|
||||||
|
""", True)
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Check that the script exists.
|
||||||
|
```
|
||||||
|
display(dbutils.fs.ls("dbfs:/databricks/init/azureml-cluster-init.sh"))
|
||||||
|
```
|
||||||
|
|
||||||
|
**Install libraries to cluster using init script 'azureml-cluster-init.sh' created in previous step
|
||||||
|
|
||||||
|
1. Configure the cluster to run the script.
|
||||||
|
* Using the cluster configuration page
|
||||||
|
1. On the cluster configuration page, click the Advanced Options toggle.
|
||||||
|
1. At the bottom of the page, click the Init Scripts tab.
|
||||||
|
1. In the Destination drop-down, select a destination type. Example: 'DBFS'
|
||||||
|
1. Specify a path to the init script.
|
||||||
|
```
|
||||||
|
dbfs:/databricks/init/azureml-cluster-init.sh
|
||||||
|
```
|
||||||
|
1. Click Add
|
||||||
|
|
||||||
|
* Using the API.
|
||||||
|
```
|
||||||
|
curl -n -X POST -H 'Content-Type: application/json' -d '{
|
||||||
|
"cluster_id": "<cluster_id>",
|
||||||
|
"num_workers": <num_workers>,
|
||||||
|
"spark_version": "<spark_version>",
|
||||||
|
"node_type_id": "<node_type_id>",
|
||||||
|
"cluster_log_conf": {
|
||||||
|
"dbfs" : {
|
||||||
|
"destination": "dbfs:/cluster-logs"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"init_scripts": [ {
|
||||||
|
"dbfs": {
|
||||||
|
"destination": "dbfs:/databricks/init/azureml-cluster-init.sh"
|
||||||
|
}
|
||||||
|
} ]
|
||||||
|
}' https://<databricks-instance>/api/2.0/clusters/edit
|
||||||
|
```
|
||||||
@@ -13,32 +13,46 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Automated ML on Azure Databricks\n",
|
"## AutoML Installation\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example we use the scikit-learn's <a href=\"http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset\" target=\"_blank\">digit dataset</a> to showcase how you can use AutoML for a simple classification problem.\n",
|
"**For Databricks non ML runtime 7.1(scala 2.21, spark 3.0.0) and up, Install AML sdk by running the following command in the first cell of the notebook.**\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you will learn how to:\n",
|
"%pip install -r https://aka.ms/automl_linux_requirements.txt\n",
|
||||||
"1. Create Azure Machine Learning Workspace object and initialize your notebook directory to easily reload this object from a configuration file.\n",
|
|
||||||
"2. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"3. Configure Automated ML using `AutoMLConfig`.\n",
|
|
||||||
"4. Train the model using Azure Databricks.\n",
|
|
||||||
"5. Explore the results.\n",
|
|
||||||
"6. Viewing the engineered names for featurized data and featurization summary for all raw features.\n",
|
|
||||||
"7. Test the best fitted model.\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"Before running this notebook, please follow the <a href=\"https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks\" target=\"_blank\">readme for using Automated ML on Azure Databricks</a> for installing necessary libraries to your cluster."
|
"**For Databricks non ML runtime 7.0 and lower, Install AML sdk using init script as shown in [readme](readme.md) before running this notebook.**\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"We support installing AML SDK with Automated ML as library from GUI. When attaching a library follow <a href=\"https://docs.databricks.com/user-guide/libraries.html\" target=\"_blank\">this link</a> and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n",
|
"# AutoML : Classification with Local Compute on Azure DataBricks\n",
|
||||||
"\n",
|
"\n",
|
||||||
"**azureml-sdk with automated ml**\n",
|
"In this example we use the scikit-learn's to showcase how you can use AutoML for a simple classification problem.\n",
|
||||||
"* Source: Upload Python Egg or PyPi\n",
|
"\n",
|
||||||
"* PyPi Name: `azureml-sdk[automl_databricks]`\n",
|
"In this notebook you will learn how to:\n",
|
||||||
"* Select Install Library"
|
"1. Create Azure Machine Learning Workspace object and initialize your notebook directory to easily reload this object from a configuration file.\n",
|
||||||
|
"2. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
|
"3. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"4. Train the model using AzureDataBricks.\n",
|
||||||
|
"5. Explore the results.\n",
|
||||||
|
"6. Test the best fitted model.\n",
|
||||||
|
"\n",
|
||||||
|
"Prerequisites:\n",
|
||||||
|
"Before running this notebook, please follow the readme for installing necessary libraries to your cluster."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Register Machine Learning Services Resource Provider\n",
|
||||||
|
"Microsoft.MachineLearningServices only needs to be registed once in the subscription. To register it:\n",
|
||||||
|
"Start the Azure portal.\n",
|
||||||
|
"Select your All services and then Subscription.\n",
|
||||||
|
"Select the subscription that you want to use.\n",
|
||||||
|
"Click on Resource providers\n",
|
||||||
|
"Click the Register link next to Microsoft.MachineLearningServices"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -145,31 +159,8 @@
|
|||||||
" resource_group = resource_group)\n",
|
" resource_group = resource_group)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n",
|
"# Persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n",
|
||||||
"ws.write_config()"
|
"ws.write_config()\n",
|
||||||
]
|
"write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)"
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Create a Folder to Host Sample Projects\n",
|
|
||||||
"Finally, create a folder where all the sample projects will be hosted."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"\n",
|
|
||||||
"sample_projects_folder = './sample_projects'\n",
|
|
||||||
"\n",
|
|
||||||
"if not os.path.isdir(sample_projects_folder):\n",
|
|
||||||
" os.mkdir(sample_projects_folder)\n",
|
|
||||||
" \n",
|
|
||||||
"print('Sample projects will be created in {}.'.format(sample_projects_folder))"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -178,7 +169,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Create an Experiment\n",
|
"## Create an Experiment\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -191,6 +182,7 @@
|
|||||||
"import os\n",
|
"import os\n",
|
||||||
"import random\n",
|
"import random\n",
|
||||||
"import time\n",
|
"import time\n",
|
||||||
|
"import json\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from matplotlib import pyplot as plt\n",
|
"from matplotlib import pyplot as plt\n",
|
||||||
"from matplotlib.pyplot import imshow\n",
|
"from matplotlib.pyplot import imshow\n",
|
||||||
@@ -212,7 +204,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
"# Choose a name for the experiment and specify the project folder.\n",
|
||||||
"experiment_name = 'automl-local-classification'\n",
|
"experiment_name = 'automl-local-classification'\n",
|
||||||
"project_folder = './sample_projects/automl-local-classification'\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -222,7 +213,6 @@
|
|||||||
"output['Workspace Name'] = ws.name\n",
|
"output['Workspace Name'] = ws.name\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output['Location'] = ws.location\n",
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
"output['Experiment Name'] = experiment.name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
"pd.DataFrame(data = output, index = ['']).T"
|
"pd.DataFrame(data = output, index = ['']).T"
|
||||||
@@ -232,9 +222,16 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Diagnostics\n",
|
"## Load Training Data Using Dataset"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Automated ML takes a `TabularDataset` as input.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Opt-in diagnostics for better experience, quality, and security of future releases."
|
"You are free to use the data preparation libraries/tools of your choice to do the require preparation and once you are done, you can write it to a datastore and create a TabularDataset from it."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -243,24 +240,20 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.telemetry import set_diagnostics_collection\n",
|
"# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n",
|
||||||
"set_diagnostics_collection(send_diagnostics = True)"
|
"from azureml.core.dataset import Dataset\n",
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Registering Datastore"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Datastore is the way to save connection information to a storage service (e.g. Azure Blob, Azure Data Lake, Azure SQL) information to your workspace so you can access them without exposing credentials in your code. The first thing you will need to do is register a datastore, you can refer to our [python SDK documentation](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.datastore.datastore?view=azure-ml-py) on how to register datastores. __Note: for best security practices, please do not check in code that contains registering datastores with secrets into your source control__\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"The code below registers a datastore pointing to a publicly readable blob container."
|
"example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(example_data)\n",
|
||||||
|
"dataset.take(5).to_pandas_dataframe()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Review the TabularDataset\n",
|
||||||
|
"You can peek the result of a TabularDataset at any range using `skip(i)` and `take(j).to_pandas_dataframe()`. Doing so evaluates only j records for all the steps in the TabularDataset, which makes it fast even against large datasets."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -269,111 +262,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core import Datastore\n",
|
"training_data = dataset.drop_columns(columns=['FBI Code'])\n",
|
||||||
"\n",
|
"label = 'Primary Type'"
|
||||||
"datastore_name = 'demo_training'\n",
|
|
||||||
"container_name = 'digits' \n",
|
|
||||||
"account_name = 'automlpublicdatasets'\n",
|
|
||||||
"Datastore.register_azure_blob_container(\n",
|
|
||||||
" workspace = ws, \n",
|
|
||||||
" datastore_name = datastore_name, \n",
|
|
||||||
" container_name = container_name, \n",
|
|
||||||
" account_name = account_name,\n",
|
|
||||||
" overwrite = True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Below is an example on how to register a private blob container\n",
|
|
||||||
"```python\n",
|
|
||||||
"datastore = Datastore.register_azure_blob_container(\n",
|
|
||||||
" workspace = ws, \n",
|
|
||||||
" datastore_name = 'example_datastore', \n",
|
|
||||||
" container_name = 'example-container', \n",
|
|
||||||
" account_name = 'storageaccount',\n",
|
|
||||||
" account_key = 'accountkey'\n",
|
|
||||||
")\n",
|
|
||||||
"```\n",
|
|
||||||
"The example below shows how to register an Azure Data Lake store. Please make sure you have granted the necessary permissions for the service principal to access the data lake.\n",
|
|
||||||
"```python\n",
|
|
||||||
"datastore = Datastore.register_azure_data_lake(\n",
|
|
||||||
" workspace = ws,\n",
|
|
||||||
" datastore_name = 'example_datastore',\n",
|
|
||||||
" store_name = 'adlsstore',\n",
|
|
||||||
" tenant_id = 'tenant-id-of-service-principal',\n",
|
|
||||||
" client_id = 'client-id-of-service-principal',\n",
|
|
||||||
" client_secret = 'client-secret-of-service-principal'\n",
|
|
||||||
")\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Load Training Data Using DataPrep"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Automated ML takes a Dataflow as input.\n",
|
|
||||||
"\n",
|
|
||||||
"If you are familiar with Pandas and have done your data preparation work in Pandas already, you can use the `read_pandas_dataframe` method in dprep to convert the DataFrame to a Dataflow.\n",
|
|
||||||
"```python\n",
|
|
||||||
"df = pd.read_csv(...)\n",
|
|
||||||
"# apply some transforms\n",
|
|
||||||
"dprep.read_pandas_dataframe(df, temp_folder='/path/accessible/by/both/driver/and/worker')\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"If you just need to ingest data without doing any preparation, you can directly use AzureML Data Prep (Data Prep) to do so. The code below demonstrates this scenario. Data Prep also has data preparation capabilities, we have many [sample notebooks](https://github.com/Microsoft/AMLDataPrepDocs) demonstrating the capabilities.\n",
|
|
||||||
"\n",
|
|
||||||
"You will get the datastore you registered previously and pass it to Data Prep for reading. The data comes from the digits dataset: `sklearn.datasets.load_digits()`. `DataPath` points to a specific location within a datastore. "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.dataprep as dprep\n",
|
|
||||||
"from azureml.data.datapath import DataPath\n",
|
|
||||||
"\n",
|
|
||||||
"datastore = Datastore.get(workspace = ws, datastore_name = datastore_name)\n",
|
|
||||||
"\n",
|
|
||||||
"X_train = dprep.read_csv(datastore.path('X.csv'))\n",
|
|
||||||
"y_train = dprep.read_csv(datastore.path('y.csv')).to_long(dprep.ColumnSelector(term='.*', use_regex = True))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Review the Data Preparation Result\n",
|
|
||||||
"You can peek the result of a Dataflow at any range using `skip(i)` and `head(j)`. Doing so evaluates only j records for all the steps in the Dataflow, which makes it fast even against large datasets."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X_train.get_profile()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"y_train.get_profile()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -391,14 +281,11 @@
|
|||||||
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
|
||||||
"|**spark_context**|Spark Context object. for Databricks, use spark_context=sc|\n",
|
"|**spark_context**|Spark Context object. for Databricks, use spark_context=sc|\n",
|
||||||
"|**max_concurrent_iterations**|Maximum number of iterations to execute in parallel. This should be <= number of worker nodes in your Azure Databricks cluster.|\n",
|
"|**max_concurrent_iterations**|Maximum number of iterations to execute in parallel. This should be <= number of worker nodes in your Azure Databricks cluster.|\n",
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]<br>Multi-class targets. An indicator matrix turns on multilabel classification. This should be an array of integers.|\n",
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n",
|
"|**label_column_name**|The name of the label column.|"
|
||||||
"|**preprocess**|set this to True to enable pre-processing of data eg. string to numeric using one-hot encoding|\n",
|
|
||||||
"|**exit_score**|Target score for experiment. It is associated with the metric. eg. exit_score=0.995 will exit experiment after that|"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -411,15 +298,13 @@
|
|||||||
" debug_log = 'automl_errors.log',\n",
|
" debug_log = 'automl_errors.log',\n",
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
" primary_metric = 'AUC_weighted',\n",
|
||||||
" iteration_timeout_minutes = 10,\n",
|
" iteration_timeout_minutes = 10,\n",
|
||||||
" iterations = 3,\n",
|
" iterations = 5,\n",
|
||||||
" preprocess = True,\n",
|
|
||||||
" n_cross_validations = 10,\n",
|
" n_cross_validations = 10,\n",
|
||||||
" max_concurrent_iterations = 2, #change it based on number of worker nodes\n",
|
" max_concurrent_iterations = 2, #change it based on number of worker nodes\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" verbosity = logging.INFO,\n",
|
||||||
" spark_context=sc, #databricks/spark related\n",
|
" spark_context=sc, #databricks/spark related\n",
|
||||||
" X = X_train, \n",
|
" training_data=training_data,\n",
|
||||||
" y = y_train,\n",
|
" label_column_name=label)"
|
||||||
" path = project_folder)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -440,26 +325,6 @@
|
|||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
"local_run = experiment.submit(automl_config, show_output = True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Continue experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run.continue_experiment(iterations=2,\n",
|
|
||||||
" X=X_train, \n",
|
|
||||||
" y=y_train,\n",
|
|
||||||
" spark_context=sc,\n",
|
|
||||||
" show_output=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -482,14 +347,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"displayHTML(\"<a href={} target='_blank'>Your experiment in Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"The following will show the child runs and waits for the parent run to complete."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -510,6 +368,7 @@
|
|||||||
"metricslist = {}\n",
|
"metricslist = {}\n",
|
||||||
"for run in children:\n",
|
"for run in children:\n",
|
||||||
" properties = run.get_properties()\n",
|
" properties = run.get_properties()\n",
|
||||||
|
" #print(properties)\n",
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
" metricslist[int(properties['iteration'])] = metrics\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -521,9 +380,11 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Retrieve the Best Model after the above run is complete \n",
|
"## Deploy\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
"### Retrieve the Best Model\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -532,68 +393,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
"best_run, fitted_model = local_run.get_output()"
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric after the above run is complete based on the child run\n",
|
|
||||||
"Show the run and the model that has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View the engineered names for featurized data\n",
|
|
||||||
"Below we display the engineered feature names generated for the featurized data using the preprocessing featurization."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"fitted_model.named_steps['datatransformer'].get_engineered_feature_names()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View the featurization summary\n",
|
|
||||||
"Below we display the featurization that was performed on different raw features in the user data. For each raw feature in the user data, the following information is displayed:-\n",
|
|
||||||
"- Raw feature name\n",
|
|
||||||
"- Number of engineered features formed out of this raw feature\n",
|
|
||||||
"- Type detected\n",
|
|
||||||
"- If feature was dropped\n",
|
|
||||||
"- List of feature transformations for the raw feature"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"fitted_model.named_steps['datatransformer'].get_featurization_summary()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -611,11 +411,13 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"blob_location = \"https://{}.blob.core.windows.net/{}\".format(account_name, container_name)\n",
|
"dataset_test = Dataset.Tabular.from_delimited_files(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv')\n",
|
||||||
"X_test = pd.read_csv(\"{}./X_valid.csv\".format(blob_location), header=0)\n",
|
"\n",
|
||||||
"y_test = pd.read_csv(\"{}/y_valid.csv\".format(blob_location), header=0)\n",
|
"df_test = dataset_test.to_pandas_dataframe()\n",
|
||||||
"images = pd.read_csv(\"{}/images.csv\".format(blob_location), header=None)\n",
|
"df_test = df_test[pd.notnull(df_test['Primary Type'])]\n",
|
||||||
"images = np.reshape(images.values, (100,8,8))"
|
"\n",
|
||||||
|
"y_test = df_test[['Primary Type']]\n",
|
||||||
|
"X_test = df_test.drop(['Primary Type', 'FBI Code'], axis=1)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -632,35 +434,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Randomly select digits and test.\n",
|
"fitted_model.predict(X_test)"
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test.values[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
|
|
||||||
" fig = plt.figure(3, figsize = (5,5))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" display(fig)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"When deploying an automated ML trained model, please specify _pippackages=['azureml-sdk[automl]']_ in your CondaDependencies.\n",
|
|
||||||
"\n",
|
|
||||||
"Please refer to only the **Deploy** section in this notebook - <a href=\"https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/automated-machine-learning/classification-with-deployment\" target=\"_blank\">Deployment of Automated ML trained model</a>"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": []
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -693,10 +469,10 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.5"
|
"version": "3.6.8"
|
||||||
},
|
},
|
||||||
"name": "auto-ml-classification-local-adb",
|
"name": "auto-ml-classification-local-adb",
|
||||||
"notebookId": 587284549713154
|
"notebookId": 1275190406842063
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 1
|
"nbformat_minor": 1
|
||||||
|
|||||||
@@ -13,12 +13,13 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n",
|
"## AutoML Installation\n",
|
||||||
"\n",
|
"\n",
|
||||||
"**install azureml-sdk with Automated ML**\n",
|
"**For Databricks non ML runtime 7.1(scala 2.21, spark 3.0.0) and up, Install AML sdk by running the following command in the first cell of the notebook.**\n",
|
||||||
"* Source: Upload Python Egg or PyPi\n",
|
"\n",
|
||||||
"* PyPi Name: `azureml-sdk[automl_databricks]`\n",
|
"%pip install --upgrade --force-reinstall -r https://aka.ms/automl_linux_requirements.txt\n",
|
||||||
"* Select Install Library"
|
"\n",
|
||||||
|
"**For Databricks non ML runtime 7.0 and lower, Install AML sdk using init script as shown in [readme](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/azure-databricks/automl/README.md) before running this notebook.**"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -27,7 +28,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# AutoML : Classification with Local Compute on Azure DataBricks with deployment to ACI\n",
|
"# AutoML : Classification with Local Compute on Azure DataBricks with deployment to ACI\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
|
"In this example we use the scikit-learn's to showcase how you can use AutoML for a simple classification problem.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you will learn how to:\n",
|
"In this notebook you will learn how to:\n",
|
||||||
"1. Create Azure Machine Learning Workspace object and initialize your notebook directory to easily reload this object from a configuration file.\n",
|
"1. Create Azure Machine Learning Workspace object and initialize your notebook directory to easily reload this object from a configuration file.\n",
|
||||||
@@ -164,30 +165,6 @@
|
|||||||
"write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)"
|
"write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Create a Folder to Host Sample Projects\n",
|
|
||||||
"Finally, create a folder where all the sample projects will be hosted."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"\n",
|
|
||||||
"sample_projects_folder = './sample_projects'\n",
|
|
||||||
"\n",
|
|
||||||
"if not os.path.isdir(sample_projects_folder):\n",
|
|
||||||
" os.mkdir(sample_projects_folder)\n",
|
|
||||||
" \n",
|
|
||||||
"print('Sample projects will be created in {}.'.format(sample_projects_folder))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -229,7 +206,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
"# Choose a name for the experiment and specify the project folder.\n",
|
||||||
"experiment_name = 'automl-local-classification'\n",
|
"experiment_name = 'automl-local-classification'\n",
|
||||||
"project_folder = './sample_projects/automl-local-classification'\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -239,7 +215,6 @@
|
|||||||
"output['Workspace Name'] = ws.name\n",
|
"output['Workspace Name'] = ws.name\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output['Location'] = ws.location\n",
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
"output['Experiment Name'] = experiment.name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
"pd.DataFrame(data = output, index = ['']).T"
|
"pd.DataFrame(data = output, index = ['']).T"
|
||||||
@@ -249,9 +224,16 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Diagnostics\n",
|
"## Load Training Data Using Dataset"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Automated ML takes a `TabularDataset` as input.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Opt-in diagnostics for better experience, quality, and security of future releases."
|
"You are free to use the data preparation libraries/tools of your choice to do the require preparation and once you are done, you can write it to a datastore and create a TabularDataset from it."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -260,24 +242,20 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.telemetry import set_diagnostics_collection\n",
|
"# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n",
|
||||||
"set_diagnostics_collection(send_diagnostics = True)"
|
"from azureml.core.dataset import Dataset\n",
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Registering Datastore"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Datastore is the way to save connection information to a storage service (e.g. Azure Blob, Azure Data Lake, Azure SQL) information to your workspace so you can access them without exposing credentials in your code. The first thing you will need to do is register a datastore, you can refer to our [python SDK documentation](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.datastore.datastore?view=azure-ml-py) on how to register datastores. __Note: for best security practices, please do not check in code that contains registering datastores with secrets into your source control__\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"The code below registers a datastore pointing to a publicly readable blob container."
|
"example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(example_data)\n",
|
||||||
|
"dataset.take(5).to_pandas_dataframe()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Review the TabularDataset\n",
|
||||||
|
"You can peek the result of a TabularDataset at any range using `skip(i)` and `take(j).to_pandas_dataframe()`. Doing so evaluates only j records for all the steps in the TabularDataset, which makes it fast even against large datasets."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -286,111 +264,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core import Datastore\n",
|
"training_data = dataset.drop_columns(columns=['FBI Code'])\n",
|
||||||
"\n",
|
"label = 'Primary Type'"
|
||||||
"datastore_name = 'demo_training'\n",
|
|
||||||
"container_name = 'digits' \n",
|
|
||||||
"account_name = 'automlpublicdatasets'\n",
|
|
||||||
"Datastore.register_azure_blob_container(\n",
|
|
||||||
" workspace = ws, \n",
|
|
||||||
" datastore_name = datastore_name, \n",
|
|
||||||
" container_name = container_name, \n",
|
|
||||||
" account_name = account_name,\n",
|
|
||||||
" overwrite = True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Below is an example on how to register a private blob container\n",
|
|
||||||
"```python\n",
|
|
||||||
"datastore = Datastore.register_azure_blob_container(\n",
|
|
||||||
" workspace = ws, \n",
|
|
||||||
" datastore_name = 'example_datastore', \n",
|
|
||||||
" container_name = 'example-container', \n",
|
|
||||||
" account_name = 'storageaccount',\n",
|
|
||||||
" account_key = 'accountkey'\n",
|
|
||||||
")\n",
|
|
||||||
"```\n",
|
|
||||||
"The example below shows how to register an Azure Data Lake store. Please make sure you have granted the necessary permissions for the service principal to access the data lake.\n",
|
|
||||||
"```python\n",
|
|
||||||
"datastore = Datastore.register_azure_data_lake(\n",
|
|
||||||
" workspace = ws,\n",
|
|
||||||
" datastore_name = 'example_datastore',\n",
|
|
||||||
" store_name = 'adlsstore',\n",
|
|
||||||
" tenant_id = 'tenant-id-of-service-principal',\n",
|
|
||||||
" client_id = 'client-id-of-service-principal',\n",
|
|
||||||
" client_secret = 'client-secret-of-service-principal'\n",
|
|
||||||
")\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Load Training Data Using DataPrep"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Automated ML takes a Dataflow as input.\n",
|
|
||||||
"\n",
|
|
||||||
"If you are familiar with Pandas and have done your data preparation work in Pandas already, you can use the `read_pandas_dataframe` method in dprep to convert the DataFrame to a Dataflow.\n",
|
|
||||||
"```python\n",
|
|
||||||
"df = pd.read_csv(...)\n",
|
|
||||||
"# apply some transforms\n",
|
|
||||||
"dprep.read_pandas_dataframe(df, temp_folder='/path/accessible/by/both/driver/and/worker')\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"If you just need to ingest data without doing any preparation, you can directly use AzureML Data Prep (Data Prep) to do so. The code below demonstrates this scenario. Data Prep also has data preparation capabilities, we have many [sample notebooks](https://github.com/Microsoft/AMLDataPrepDocs) demonstrating the capabilities.\n",
|
|
||||||
"\n",
|
|
||||||
"You will get the datastore you registered previously and pass it to Data Prep for reading. The data comes from the digits dataset: `sklearn.datasets.load_digits()`. `DataPath` points to a specific location within a datastore. "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.dataprep as dprep\n",
|
|
||||||
"from azureml.data.datapath import DataPath\n",
|
|
||||||
"\n",
|
|
||||||
"datastore = Datastore.get(workspace = ws, datastore_name = datastore_name)\n",
|
|
||||||
"\n",
|
|
||||||
"X_train = dprep.read_csv(datastore.path('X.csv'))\n",
|
|
||||||
"y_train = dprep.read_csv(datastore.path('y.csv')).to_long(dprep.ColumnSelector(term='.*', use_regex = True))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Review the Data Preparation Result\n",
|
|
||||||
"You can peek the result of a Dataflow at any range using skip(i) and head(j). Doing so evaluates only j records for all the steps in the Dataflow, which makes it fast even against large datasets."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X_train.get_profile()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"y_train.get_profile()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -408,14 +283,11 @@
|
|||||||
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
|
||||||
"|**spark_context**|Spark Context object. for Databricks, use spark_context=sc|\n",
|
"|**spark_context**|Spark Context object. for Databricks, use spark_context=sc|\n",
|
||||||
"|**max_concurrent_iterations**|Maximum number of iterations to execute in parallel. This should be <= number of worker nodes in your Azure Databricks cluster.|\n",
|
"|**max_concurrent_iterations**|Maximum number of iterations to execute in parallel. This should be <= number of worker nodes in your Azure Databricks cluster.|\n",
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]<br>Multi-class targets. An indicator matrix turns on multilabel classification. This should be an array of integers.|\n",
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n",
|
"|**label_column_name**|The name of the label column.|"
|
||||||
"|**preprocess**|set this to True to enable pre-processing of data eg. string to numeric using one-hot encoding|\n",
|
|
||||||
"|**exit_score**|Target score for experiment. It is associated with the metric. eg. exit_score=0.995 will exit experiment after that|"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -429,14 +301,12 @@
|
|||||||
" primary_metric = 'AUC_weighted',\n",
|
" primary_metric = 'AUC_weighted',\n",
|
||||||
" iteration_timeout_minutes = 10,\n",
|
" iteration_timeout_minutes = 10,\n",
|
||||||
" iterations = 5,\n",
|
" iterations = 5,\n",
|
||||||
" preprocess = True,\n",
|
|
||||||
" n_cross_validations = 10,\n",
|
" n_cross_validations = 10,\n",
|
||||||
" max_concurrent_iterations = 2, #change it based on number of worker nodes\n",
|
" max_concurrent_iterations = 2, #change it based on number of worker nodes\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" verbosity = logging.INFO,\n",
|
||||||
" spark_context=sc, #databricks/spark related\n",
|
" spark_context=sc, #databricks/spark related\n",
|
||||||
" X = X_train, \n",
|
" training_data=training_data,\n",
|
||||||
" y = y_train,\n",
|
" label_column_name=label)"
|
||||||
" path = project_folder)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -482,13 +352,6 @@
|
|||||||
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"The following will show the child runs and waits for the parent run to complete."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -519,9 +382,11 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Retrieve the Best Model after the above run is complete \n",
|
"## Deploy\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
"### Retrieve the Best Model\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -530,17 +395,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
"best_run, fitted_model = local_run.get_output()"
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Best Model Based on Any Other Metric after the above run is complete based on the child run\n",
|
"### Download the conda environment file\n",
|
||||||
"Show the run and the model that has the smallest `log_loss` value:"
|
"From the *best_run* download the conda environment file that was used to train the AutoML model."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -549,10 +412,34 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"lookup_metric = \"log_loss\"\n",
|
"from azureml.automl.core.shared import constants\n",
|
||||||
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
|
"conda_env_file_name = 'conda_env.yml'\n",
|
||||||
"print(best_run)\n",
|
"best_run.download_file(name=\"outputs/conda_env_v_1_0_0.yml\", output_file_path=conda_env_file_name)\n",
|
||||||
"print(fitted_model)"
|
"with open(conda_env_file_name, \"r\") as conda_file:\n",
|
||||||
|
" conda_file_contents = conda_file.read()\n",
|
||||||
|
" print(conda_file_contents)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Download the model scoring file\n",
|
||||||
|
"From the *best_run* download the scoring file to get the predictions from the AutoML model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.automl.core.shared import constants\n",
|
||||||
|
"script_file_name = 'scoring_file.py'\n",
|
||||||
|
"best_run.download_file(name=\"outputs/scoring_file_v_1_0_0.py\", output_file_path=script_file_name)\n",
|
||||||
|
"with open(script_file_name, \"r\") as scoring_file:\n",
|
||||||
|
" scoring_file_contents = scoring_file.read()\n",
|
||||||
|
" print(scoring_file_contents)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -579,8 +466,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create Scoring Script\n",
|
"### Deploy the model as a Web Service on Azure Container Instance\n",
|
||||||
"Replace model_id with name of model from output of above register cell"
|
"\n",
|
||||||
|
"Create the configuration needed for deploying the model as a web service service."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -589,142 +477,33 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%writefile score.py\n",
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
"import pickle\n",
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
"import json\n",
|
"from azureml.core.environment import Environment\n",
|
||||||
"import numpy as np\n",
|
"\n",
|
||||||
"import azureml.train.automl\n",
|
"myenv = Environment.from_conda_specification(name=\"myenv\", file_path=conda_env_file_name)\n",
|
||||||
"from sklearn.externals import joblib\n",
|
"inference_config = InferenceConfig(entry_script=script_file_name, environment=myenv)\n",
|
||||||
|
"\n",
|
||||||
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
||||||
|
" memory_gb = 1, \n",
|
||||||
|
" tags = {'area': \"digits\", 'type': \"automl_classification\"}, \n",
|
||||||
|
" description = 'sample service for Automl Classification')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import Webservice\n",
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"def init():\n",
|
"aci_service_name = 'automl-databricks-local'\n",
|
||||||
" global model\n",
|
"print(aci_service_name)\n",
|
||||||
" model_path = Model.get_model_path(model_name = '<<model_id>>') # this name is model.id of model that we want to deploy\n",
|
"aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig)\n",
|
||||||
" # deserialize the model file back into a sklearn model\n",
|
"aci_service.wait_for_deployment(True)\n",
|
||||||
" model = joblib.load(model_path)\n",
|
"print(aci_service.state)"
|
||||||
"\n",
|
|
||||||
"def run(raw_data):\n",
|
|
||||||
" try:\n",
|
|
||||||
" data = (pd.DataFrame(np.array(json.loads(raw_data)['data']), columns=[str(i) for i in range(0,64)]))\n",
|
|
||||||
" result = model.predict(data)\n",
|
|
||||||
" except Exception as e:\n",
|
|
||||||
" result = str(e)\n",
|
|
||||||
" return json.dumps({\"error\": result})\n",
|
|
||||||
" return json.dumps({\"result\":result.tolist()})"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Replace <<model_id>>\n",
|
|
||||||
"content = \"\"\n",
|
|
||||||
"with open(\"score.py\", \"r\") as fo:\n",
|
|
||||||
" content = fo.read()\n",
|
|
||||||
"\n",
|
|
||||||
"new_content = content.replace(\"<<model_id>>\", local_run.model_id)\n",
|
|
||||||
"with open(\"score.py\", \"w\") as fw:\n",
|
|
||||||
" fw.write(new_content)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Create a YAML File for the Environment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"\n",
|
|
||||||
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn'], pip_packages=['azureml-sdk[automl]'])\n",
|
|
||||||
"\n",
|
|
||||||
"conda_env_file_name = 'mydeployenv.yml'\n",
|
|
||||||
"myenv.save_to_file('.', conda_env_file_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Create ACI config"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#deploy to ACI\n",
|
|
||||||
"from azureml.core.webservice import AciWebservice, Webservice\n",
|
|
||||||
"\n",
|
|
||||||
"myaci_config = AciWebservice.deploy_configuration(\n",
|
|
||||||
" cpu_cores = 2, \n",
|
|
||||||
" memory_gb = 2, \n",
|
|
||||||
" tags = {'name':'Databricks Azure ML ACI'}, \n",
|
|
||||||
" description = 'This is for ADB and AutoML example.')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Deploy the Image as a Web Service on Azure Container Instance\n",
|
|
||||||
"Replace servicename with any meaningful name of service"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# this will take 10-15 minutes to finish\n",
|
|
||||||
"\n",
|
|
||||||
"import uuid\n",
|
|
||||||
"from azureml.core.image import ContainerImage\n",
|
|
||||||
"\n",
|
|
||||||
"guid = str(uuid.uuid4()).split(\"-\")[0]\n",
|
|
||||||
"service_name = \"myservice-{}\".format(guid)\n",
|
|
||||||
"print(\"Creating service with name: {}\".format(service_name))\n",
|
|
||||||
"runtime = \"spark-py\" \n",
|
|
||||||
"driver_file = \"score.py\"\n",
|
|
||||||
"my_conda_file = \"mydeployenv.yml\"\n",
|
|
||||||
"\n",
|
|
||||||
"# image creation\n",
|
|
||||||
"myimage_config = ContainerImage.image_configuration(execution_script = driver_file, \n",
|
|
||||||
" runtime = runtime, \n",
|
|
||||||
" conda_file = 'mydeployenv.yml')\n",
|
|
||||||
"\n",
|
|
||||||
"# Webservice creation\n",
|
|
||||||
"myservice = Webservice.deploy_from_model(\n",
|
|
||||||
" workspace=ws, \n",
|
|
||||||
" name=service_name,\n",
|
|
||||||
" deployment_config = myaci_config,\n",
|
|
||||||
" models = [model],\n",
|
|
||||||
" image_config = myimage_config\n",
|
|
||||||
" )\n",
|
|
||||||
"\n",
|
|
||||||
"myservice.wait_for_deployment(show_output=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#for using the Web HTTP API \n",
|
|
||||||
"print(myservice.scoring_uri)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -742,11 +521,13 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"blob_location = \"https://{}.blob.core.windows.net/{}\".format(account_name, container_name)\n",
|
"dataset_test = Dataset.Tabular.from_delimited_files(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv')\n",
|
||||||
"X_test = pd.read_csv(\"{}./X_valid.csv\".format(blob_location), header=0)\n",
|
"\n",
|
||||||
"y_test = pd.read_csv(\"{}/y_valid.csv\".format(blob_location), header=0)\n",
|
"df_test = dataset_test.to_pandas_dataframe()\n",
|
||||||
"images = pd.read_csv(\"{}/images.csv\".format(blob_location), header=None)\n",
|
"df_test = df_test[pd.notnull(df_test['Primary Type'])]\n",
|
||||||
"images = np.reshape(images.values, (100,8,8))"
|
"\n",
|
||||||
|
"y_test = df_test[['Primary Type']]\n",
|
||||||
|
"X_test = df_test.drop(['Primary Type', 'FBI Code'], axis=1)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -763,20 +544,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import json\n",
|
"fitted_model.predict(X_test)"
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" test_sample = json.dumps({'data':X_test[index:index + 1].values.tolist()})\n",
|
|
||||||
" predicted = myservice.run(input_data = test_sample)\n",
|
|
||||||
" label = y_test.values[index]\n",
|
|
||||||
" predictedDict = json.loads(predicted)\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %s \" % ( label,predictedDict['result'][0]) \n",
|
|
||||||
" fig = plt.figure(3, figsize = (5,5))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" display(fig)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -794,7 +562,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"myservice.delete()"
|
"aci_service.delete()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -829,10 +597,10 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.5"
|
"version": "3.6.8"
|
||||||
},
|
},
|
||||||
"name": "auto-ml-classification-local-adb",
|
"name": "auto-ml-classification-local-adb",
|
||||||
"notebookId": 2733885892129020
|
"notebookId": 3772036807853791
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 1
|
"nbformat_minor": 1
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
# Using Databricks as a Compute Target from Azure Machine Learning Pipeline
|
|
||||||
To use Databricks as a compute target from Azure Machine Learning Pipeline, a DatabricksStep is used. This notebook demonstrates the use of DatabricksStep in Azure Machine Learning Pipeline.
|
|
||||||
|
|
||||||
The notebook will show:
|
|
||||||
|
|
||||||
1. Running an arbitrary Databricks notebook that the customer has in Databricks workspace
|
|
||||||
2. Running an arbitrary Python script that the customer has in DBFS
|
|
||||||
3. Running an arbitrary Python script that is available on local computer (will upload to DBFS, and then run in Databricks)
|
|
||||||
4. Running a JAR job that the customer has in DBFS.
|
|
||||||
|
|
||||||
## Before you begin:
|
|
||||||
1. **Create an Azure Databricks workspace** in the same subscription where you have your Azure Machine Learning workspace.
|
|
||||||
You will need details of this workspace later on to define DatabricksStep. [More information](https://ms.portal.azure.com/#blade/HubsExtension/Resources/resourceType/Microsoft.Databricks%2Fworkspaces).
|
|
||||||
2. **Create PAT (access token)** at the Azure Databricks portal. [More information](https://docs.databricks.com/api/latest/authentication.html#generate-a-token).
|
|
||||||
3. **Add demo notebook to ADB** This notebook has a sample you can use as is. Launch Azure Databricks attached to your Azure Machine Learning workspace and add a new notebook.
|
|
||||||
4. **Create/attach a Blob storage** for use from ADB
|
|
||||||
@@ -1,715 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Using Databricks as a Compute Target from Azure Machine Learning Pipeline\n",
|
|
||||||
"To use Databricks as a compute target from [Azure Machine Learning Pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines), a [DatabricksStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.databricks_step.databricksstep?view=azure-ml-py) is used. This notebook demonstrates the use of DatabricksStep in Azure Machine Learning Pipeline.\n",
|
|
||||||
"\n",
|
|
||||||
"The notebook will show:\n",
|
|
||||||
"1. Running an arbitrary Databricks notebook that the customer has in Databricks workspace\n",
|
|
||||||
"2. Running an arbitrary Python script that the customer has in DBFS\n",
|
|
||||||
"3. Running an arbitrary Python script that is available on local computer (will upload to DBFS, and then run in Databricks) \n",
|
|
||||||
"4. Running a JAR job that the customer has in DBFS.\n",
|
|
||||||
"\n",
|
|
||||||
"## Before you begin:\n",
|
|
||||||
"\n",
|
|
||||||
"1. **Create an Azure Databricks workspace** in the same subscription where you have your Azure Machine Learning workspace. You will need details of this workspace later on to define DatabricksStep. [Click here](https://ms.portal.azure.com/#blade/HubsExtension/Resources/resourceType/Microsoft.Databricks%2Fworkspaces) for more information.\n",
|
|
||||||
"2. **Create PAT (access token)**: Manually create a Databricks access token at the Azure Databricks portal. See [this](https://docs.databricks.com/api/latest/authentication.html#generate-a-token) for more information.\n",
|
|
||||||
"3. **Add demo notebook to ADB**: This notebook has a sample you can use as is. Launch Azure Databricks attached to your Azure Machine Learning workspace and add a new notebook. \n",
|
|
||||||
"4. **Create/attach a Blob storage** for use from ADB"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Add demo notebook to ADB Workspace\n",
|
|
||||||
"Copy and paste the below code to create a new notebook in your ADB workspace."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"# direct access\n",
|
|
||||||
"dbutils.widgets.get(\"myparam\")\n",
|
|
||||||
"p = getArgument(\"myparam\")\n",
|
|
||||||
"print (\"Param -\\'myparam':\")\n",
|
|
||||||
"print (p)\n",
|
|
||||||
"\n",
|
|
||||||
"dbutils.widgets.get(\"input\")\n",
|
|
||||||
"i = getArgument(\"input\")\n",
|
|
||||||
"print (\"Param -\\'input':\")\n",
|
|
||||||
"print (i)\n",
|
|
||||||
"\n",
|
|
||||||
"dbutils.widgets.get(\"output\")\n",
|
|
||||||
"o = getArgument(\"output\")\n",
|
|
||||||
"print (\"Param -\\'output':\")\n",
|
|
||||||
"print (o)\n",
|
|
||||||
"\n",
|
|
||||||
"n = i + \"/testdata.txt\"\n",
|
|
||||||
"df = spark.read.csv(n)\n",
|
|
||||||
"\n",
|
|
||||||
"display (df)\n",
|
|
||||||
"\n",
|
|
||||||
"data = [('value1', 'value2')]\n",
|
|
||||||
"df2 = spark.createDataFrame(data)\n",
|
|
||||||
"\n",
|
|
||||||
"z = o + \"/output.txt\"\n",
|
|
||||||
"df2.write.csv(z)\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Azure Machine Learning and Pipeline SDK-specific imports"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.runconfig import JarLibrary\n",
|
|
||||||
"from azureml.core.compute import ComputeTarget, DatabricksCompute\n",
|
|
||||||
"from azureml.exceptions import ComputeTargetException\n",
|
|
||||||
"from azureml.core import Workspace, Experiment\n",
|
|
||||||
"from azureml.pipeline.core import Pipeline, PipelineData\n",
|
|
||||||
"from azureml.pipeline.steps import DatabricksStep\n",
|
|
||||||
"from azureml.core.datastore import Datastore\n",
|
|
||||||
"from azureml.data.data_reference import DataReference\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Initialize Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"Initialize a workspace object from persisted configuration. Make sure the config file is present at .\\config.json"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Attach Databricks compute target\n",
|
|
||||||
"Next, you need to add your Databricks workspace to Azure Machine Learning as a compute target and give it a name. You will use this name to refer to your Databricks workspace compute target inside Azure Machine Learning.\n",
|
|
||||||
"\n",
|
|
||||||
"- **Resource Group** - The resource group name of your Azure Machine Learning workspace\n",
|
|
||||||
"- **Databricks Workspace Name** - The workspace name of your Azure Databricks workspace\n",
|
|
||||||
"- **Databricks Access Token** - The access token you created in ADB\n",
|
|
||||||
"\n",
|
|
||||||
"**The Databricks workspace need to be present in the same subscription as your AML workspace**"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Replace with your account info before running.\n",
|
|
||||||
" \n",
|
|
||||||
"db_compute_name=os.getenv(\"DATABRICKS_COMPUTE_NAME\", \"<my-databricks-compute-name>\") # Databricks compute name\n",
|
|
||||||
"db_resource_group=os.getenv(\"DATABRICKS_RESOURCE_GROUP\", \"<my-db-resource-group>\") # Databricks resource group\n",
|
|
||||||
"db_workspace_name=os.getenv(\"DATABRICKS_WORKSPACE_NAME\", \"<my-db-workspace-name>\") # Databricks workspace name\n",
|
|
||||||
"db_access_token=os.getenv(\"DATABRICKS_ACCESS_TOKEN\", \"<my-access-token>\") # Databricks access token\n",
|
|
||||||
" \n",
|
|
||||||
"try:\n",
|
|
||||||
" databricks_compute = DatabricksCompute(workspace=ws, name=db_compute_name)\n",
|
|
||||||
" print('Compute target {} already exists'.format(db_compute_name))\n",
|
|
||||||
"except ComputeTargetException:\n",
|
|
||||||
" print('Compute not found, will use below parameters to attach new one')\n",
|
|
||||||
" print('db_compute_name {}'.format(db_compute_name))\n",
|
|
||||||
" print('db_resource_group {}'.format(db_resource_group))\n",
|
|
||||||
" print('db_workspace_name {}'.format(db_workspace_name))\n",
|
|
||||||
" print('db_access_token {}'.format(db_access_token))\n",
|
|
||||||
" \n",
|
|
||||||
" config = DatabricksCompute.attach_configuration(\n",
|
|
||||||
" resource_group = db_resource_group,\n",
|
|
||||||
" workspace_name = db_workspace_name,\n",
|
|
||||||
" access_token= db_access_token)\n",
|
|
||||||
" databricks_compute=ComputeTarget.attach(ws, db_compute_name, config)\n",
|
|
||||||
" databricks_compute.wait_for_completion(True)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data Connections with Inputs and Outputs\n",
|
|
||||||
"The DatabricksStep supports Azure Bloband ADLS for inputs and outputs. You also will need to define a [Secrets](https://docs.azuredatabricks.net/user-guide/secrets/index.html) scope to enable authentication to external data sources such as Blob and ADLS from Databricks.\n",
|
|
||||||
"\n",
|
|
||||||
"- Databricks documentation on [Azure Blob](https://docs.azuredatabricks.net/spark/latest/data-sources/azure/azure-storage.html)\n",
|
|
||||||
"- Databricks documentation on [ADLS](https://docs.databricks.com/spark/latest/data-sources/azure/azure-datalake.html)\n",
|
|
||||||
"\n",
|
|
||||||
"### Type of Data Access\n",
|
|
||||||
"Databricks allows to interact with Azure Blob and ADLS in two ways.\n",
|
|
||||||
"- **Direct Access**: Databricks allows you to interact with Azure Blob or ADLS URIs directly. The input or output URIs will be mapped to a Databricks widget param in the Databricks notebook.\n",
|
|
||||||
"- **Mounting**: You will be supplied with additional parameters and secrets that will enable you to mount your ADLS or Azure Blob input or output location in your Databricks notebook."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Direct Access: Python sample code\n",
|
|
||||||
"If you have a data reference named \"input\" it will represent the URI of the input and you can access it directly in the Databricks python notebook like so:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"dbutils.widgets.get(\"input\")\n",
|
|
||||||
"y = getArgument(\"input\")\n",
|
|
||||||
"df = spark.read.csv(y)\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Mounting: Python sample code for Azure Blob\n",
|
|
||||||
"Given an Azure Blob data reference named \"input\" the following widget params will be made available in the Databricks notebook:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"# This contains the input URI\n",
|
|
||||||
"dbutils.widgets.get(\"input\")\n",
|
|
||||||
"myinput_uri = getArgument(\"input\")\n",
|
|
||||||
"\n",
|
|
||||||
"# How to get the input datastore name inside ADB notebook\n",
|
|
||||||
"# This contains the name of a Databricks secret (in the predefined \"amlscope\" secret scope) \n",
|
|
||||||
"# that contians an access key or sas for the Azure Blob input (this name is obtained by appending \n",
|
|
||||||
"# the name of the input with \"_blob_secretname\". \n",
|
|
||||||
"dbutils.widgets.get(\"input_blob_secretname\") \n",
|
|
||||||
"myinput_blob_secretname = getArgument(\"input_blob_secretname\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the required configuration for mounting\n",
|
|
||||||
"dbutils.widgets.get(\"input_blob_config\")\n",
|
|
||||||
"myinput_blob_config = getArgument(\"input_blob_config\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Usage\n",
|
|
||||||
"dbutils.fs.mount(\n",
|
|
||||||
" source = myinput_uri,\n",
|
|
||||||
" mount_point = \"/mnt/input\",\n",
|
|
||||||
" extra_configs = {myinput_blob_config:dbutils.secrets.get(scope = \"amlscope\", key = myinput_blob_secretname)})\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Mounting: Python sample code for ADLS\n",
|
|
||||||
"Given an ADLS data reference named \"input\" the following widget params will be made available in the Databricks notebook:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"# This contains the input URI\n",
|
|
||||||
"dbutils.widgets.get(\"input\") \n",
|
|
||||||
"myinput_uri = getArgument(\"input\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the client id for the service principal \n",
|
|
||||||
"# that has access to the adls input\n",
|
|
||||||
"dbutils.widgets.get(\"input_adls_clientid\") \n",
|
|
||||||
"myinput_adls_clientid = getArgument(\"input_adls_clientid\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the name of a Databricks secret (in the predefined \"amlscope\" secret scope) \n",
|
|
||||||
"# that contains the secret for the above mentioned service principal\n",
|
|
||||||
"dbutils.widgets.get(\"input_adls_secretname\") \n",
|
|
||||||
"myinput_adls_secretname = getArgument(\"input_adls_secretname\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the refresh url for the mounting configs\n",
|
|
||||||
"dbutils.widgets.get(\"input_adls_refresh_url\") \n",
|
|
||||||
"myinput_adls_refresh_url = getArgument(\"input_adls_refresh_url\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Usage \n",
|
|
||||||
"configs = {\"dfs.adls.oauth2.access.token.provider.type\": \"ClientCredential\",\n",
|
|
||||||
" \"dfs.adls.oauth2.client.id\": myinput_adls_clientid,\n",
|
|
||||||
" \"dfs.adls.oauth2.credential\": dbutils.secrets.get(scope = \"amlscope\", key =myinput_adls_secretname),\n",
|
|
||||||
" \"dfs.adls.oauth2.refresh.url\": myinput_adls_refresh_url}\n",
|
|
||||||
"\n",
|
|
||||||
"dbutils.fs.mount(\n",
|
|
||||||
" source = myinput_uri,\n",
|
|
||||||
" mount_point = \"/mnt/output\",\n",
|
|
||||||
" extra_configs = configs)\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Use Databricks from Azure Machine Learning Pipeline\n",
|
|
||||||
"To use Databricks as a compute target from Azure Machine Learning Pipeline, a DatabricksStep is used. Let's define a datasource (via DataReference) and intermediate data (via PipelineData) to be used in DatabricksStep."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Use the default blob storage\n",
|
|
||||||
"def_blob_store = Datastore(ws, \"workspaceblobstore\")\n",
|
|
||||||
"print('Datastore {} will be used'.format(def_blob_store.name))\n",
|
|
||||||
"\n",
|
|
||||||
"# We are uploading a sample file in the local directory to be used as a datasource\n",
|
|
||||||
"def_blob_store.upload_files(files=[\"./testdata.txt\"], target_path=\"dbtest\", overwrite=False)\n",
|
|
||||||
"\n",
|
|
||||||
"step_1_input = DataReference(datastore=def_blob_store, path_on_datastore=\"dbtest\",\n",
|
|
||||||
" data_reference_name=\"input\")\n",
|
|
||||||
"\n",
|
|
||||||
"step_1_output = PipelineData(\"output\", datastore=def_blob_store)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Add a DatabricksStep\n",
|
|
||||||
"Adds a Databricks notebook as a step in a Pipeline.\n",
|
|
||||||
"- ***name:** Name of the Module\n",
|
|
||||||
"- **inputs:** List of input connections for data consumed by this step. Fetch this inside the notebook using dbutils.widgets.get(\"input\")\n",
|
|
||||||
"- **outputs:** List of output port definitions for outputs produced by this step. Fetch this inside the notebook using dbutils.widgets.get(\"output\")\n",
|
|
||||||
"- **existing_cluster_id:** Cluster ID of an existing Interactive cluster on the Databricks workspace. If you are providing this, do not provide any of the parameters below that are used to create a new cluster such as spark_version, node_type, etc.\n",
|
|
||||||
"- **spark_version:** Version of spark for the databricks run cluster. default value: 4.0.x-scala2.11\n",
|
|
||||||
"- **node_type:** Azure vm node types for the databricks run cluster. default value: Standard_D3_v2\n",
|
|
||||||
"- **num_workers:** Specifies a static number of workers for the databricks run cluster\n",
|
|
||||||
"- **min_workers:** Specifies a min number of workers to use for auto-scaling the databricks run cluster\n",
|
|
||||||
"- **max_workers:** Specifies a max number of workers to use for auto-scaling the databricks run cluster\n",
|
|
||||||
"- **spark_env_variables:** Spark environment variables for the databricks run cluster (dictionary of {str:str}). default value: {'PYSPARK_PYTHON': '/databricks/python3/bin/python3'}\n",
|
|
||||||
"- **notebook_path:** Path to the notebook in the databricks instance. If you are providing this, do not provide python script related paramaters or JAR related parameters.\n",
|
|
||||||
"- **notebook_params:** Parameters for the databricks notebook (dictionary of {str:str}). Fetch this inside the notebook using dbutils.widgets.get(\"myparam\")\n",
|
|
||||||
"- **python_script_path:** The path to the python script in the DBFS or S3. If you are providing this, do not provide python_script_name which is used for uploading script from local machine.\n",
|
|
||||||
"- **python_script_params:** Parameters for the python script (list of str)\n",
|
|
||||||
"- **main_class_name:** The name of the entry point in a JAR module. If you are providing this, do not provide any python script or notebook related parameters.\n",
|
|
||||||
"- **jar_params:** Parameters for the JAR module (list of str)\n",
|
|
||||||
"- **python_script_name:** name of a python script on your local machine (relative to source_directory). If you are providing this do not provide python_script_path which is used to execute a remote python script; or any of the JAR or notebook related parameters.\n",
|
|
||||||
"- **source_directory:** folder that contains the script and other files\n",
|
|
||||||
"- **hash_paths:** list of paths to hash to detect a change in source_directory (script file is always hashed)\n",
|
|
||||||
"- **run_name:** Name in databricks for this run\n",
|
|
||||||
"- **timeout_seconds:** Timeout for the databricks run\n",
|
|
||||||
"- **runconfig:** Runconfig to use. Either pass runconfig or each library type as a separate parameter but do not mix the two\n",
|
|
||||||
"- **maven_libraries:** maven libraries for the databricks run\n",
|
|
||||||
"- **pypi_libraries:** pypi libraries for the databricks run\n",
|
|
||||||
"- **egg_libraries:** egg libraries for the databricks run\n",
|
|
||||||
"- **jar_libraries:** jar libraries for the databricks run\n",
|
|
||||||
"- **rcran_libraries:** rcran libraries for the databricks run\n",
|
|
||||||
"- **compute_target:** Azure Databricks compute\n",
|
|
||||||
"- **allow_reuse:** Whether the step should reuse previous results when run with the same settings/inputs\n",
|
|
||||||
"- **version:** Optional version tag to denote a change in functionality for the step\n",
|
|
||||||
"\n",
|
|
||||||
"\\* *denotes required fields* \n",
|
|
||||||
"*You must provide exactly one of num_workers or min_workers and max_workers paramaters* \n",
|
|
||||||
"*You must provide exactly one of databricks_compute or databricks_compute_name parameters*\n",
|
|
||||||
"\n",
|
|
||||||
"## Use runconfig to specify library dependencies\n",
|
|
||||||
"You can use a runconfig to specify the library dependencies for your cluster in Databricks. The runconfig will contain a databricks section as follows:\n",
|
|
||||||
"\n",
|
|
||||||
"```yaml\n",
|
|
||||||
"environment:\n",
|
|
||||||
"# Databricks details\n",
|
|
||||||
" databricks:\n",
|
|
||||||
"# List of maven libraries.\n",
|
|
||||||
" mavenLibraries:\n",
|
|
||||||
" - coordinates: org.jsoup:jsoup:1.7.1\n",
|
|
||||||
" repo: ''\n",
|
|
||||||
" exclusions:\n",
|
|
||||||
" - slf4j:slf4j\n",
|
|
||||||
" - '*:hadoop-client'\n",
|
|
||||||
"# List of PyPi libraries\n",
|
|
||||||
" pypiLibraries:\n",
|
|
||||||
" - package: beautifulsoup4\n",
|
|
||||||
" repo: ''\n",
|
|
||||||
"# List of RCran libraries\n",
|
|
||||||
" rcranLibraries:\n",
|
|
||||||
" -\n",
|
|
||||||
"# Coordinates.\n",
|
|
||||||
" package: ada\n",
|
|
||||||
"# Repo\n",
|
|
||||||
" repo: http://cran.us.r-project.org\n",
|
|
||||||
"# List of JAR libraries\n",
|
|
||||||
" jarLibraries:\n",
|
|
||||||
" -\n",
|
|
||||||
"# Coordinates.\n",
|
|
||||||
" library: dbfs:/mnt/libraries/library.jar\n",
|
|
||||||
"# List of Egg libraries\n",
|
|
||||||
" eggLibraries:\n",
|
|
||||||
" -\n",
|
|
||||||
"# Coordinates.\n",
|
|
||||||
" library: dbfs:/mnt/libraries/library.egg\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"You can then create a RunConfiguration object using this file and pass it as the runconfig parameter to DatabricksStep.\n",
|
|
||||||
"```python\n",
|
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
|
||||||
"\n",
|
|
||||||
"runconfig = RunConfiguration()\n",
|
|
||||||
"runconfig.load(path='<directory_where_runconfig_is_stored>', name='<runconfig_file_name>')\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 1. Running the demo notebook already added to the Databricks workspace\n",
|
|
||||||
"Create a notebook in the Azure Databricks workspace, and provide the path to that notebook as the value associated with the environment variable \"DATABRICKS_NOTEBOOK_PATH\". This will then set the variable\u00c2\u00a0notebook_path\u00c2\u00a0when you run the code cell below:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"notebook_path=os.getenv(\"DATABRICKS_NOTEBOOK_PATH\", \"<my-databricks-notebook-path>\") # Databricks notebook path\n",
|
|
||||||
"\n",
|
|
||||||
"dbNbStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBNotebookInWS\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" outputs=[step_1_output],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" notebook_path=notebook_path,\n",
|
|
||||||
" notebook_params={'myparam': 'testparam'},\n",
|
|
||||||
" run_name='DB_Notebook_demo',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbNbStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_Notebook_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 2. Running a Python script from DBFS\n",
|
|
||||||
"This shows how to run a Python script in DBFS. \n",
|
|
||||||
"\n",
|
|
||||||
"To complete this, you will need to first upload the Python script in your local machine to DBFS using the [CLI](https://docs.azuredatabricks.net/user-guide/dbfs-databricks-file-system.html). The CLI command is given below:\n",
|
|
||||||
"\n",
|
|
||||||
"```\n",
|
|
||||||
"dbfs cp ./train-db-dbfs.py dbfs:/train-db-dbfs.py\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"The code in the below cell assumes that you have completed the previous step of uploading the script `train-db-dbfs.py` to the root folder in DBFS."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"python_script_path = os.getenv(\"DATABRICKS_PYTHON_SCRIPT_PATH\", \"<my-databricks-python-script-path>\") # Databricks python script path\n",
|
|
||||||
"\n",
|
|
||||||
"dbPythonInDbfsStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBPythonInDBFS\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" python_script_path=python_script_path,\n",
|
|
||||||
" python_script_params={'--input_data'},\n",
|
|
||||||
" run_name='DB_Python_demo',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbPythonInDbfsStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_Python_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 3. Running a Python script in Databricks that currenlty is in local computer\n",
|
|
||||||
"To run a Python script that is currently in your local computer, follow the instructions below. \n",
|
|
||||||
"\n",
|
|
||||||
"The commented out code below code assumes that you have `train-db-local.py` in the `scripts` subdirectory under the current working directory.\n",
|
|
||||||
"\n",
|
|
||||||
"In this case, the Python script will be uploaded first to DBFS, and then the script will be run in Databricks."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"python_script_name = \"train-db-local.py\"\n",
|
|
||||||
"source_directory = \".\"\n",
|
|
||||||
"\n",
|
|
||||||
"dbPythonInLocalMachineStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBPythonInLocalMachine\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" python_script_name=python_script_name,\n",
|
|
||||||
" source_directory=source_directory,\n",
|
|
||||||
" run_name='DB_Python_Local_demo',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbPythonInLocalMachineStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_Python_Local_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 4. Running a JAR job that is alreay added in DBFS\n",
|
|
||||||
"To run a JAR job that is already uploaded to DBFS, follow the instructions below. You will first upload the JAR file to DBFS using the [CLI](https://docs.azuredatabricks.net/user-guide/dbfs-databricks-file-system.html).\n",
|
|
||||||
"\n",
|
|
||||||
"The commented out code in the below cell assumes that you have uploaded `train-db-dbfs.jar` to the root folder in DBFS. You can upload `train-db-dbfs.jar` to the root folder in DBFS using this commandline so you can use `jar_library_dbfs_path = \"dbfs:/train-db-dbfs.jar\"`:\n",
|
|
||||||
"\n",
|
|
||||||
"```\n",
|
|
||||||
"dbfs cp ./train-db-dbfs.jar dbfs:/train-db-dbfs.jar\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"main_jar_class_name = \"com.microsoft.aeva.Main\"\n",
|
|
||||||
"jar_library_dbfs_path = os.getenv(\"DATABRICKS_JAR_LIB_PATH\", \"<my-databricks-jar-lib-path>\") # Databricks jar library path\n",
|
|
||||||
"\n",
|
|
||||||
"dbJarInDbfsStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBJarInDBFS\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" main_class_name=main_jar_class_name,\n",
|
|
||||||
" jar_params={'arg1', 'arg2'},\n",
|
|
||||||
" run_name='DB_JAR_demo',\n",
|
|
||||||
" jar_libraries=[JarLibrary(jar_library_dbfs_path)],\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbJarInDbfsStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_JAR_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Next: ADLA as a Compute Target\n",
|
|
||||||
"To use ADLA as a compute target from Azure Machine Learning Pipeline, a AdlaStep is used. This [notebook](./aml-pipelines-use-adla-as-compute-target.ipynb) demonstrates the use of AdlaStep in Azure Machine Learning Pipeline."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "diray"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"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.6.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
Test1
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
# Copyright (c) Microsoft. All rights reserved.
|
|
||||||
# Licensed under the MIT license.
|
|
||||||
|
|
||||||
print("In train.py")
|
|
||||||
print("As a data scientist, this is where I use my training code.")
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
**Azure HDInsight**
|
|
||||||
|
|
||||||
Azure HDInsight is a fully managed cloud Hadoop & Spark offering the gives
|
|
||||||
optimized open-source analytic clusters for Spark, Hive, MapReduce, HBase,
|
|
||||||
Storm, and Kafka. HDInsight Spark clusters provide kernels that you can use with
|
|
||||||
the Jupyter notebook on [Apache Spark](https://spark.apache.org/) for testing
|
|
||||||
your applications.
|
|
||||||
|
|
||||||
How Azure HDInsight works with Azure Machine Learning service
|
|
||||||
|
|
||||||
- You can train a model using Spark clusters and deploy the model to ACI/AKS
|
|
||||||
from within Azure HDInsight.
|
|
||||||
|
|
||||||
- You can also use [automated machine
|
|
||||||
learning](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-automated-ml) capabilities
|
|
||||||
integrated within Azure HDInsight.
|
|
||||||
|
|
||||||
You can use Azure HDInsight as a compute target from an [Azure Machine Learning
|
|
||||||
pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines).
|
|
||||||
|
|
||||||
**Set up your HDInsight cluster**
|
|
||||||
|
|
||||||
Create [HDInsight
|
|
||||||
cluster](https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-hadoop-provision-linux-clusters)
|
|
||||||
|
|
||||||
**Quick create: Basic cluster setup**
|
|
||||||
|
|
||||||
This article walks you through setup in the [Azure
|
|
||||||
portal](https://portal.azure.com/), where you can create an HDInsight cluster
|
|
||||||
using *Quick create* or *Custom*.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Follow instructions on the screen to do a basic cluster setup. Details are
|
|
||||||
provided below for:
|
|
||||||
|
|
||||||
- [Resource group
|
|
||||||
name](https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-hadoop-provision-linux-clusters#resource-group-name)
|
|
||||||
|
|
||||||
- [Cluster types and
|
|
||||||
configuration](https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-hadoop-provision-linux-clusters#cluster-types)
|
|
||||||
(Cluster must be Spark 2.3 (HDI 3.6) or greater)
|
|
||||||
|
|
||||||
- Cluster login and SSH username
|
|
||||||
|
|
||||||
- [Location](https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-hadoop-provision-linux-clusters#location)
|
|
||||||
|
|
||||||
**Import the sample HDI notebook in Jupyter**
|
|
||||||
|
|
||||||
**Important links:**
|
|
||||||
|
|
||||||
Create HDI cluster:
|
|
||||||
<https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-hadoop-provision-linux-clusters>
|
|
||||||
|
|
||||||

|
|
||||||
@@ -1,631 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated ML on Azure HDInsight\n",
|
|
||||||
"\n",
|
|
||||||
"In this example we use the scikit-learn's <a href=\"http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset\" target=\"_blank\">digit dataset</a> to showcase how you can use AutoML for a simple classification problem.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create Azure Machine Learning Workspace object and initialize your notebook directory to easily reload this object from a configuration file.\n",
|
|
||||||
"2. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"3. Configure Automated ML using `AutoMLConfig`.\n",
|
|
||||||
"4. Train the model using Azure HDInsight.\n",
|
|
||||||
"5. Explore the results.\n",
|
|
||||||
"6. Test the best fitted model.\n",
|
|
||||||
"\n",
|
|
||||||
"Before running this notebook, please follow the readme for using Automated ML on Azure HDI for installing necessary libraries to your cluster."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Check the Azure ML Core SDK Version to Validate Your Installation"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from azureml.core.authentication import ServicePrincipalAuthentication\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun\n",
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"SDK Version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Initialize an Azure ML Workspace\n",
|
|
||||||
"### What is an Azure ML Workspace and Why Do I Need One?\n",
|
|
||||||
"\n",
|
|
||||||
"An Azure ML workspace is an Azure resource that organizes and coordinates the actions of many other Azure resources to assist in executing and sharing machine learning workflows. In particular, an Azure ML workspace coordinates storage, databases, and compute resources providing added functionality for machine learning experimentation, operationalization, and the monitoring of operationalized models.\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"### What do I Need?\n",
|
|
||||||
"\n",
|
|
||||||
"To create or access an Azure ML workspace, you will need to import the Azure ML library and specify following information:\n",
|
|
||||||
"* A name for your workspace. You can choose one.\n",
|
|
||||||
"* Your subscription id. Use the `id` value from the `az account show` command output above.\n",
|
|
||||||
"* The resource group name. The resource group organizes Azure resources and provides a default region for the resources in the group. The resource group will be created if it doesn't exist. Resource groups can be created and viewed in the [Azure portal](https://portal.azure.com)\n",
|
|
||||||
"* Supported regions include `eastus2`, `eastus`,`westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus`."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from azureml.core.authentication import ServicePrincipalAuthentication\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun\n",
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"subscription_id = \"<Your SubscriptionId>\" #you should be owner or contributor\n",
|
|
||||||
"resource_group = \"<Resource group - new or existing>\" #you should be owner or contributor\n",
|
|
||||||
"workspace_name = \"<workspace to be created>\" #your workspace name\n",
|
|
||||||
"workspace_region = \"<azureregion>\" #your region\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"tenant_id = \"<tenant_id>\"\n",
|
|
||||||
"app_id = \"<app_id>\"\n",
|
|
||||||
"app_key = \"<app_key>\"\n",
|
|
||||||
"\n",
|
|
||||||
"auth_sp = ServicePrincipalAuthentication(tenant_id = tenant_id,\n",
|
|
||||||
" service_principal_id = app_id,\n",
|
|
||||||
" service_principal_password = app_key)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Creating a Workspace\n",
|
|
||||||
"If you already have access to an Azure ML workspace you want to use, you can skip this cell. Otherwise, this cell will create an Azure ML workspace for you in the specified subscription, provided you have the correct permissions for the given `subscription_id`.\n",
|
|
||||||
"\n",
|
|
||||||
"This will fail when:\n",
|
|
||||||
"1. The workspace already exists.\n",
|
|
||||||
"2. You do not have permission to create a workspace in the resource group.\n",
|
|
||||||
"3. You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription.\n",
|
|
||||||
"\n",
|
|
||||||
"If workspace creation fails for any reason other than already existing, please work with your IT administrator to provide you with the appropriate permissions or to provision the required resources.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** Creation of a new workspace can take several minutes."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"##TESTONLY\n",
|
|
||||||
"# Import the Workspace class and check the Azure ML SDK version.\n",
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.create(name = workspace_name,\n",
|
|
||||||
" subscription_id = subscription_id,\n",
|
|
||||||
" resource_group = resource_group, \n",
|
|
||||||
" location = workspace_region,\n",
|
|
||||||
" auth = auth_sp,\n",
|
|
||||||
" exist_ok=True)\n",
|
|
||||||
"ws.get_details()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Configuring Your Local Environment\n",
|
|
||||||
"You can validate that you have access to the specified workspace and write a configuration file to the default configuration location, `./aml_config/config.json`."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace(workspace_name = workspace_name,\n",
|
|
||||||
" subscription_id = subscription_id,\n",
|
|
||||||
" resource_group = resource_group,\n",
|
|
||||||
" auth = auth_sp)\n",
|
|
||||||
"\n",
|
|
||||||
"# Persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n",
|
|
||||||
"ws.write_config()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Create a Folder to Host Sample Projects\n",
|
|
||||||
"Finally, create a folder where all the sample projects will be hosted."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"\n",
|
|
||||||
"sample_projects_folder = './sample_projects'\n",
|
|
||||||
"\n",
|
|
||||||
"if not os.path.isdir(sample_projects_folder):\n",
|
|
||||||
" os.mkdir(sample_projects_folder)\n",
|
|
||||||
" \n",
|
|
||||||
"print('Sample projects will be created in {}.'.format(sample_projects_folder))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Create an Experiment\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"import os\n",
|
|
||||||
"import random\n",
|
|
||||||
"import time\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"from matplotlib.pyplot import imshow\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Choose a name for the experiment and specify the project folder.\n",
|
|
||||||
"experiment_name = 'automl-local-classification-hdi'\n",
|
|
||||||
"project_folder = './sample_projects/automl-local-classification-hdi'\n",
|
|
||||||
"\n",
|
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
|
||||||
"\n",
|
|
||||||
"output = {}\n",
|
|
||||||
"output['SDK version'] = azureml.core.VERSION\n",
|
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
|
||||||
"output['Workspace Name'] = ws.name\n",
|
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
|
||||||
"output['Location'] = ws.location\n",
|
|
||||||
"output['Project Directory'] = project_folder\n",
|
|
||||||
"output['Experiment Name'] = experiment.name\n",
|
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
|
||||||
"pd.DataFrame(data = output, index = ['']).T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Diagnostics\n",
|
|
||||||
"\n",
|
|
||||||
"Opt-in diagnostics for better experience, quality, and security of future releases."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.telemetry import set_diagnostics_collection\n",
|
|
||||||
"set_diagnostics_collection(send_diagnostics = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Registering Datastore"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Datastore is the way to save connection information to a storage service (e.g. Azure Blob, Azure Data Lake, Azure SQL) information to your workspace so you can access them without exposing credentials in your code. The first thing you will need to do is register a datastore, you can refer to our [python SDK documentation](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.datastore.datastore?view=azure-ml-py) on how to register datastores. __Note: for best security practices, please do not check in code that contains registering datastores with secrets into your source control__\n",
|
|
||||||
"\n",
|
|
||||||
"The code below registers a datastore pointing to a publicly readable blob container."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core import Datastore\n",
|
|
||||||
"\n",
|
|
||||||
"datastore_name = 'demo_training'\n",
|
|
||||||
"container_name = 'digits' \n",
|
|
||||||
"account_name = 'automlpublicdatasets'\n",
|
|
||||||
"Datastore.register_azure_blob_container(\n",
|
|
||||||
" workspace = ws, \n",
|
|
||||||
" datastore_name = datastore_name, \n",
|
|
||||||
" container_name = container_name, \n",
|
|
||||||
" account_name = account_name,\n",
|
|
||||||
" overwrite = True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Below is an example on how to register a private blob container\n",
|
|
||||||
"```python\n",
|
|
||||||
"datastore = Datastore.register_azure_blob_container(\n",
|
|
||||||
" workspace = ws, \n",
|
|
||||||
" datastore_name = 'example_datastore', \n",
|
|
||||||
" container_name = 'example-container', \n",
|
|
||||||
" account_name = 'storageaccount',\n",
|
|
||||||
" account_key = 'accountkey'\n",
|
|
||||||
")\n",
|
|
||||||
"```\n",
|
|
||||||
"The example below shows how to register an Azure Data Lake store. Please make sure you have granted the necessary permissions for the service principal to access the data lake.\n",
|
|
||||||
"```python\n",
|
|
||||||
"datastore = Datastore.register_azure_data_lake(\n",
|
|
||||||
" workspace = ws,\n",
|
|
||||||
" datastore_name = 'example_datastore',\n",
|
|
||||||
" store_name = 'adlsstore',\n",
|
|
||||||
" tenant_id = 'tenant-id-of-service-principal',\n",
|
|
||||||
" client_id = 'client-id-of-service-principal',\n",
|
|
||||||
" client_secret = 'client-secret-of-service-principal'\n",
|
|
||||||
")\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Load Training Data Using DataPrep"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Automated ML takes a Dataflow as input.\n",
|
|
||||||
"\n",
|
|
||||||
"If you are familiar with Pandas and have done your data preparation work in Pandas already, you can use the `read_pandas_dataframe` method in dprep to convert the DataFrame to a Dataflow.\n",
|
|
||||||
"```python\n",
|
|
||||||
"df = pd.read_csv(...)\n",
|
|
||||||
"# apply some transforms\n",
|
|
||||||
"dprep.read_pandas_dataframe(df, temp_folder='/path/accessible/by/both/driver/and/worker')\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"If you just need to ingest data without doing any preparation, you can directly use AzureML Data Prep (Data Prep) to do so. The code below demonstrates this scenario. Data Prep also has data preparation capabilities, we have many [sample notebooks](https://github.com/Microsoft/AMLDataPrepDocs) demonstrating the capabilities.\n",
|
|
||||||
"\n",
|
|
||||||
"You will get the datastore you registered previously and pass it to Data Prep for reading. The data comes from the digits dataset: `sklearn.datasets.load_digits()`. `DataPath` points to a specific location within a datastore. "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.dataprep as dprep\n",
|
|
||||||
"from azureml.data.datapath import DataPath\n",
|
|
||||||
"\n",
|
|
||||||
"datastore = Datastore.get(workspace = ws, datastore_name = datastore_name)\n",
|
|
||||||
"\n",
|
|
||||||
"X_train = dprep.read_csv(datastore.path('X.csv'))\n",
|
|
||||||
"y_train = dprep.read_csv(datastore.path('y.csv')).to_long(dprep.ColumnSelector(term='.*', use_regex = True))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Review the Data Preparation Result\n",
|
|
||||||
"You can peek the result of a Dataflow at any range using `skip(i)` and `head(j)`. Doing so evaluates only j records for all the steps in the Dataflow, which makes it fast even against large datasets."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X_train.get_profile()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"y_train.get_profile()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Configure AutoML\n",
|
|
||||||
"\n",
|
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
|
||||||
"\n",
|
|
||||||
"|Property|Description|\n",
|
|
||||||
"|-|-|\n",
|
|
||||||
"|**task**|classification or regression|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
|
||||||
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
|
||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
|
||||||
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
|
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
|
||||||
"|**spark_context**|Spark Context object. for HDInsight, use spark_context=sc|\n",
|
|
||||||
"|**max_concurrent_iterations**|Maximum number of iterations to execute in parallel. This should be <= number of worker nodes in your Azure HDInsight cluster.|\n",
|
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]<br>Multi-class targets. An indicator matrix turns on multilabel classification. This should be an array of integers.|\n",
|
|
||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n",
|
|
||||||
"|**preprocess**|set this to True to enable pre-processing of data eg. string to numeric using one-hot encoding|\n",
|
|
||||||
"|**exit_score**|Target score for experiment. It is associated with the metric. eg. exit_score=0.995 will exit experiment after that|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" primary_metric = 'AUC_weighted',\n",
|
|
||||||
" iteration_timeout_minutes = 10,\n",
|
|
||||||
" iterations = 3,\n",
|
|
||||||
" preprocess = True,\n",
|
|
||||||
" n_cross_validations = 10,\n",
|
|
||||||
" max_concurrent_iterations = 2, #change it based on number of worker nodes\n",
|
|
||||||
" verbosity = logging.INFO,\n",
|
|
||||||
" spark_context=sc, #HDI /spark related\n",
|
|
||||||
" X = X_train, \n",
|
|
||||||
" y = y_train,\n",
|
|
||||||
" path = project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train the Models\n",
|
|
||||||
"\n",
|
|
||||||
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run = experiment.submit(automl_config, show_output = True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Explore the Results"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"The following will show the child runs and waits for the parent run to complete."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Retrieve All Child Runs after the experiment is completed (in portal)\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Retrieve the Best Model after the above run is complete \n",
|
|
||||||
"\n",
|
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = local_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric after the above run is complete based on the child run\n",
|
|
||||||
"Show the run and the model that has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Test the Best Fitted Model\n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data - you can split the dataset beforehand & pass Train dataset to AutoML and use Test dataset to evaluate the best model."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"blob_location = \"https://{}.blob.core.windows.net/{}\".format(account_name, container_name)\n",
|
|
||||||
"X_test = pd.read_csv(\"{}./X_valid.csv\".format(blob_location), header=0)\n",
|
|
||||||
"y_test = pd.read_csv(\"{}/y_valid.csv\".format(blob_location), header=0)\n",
|
|
||||||
"images = pd.read_csv(\"{}/images.csv\".format(blob_location), header=None)\n",
|
|
||||||
"images = np.reshape(images.values, (100,8,8))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Testing Our Best Fitted Model\n",
|
|
||||||
"We will try to predict digits and see how our model works. This is just an example to show you."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test.values[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
|
|
||||||
" fig = plt.figure(3, figsize = (5,5))\n",
|
|
||||||
" ax1 = fig.add_axes((0,0,.8,.8))\n",
|
|
||||||
" ax1.set_title(title)\n",
|
|
||||||
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
|
|
||||||
" display(fig)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"When deploying an automated ML trained model, please specify _pippackages=['azureml-sdk[automl]']_ in your CondaDependencies.\n",
|
|
||||||
"\n",
|
|
||||||
"Please refer to only the **Deploy** section in this notebook - <a href=\"https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/automated-machine-learning/classification-with-deployment\" target=\"_blank\">Deployment of Automated ML trained model</a>"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "savitam"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "sasum"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "Python",
|
|
||||||
"name": "Python36"
|
|
||||||
},
|
|
||||||
"language_info": {
|
|
||||||
"codemirror_mode": {
|
|
||||||
"name": "python",
|
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "pyspark3",
|
|
||||||
"pygments_lexer": "python3"
|
|
||||||
},
|
|
||||||
"name": "auto-ml-classification-local-adb",
|
|
||||||
"notebookId": 587284549713154
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user