Compare commits

..

291 Commits

Author SHA1 Message Date
Akshaya Annavajhala (AK)
60de701207 revert overwrites 2019-10-15 12:33:31 -07:00
Akshaya Annavajhala (AK)
5841fa4a42 revert overwrites 2019-10-15 12:27:56 -07:00
Shané Winner
659fb7abc3 Merge pull request #619 from Azure/release_update/Release-153
update samples from Release-153 as a part of 1.0.69 SDK release
2019-10-14 15:39:40 -07:00
vizhur
2e404cfc3a update samples from Release-153 as a part of 1.0.69 SDK release 2019-10-14 22:30:58 +00:00
Shané Winner
5fcf4887bc Update index.md 2019-10-06 11:44:35 -07:00
Shané Winner
1e7f3117ae Update index.md 2019-10-06 11:44:01 -07:00
Shané Winner
bbb3f85da9 Update README.md 2019-10-06 11:33:56 -07:00
Shané Winner
c816dfb479 Update index.md 2019-10-06 11:29:58 -07:00
Shané Winner
8c128640b1 Update index.md 2019-10-06 11:28:34 -07:00
vizhur
4d2b937846 Merge pull request #600 from Azure/release_update/Release-24
Fix for Tensorflow 2.0 related Notebook Failures
2019-10-02 16:27:31 -04:00
vizhur
5492f52faf update samples - test 2019-10-02 20:23:54 +00:00
Shané Winner
735db9ebe7 Update index.md 2019-10-01 09:59:10 -07:00
Shané Winner
573030b990 Update README.md 2019-10-01 09:52:10 -07:00
Shané Winner
392a059000 Update index.md 2019-10-01 09:44:37 -07:00
Shané Winner
3580e54fbb Update index.md 2019-10-01 09:42:20 -07:00
Shané Winner
2017bcd716 Update index.md 2019-10-01 09:41:33 -07:00
Roope Astala
4a3f8e7025 Merge pull request #594 from Azure/release_update/Release-149
update samples from Release-149 as a part of 1.0.65 SDK release
2019-09-30 13:29:57 -04:00
vizhur
45880114db update samples from Release-149 as a part of 1.0.65 SDK release 2019-09-30 17:08:52 +00:00
Roope Astala
314bad72a4 Merge pull request #588 from skaarthik/rapids
updating to use AML base image and system managed dependencies
2019-09-25 07:44:31 -04:00
Kaarthik Sivashanmugam
f252308005 updating to use AML base image and system managed dependencies 2019-09-24 20:47:15 -07:00
Kaarthik Sivashanmugam
6622a6c5f2 Merge pull request #1 from Azure/master
merge latest changes from Azure/MLNB repo
2019-09-24 20:40:43 -07:00
Roope Astala
6b19e2f263 Merge pull request #587 from Azure/akshaya-a-patch-3
Update README.md to remove confusing reference
2019-09-24 16:13:16 -04:00
Akshaya Annavajhala
42fd4598cb Update README.md 2019-09-24 15:28:30 -04:00
Roope Astala
476d945439 Merge pull request #580 from akshaya-a/master
Add documentation on the preview ADB linking experience
2019-09-24 09:31:45 -04:00
Shané Winner
e96bb9bef2 Delete manage-runs.yml 2019-09-22 20:37:17 -07:00
Shané Winner
2be4a5e54d Delete manage-runs.ipynb 2019-09-22 20:37:07 -07:00
Shané Winner
247a25f280 Delete hello_with_delay.py 2019-09-22 20:36:50 -07:00
Shané Winner
5d9d8eade6 Delete hello_with_children.py 2019-09-22 20:36:39 -07:00
Shané Winner
dba978e42a Delete hello.py 2019-09-22 20:36:29 -07:00
Shané Winner
7f4101c33e Delete run_details.PNG 2019-09-22 20:36:12 -07:00
Shané Winner
62b0d5df69 Delete run_history.png 2019-09-22 20:36:01 -07:00
Shané Winner
f10b55a1bc Delete logging-api.ipynb 2019-09-22 20:35:47 -07:00
Shané Winner
da9e86635e Delete logging-api.yml 2019-09-22 20:35:36 -07:00
Shané Winner
9ca6388996 Delete datasets-diff.ipynb 2019-09-19 14:14:59 -07:00
Akshaya Annavajhala
3ce779063b address PR feedback 2019-09-18 15:48:42 -04:00
Akshaya Annavajhala
ce635ce4fe add the word mlflow 2019-09-18 13:25:41 -04:00
Akshaya Annavajhala
f08e68c8e9 add linking docs 2019-09-18 11:08:46 -04:00
Shané Winner
93a1d232db Update index.md 2019-09-17 10:00:57 -07:00
Shané Winner
923483528c Update index.md 2019-09-17 09:59:23 -07:00
Shané Winner
cbeacb2ab2 Delete sklearn_regression_model.pkl 2019-09-17 09:37:44 -07:00
Shané Winner
c928c50707 Delete score.py 2019-09-17 09:37:34 -07:00
Shané Winner
efb42bacf9 Delete register-model-deploy-local.ipynb 2019-09-17 09:37:26 -07:00
Shané Winner
d8f349a1ae Delete register-model-deploy-local-advanced.ipynb 2019-09-17 09:37:17 -07:00
Shané Winner
96a61fdc78 Delete myenv.yml 2019-09-17 09:37:08 -07:00
Shané Winner
ff8128f023 Delete helloworld.txt 2019-09-17 09:36:59 -07:00
Shané Winner
8260302a68 Delete dockerSharedDrive.JPG 2019-09-17 09:36:50 -07:00
Shané Winner
fbd7f4a55b Delete README.md 2019-09-17 09:36:41 -07:00
Shané Winner
d4e4206179 Delete helloworld.txt 2019-09-17 09:35:38 -07:00
Shané Winner
a98b918feb Delete model-register-and-deploy.ipynb 2019-09-17 09:35:29 -07:00
Shané Winner
890490ec70 Delete model-register-and-deploy.yml 2019-09-17 09:35:17 -07:00
Shané Winner
c068c9b979 Delete myenv.yml 2019-09-17 09:34:54 -07:00
Shané Winner
f334a3516f Delete score.py 2019-09-17 09:34:44 -07:00
Shané Winner
96248d8dff Delete sklearn_regression_model.pkl 2019-09-17 09:34:27 -07:00
Shané Winner
c42e865700 Delete README.md 2019-09-17 09:29:20 -07:00
vizhur
9233ce089a Merge pull request #577 from Azure/release_update/Release-146
update samples from Release-146 as a part of 1.0.62 SDK release
2019-09-16 19:44:43 -04:00
vizhur
6bb1e2a3e3 update samples from Release-146 as a part of 1.0.62 SDK release 2019-09-16 23:21:57 +00:00
Shané Winner
e1724c8a89 Merge pull request #573 from lostmygithubaccount/master
adding timeseries dataset example notebook
2019-09-16 11:00:30 -07:00
Shané Winner
446e0768cc Delete datasets-diff.ipynb 2019-09-16 10:53:16 -07:00
Cody Peterson
8a2f114a16 adding timeseries dataset example notebook 2019-09-13 08:30:26 -07:00
Shané Winner
80c0d4d30f Merge pull request #570 from trevorbye/master
new pipeline tutorial
2019-09-11 09:28:40 -07:00
Trevor Bye
e8f4708a5a adding index metadata 2019-09-11 09:24:41 -07:00
Trevor Bye
fbaeb84204 adding tutorial 2019-09-11 09:02:06 -07:00
Trevor Bye
da1fab0a77 removing dprep file from old deleted tutorial 2019-09-10 12:31:57 -07:00
Shané Winner
94d2890bb5 Update index.md 2019-09-06 06:37:35 -07:00
Shané Winner
4d1ec4f7d4 Update index.md 2019-09-06 06:30:54 -07:00
Shané Winner
ace3153831 Update index.md 2019-09-06 06:28:50 -07:00
Shané Winner
58bbfe57b2 Update index.md 2019-09-06 06:15:36 -07:00
vizhur
11ea00b1d9 Update index.md 2019-09-06 09:14:30 -04:00
Shané Winner
b81efca3e5 Update index.md 2019-09-06 06:13:03 -07:00
vizhur
d7ceb9bca2 Update index.md 2019-09-06 09:08:02 -04:00
Shané Winner
17730dc69a Merge pull request #564 from MayMSFT/patch-1
Update file-dataset-img-classification.ipynb
2019-09-04 13:31:08 -07:00
May Hu
3a029d48a2 Update file-dataset-img-classification.ipynb
made edit on the sdk version
2019-09-04 13:25:10 -07:00
vizhur
06d43956f3 Merge pull request #558 from Azure/release_update/Release-144
update samples from Release-144 as a part of 1.0.60 SDK release
2019-09-03 22:09:33 -04:00
vizhur
a1cb9b33a5 update samples from Release-144 as a part of 1.0.60 SDK release 2019-09-03 22:39:55 +00:00
Shané Winner
fdc3fe2a53 Delete README.md 2019-08-29 10:22:24 -07:00
Shané Winner
628b35912c Delete train-remote.yml 2019-08-29 10:22:15 -07:00
Shané Winner
3f4cc22e94 Delete train-remote.ipynb 2019-08-29 10:22:07 -07:00
Shané Winner
18d7afb707 Delete train_diabetes.py 2019-08-29 10:21:59 -07:00
Shané Winner
cd35ca30d4 Delete train-local.ipynb 2019-08-29 10:21:48 -07:00
Shané Winner
30eae0b46c Delete train-local.yml 2019-08-29 10:21:40 -07:00
Shané Winner
f16951387f Delete train.py 2019-08-29 10:21:27 -07:00
Shané Winner
0d8de29147 Delete train-and-deploy-pytorch.ipynb 2019-08-29 10:21:16 -07:00
Shané Winner
836354640c Delete train-and-deploy-pytorch.yml 2019-08-29 10:21:08 -07:00
Shané Winner
6162e80972 Delete deploy-model.yml 2019-08-29 10:20:55 -07:00
Shané Winner
fe9fe3392d Delete deploy-model.ipynb 2019-08-29 10:20:46 -07:00
Shané Winner
5ec6d8861b Delete auto-ml-dataprep-remote-execution.yml 2019-08-27 11:19:38 -07:00
Shané Winner
ae188f324e Delete auto-ml-dataprep-remote-execution.ipynb 2019-08-27 11:19:27 -07:00
Shané Winner
4c30c2bdb9 Delete auto-ml-dataprep.yml 2019-08-27 11:19:00 -07:00
Shané Winner
b891440e2d Delete auto-ml-dataprep.ipynb 2019-08-27 11:18:50 -07:00
Shané Winner
784827cdd2 Update README.md 2019-08-27 09:23:40 -07:00
vizhur
0957af04ca Merge pull request #545 from Azure/imatiach-msft-patch-1
add dataprep dependency to notebook
2019-08-23 13:14:30 -04:00
Ilya Matiach
a3bdd193d1 add dataprep dependency to notebook
add dataprep dependency to train-explain-model-on-amlcompute-and-deploy.ipynb notebook for azureml-explain-model package
2019-08-23 13:11:36 -04:00
Shané Winner
dff09970ac Update README.md 2019-08-23 08:38:01 -07:00
Shané Winner
abc7d21711 Update README.md 2019-08-23 05:28:45 +00:00
Shané Winner
ec12ef635f Delete azure-ml-datadrift.ipynb 2019-08-21 10:32:40 -07:00
Shané Winner
81b3e6f09f Delete azure-ml-datadrift.yml 2019-08-21 10:32:32 -07:00
Shané Winner
cc167dceda Delete score.py 2019-08-21 10:32:23 -07:00
Shané Winner
bc52a6d8ee Delete datasets-diff.ipynb 2019-08-21 10:31:50 -07:00
Shané Winner
5bbbdbe73c Delete Titanic.csv 2019-08-21 10:31:38 -07:00
Shané Winner
fd4de05ddd Delete train.py 2019-08-21 10:31:26 -07:00
Shané Winner
9eaab2189d Delete datasets-tutorial.ipynb 2019-08-21 10:31:15 -07:00
Shané Winner
12147754b2 Delete datasets-diff.ipynb 2019-08-21 10:31:05 -07:00
Shané Winner
90ef263823 Delete README.md 2019-08-21 10:30:54 -07:00
Shané Winner
143590cfb4 Delete new-york-taxi_scale-out.ipynb 2019-08-21 10:30:39 -07:00
Shané Winner
40379014ad Delete new-york-taxi.ipynb 2019-08-21 10:30:29 -07:00
Shané Winner
f7b0e99fa1 Delete part-00000-34f8a7a7-c3cd-4926-92b2-ba2dcd3f95b7.gz.parquet 2019-08-21 10:30:18 -07:00
Shané Winner
7a7ac48411 Delete part-00000-34f8a7a7-c3cd-4926-92b2-ba2dcd3f95b7.gz.parquet 2019-08-21 10:30:04 -07:00
Shané Winner
50107c5b1e Delete part-00007-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:29:51 -07:00
Shané Winner
e41d7e6819 Delete part-00006-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:29:36 -07:00
Shané Winner
691e038e84 Delete part-00005-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:29:18 -07:00
Shané Winner
426e79d635 Delete part-00004-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:29:02 -07:00
Shané Winner
326677e87f Delete part-00003-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:28:45 -07:00
Shané Winner
44988e30ae Delete part-00002-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:28:31 -07:00
Shané Winner
646ae37384 Delete part-00001-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:28:18 -07:00
Shané Winner
457e29a663 Delete part-00000-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-08-21 10:28:03 -07:00
Shané Winner
2771edfb2c Delete _SUCCESS 2019-08-21 10:27:45 -07:00
Shané Winner
f0001ec322 Delete adls-dpreptestfiles.crt 2019-08-21 10:27:31 -07:00
Shané Winner
d3e02a017d Delete chicago-aldermen-2015.csv 2019-08-21 10:27:05 -07:00
Shané Winner
a0ebed6876 Delete crime-dirty.csv 2019-08-21 10:26:55 -07:00
Shané Winner
dc0ab6db47 Delete crime-spring.csv 2019-08-21 10:26:45 -07:00
Shané Winner
ea7900f82c Delete crime-winter.csv 2019-08-21 10:26:35 -07:00
Shané Winner
0cb3fd180d Delete crime.parquet 2019-08-21 10:26:26 -07:00
Shané Winner
b05c3e46bb Delete crime.txt 2019-08-21 10:26:17 -07:00
Shané Winner
a1b7d298d3 Delete crime.xlsx 2019-08-21 10:25:41 -07:00
Shané Winner
cc5516c3b3 Delete crime_duplicate_headers.csv 2019-08-21 10:25:32 -07:00
Shané Winner
4fb6070b89 Delete crime.zip 2019-08-21 10:25:23 -07:00
Shané Winner
1b926cdf53 Delete crime-full.csv 2019-08-21 10:25:13 -07:00
Shané Winner
72fc00fb65 Delete crime.dprep 2019-08-21 10:24:56 -07:00
Shané Winner
ddc6b57253 Delete ADLSgen2-datapreptest.crt 2019-08-21 10:24:47 -07:00
Shané Winner
e8b3b98338 Delete crime_fixed_width_file.txt 2019-08-21 10:24:38 -07:00
Shané Winner
66325a1405 Delete crime_multiple_separators.csv 2019-08-21 10:24:29 -07:00
Shané Winner
0efbeaf4b8 Delete json.json 2019-08-21 10:24:12 -07:00
Shané Winner
11d487fb28 Merge pull request #542 from Azure/sgilley/update-deploy
change deployment to model-centric approach
2019-08-21 10:22:13 -07:00
Shané Winner
073e319ef9 Delete large_dflow.json 2019-08-21 10:21:41 -07:00
Shané Winner
3ed75f28d1 Delete map_func.py 2019-08-21 10:21:23 -07:00
Shané Winner
bfc0367f54 Delete median_income.csv 2019-08-21 10:21:14 -07:00
Shané Winner
075eeb583f Delete median_income_transformed.csv 2019-08-21 10:21:05 -07:00
Shané Winner
b7531d3b9e Delete parquet.parquet 2019-08-21 10:20:55 -07:00
Shané Winner
41dc3bd1cf Delete secrets.dprep 2019-08-21 10:20:45 -07:00
Shané Winner
b790b385a4 Delete stream-path.csv 2019-08-21 10:20:36 -07:00
Shané Winner
8700328fe9 Delete summarize.ipynb 2019-08-21 10:17:21 -07:00
Shané Winner
adbd2c8200 Delete subsetting-sampling.ipynb 2019-08-21 10:17:12 -07:00
Shané Winner
7d552effb0 Delete split-column-by-example.ipynb 2019-08-21 10:17:01 -07:00
Shané Winner
bc81d2a5a7 Delete semantic-types.ipynb 2019-08-21 10:16:52 -07:00
Shané Winner
7620de2d91 Delete secrets.ipynb 2019-08-21 10:16:42 -07:00
Shané Winner
07a43a0444 Delete replace-fill-error.ipynb 2019-08-21 10:16:33 -07:00
Shané Winner
f4d5874e09 Delete replace-datasource-replace-reference.ipynb 2019-08-21 10:16:23 -07:00
Shané Winner
8a0b4d24bd Delete random-split.ipynb 2019-08-21 10:16:14 -07:00
Shané Winner
636f19be1f Delete quantile-transformation.ipynb 2019-08-21 10:16:04 -07:00
Shané Winner
0fd7f7d9b2 Delete open-save-dataflows.ipynb 2019-08-21 10:15:54 -07:00
Shané Winner
ab6c66534f Delete one-hot-encoder.ipynb 2019-08-21 10:15:45 -07:00
Shané Winner
faccf13759 Delete min-max-scaler.ipynb 2019-08-21 10:15:36 -07:00
Shané Winner
4c6a28e4ed Delete label-encoder.ipynb 2019-08-21 10:15:25 -07:00
Shané Winner
64ad88e2cb Delete join.ipynb 2019-08-21 10:15:17 -07:00
Shané Winner
969ac90d39 Delete impute-missing-values.ipynb 2019-08-21 10:12:12 -07:00
Shané Winner
fb977c1e95 Delete fuzzy-group.ipynb 2019-08-21 10:12:03 -07:00
Shané Winner
d5ba3916f7 Delete filtering.ipynb 2019-08-21 10:11:53 -07:00
Shané Winner
f7f1087337 Delete external-references.ipynb 2019-08-21 10:11:43 -07:00
Shané Winner
47ea2dbc03 Delete derive-column-by-example.ipynb 2019-08-21 10:11:33 -07:00
Shané Winner
bd2cf534e5 Delete datastore.ipynb 2019-08-21 10:11:24 -07:00
Shané Winner
65f1668d69 Delete data-profile.ipynb 2019-08-21 10:11:16 -07:00
Shané Winner
e0fb7df0aa Delete data-ingestion.ipynb 2019-08-21 10:11:06 -07:00
Shané Winner
7047f76299 Delete custom-python-transforms.ipynb 2019-08-21 10:10:56 -07:00
Shané Winner
c39f2d5eb6 Delete column-type-transforms.ipynb 2019-08-21 10:10:45 -07:00
Shané Winner
5fda69a388 Delete column-manipulations.ipynb 2019-08-21 10:10:36 -07:00
Shané Winner
87ce954eef Delete cache.ipynb 2019-08-21 10:10:26 -07:00
Shané Winner
ebbeac413a Delete auto-read-file.ipynb 2019-08-21 10:10:15 -07:00
Shané Winner
a68bbaaab4 Delete assertions.ipynb 2019-08-21 10:10:05 -07:00
Shané Winner
8784dc979f Delete append-columns-and-rows.ipynb 2019-08-21 10:09:55 -07:00
Shané Winner
f8047544fc Delete add-column-using-expression.ipynb 2019-08-21 10:09:44 -07:00
Shané Winner
eeb2a05e4f Delete working-with-file-streams.ipynb 2019-08-21 10:09:33 -07:00
Shané Winner
6db9d7bd8b Delete writing-data.ipynb 2019-08-21 10:09:19 -07:00
Shané Winner
80e2fde734 Delete getting-started.ipynb 2019-08-21 10:09:04 -07:00
Shané Winner
ae4f5d40ee Delete README.md 2019-08-21 10:08:53 -07:00
Shané Winner
5516edadfd Delete README.md 2019-08-21 10:08:13 -07:00
Sheri Gilley
475afbf44b change deployment to model-centric approach 2019-08-21 09:50:49 -05:00
Shané Winner
197eaf1aab Merge pull request #541 from Azure/sdgilley/update-tutorial
Update img-classification-part1-training.ipynb
2019-08-20 15:59:24 -07:00
Sheri Gilley
184680f1d2 Update img-classification-part1-training.ipynb
updated explanation of datastore
2019-08-20 17:52:45 -05:00
Shané Winner
474f58bd0b Merge pull request #540 from trevorbye/master
removing tutorials for single combined tutorial
2019-08-20 15:22:47 -07:00
Trevor Bye
22c8433897 removing tutorials for single combined tutorial 2019-08-20 12:09:21 -07:00
Josée Martens
822cdd0f01 Update issue templates 2019-08-20 08:35:00 -05:00
Josée Martens
6e65d42986 Update issue templates 2019-08-20 08:26:45 -05:00
Harneet Virk
4c0cbac834 Merge pull request #537 from Azure/release_update/Release-141
update samples from Release-141 as a part of 1.0.57 SDK release
2019-08-19 18:32:44 -07:00
vizhur
44a7481ed1 update samples from Release-141 as a part of 1.0.57 SDK release 2019-08-19 23:33:44 +00:00
Ilya Matiach
8f418b216d Merge pull request #526 from imatiach-msft/ilmat/remove-old-explain-dirs
removing old explain model directories
2019-08-13 12:37:00 -04:00
Ilya Matiach
2d549ecad3 removing old directories 2019-08-13 12:31:51 -04:00
Josée Martens
4dbb024529 Update issue templates 2019-08-11 18:02:17 -05:00
Josée Martens
142a1a510e Update issue templates 2019-08-11 18:00:12 -05:00
vizhur
2522486c26 Merge pull request #519 from wamartin-aml/master
Add dataprep dependency
2019-08-08 09:34:36 -04:00
Walter Martin
6d5226e47c Add dataprep dependency 2019-08-08 09:31:18 -04:00
Shané Winner
e7676d7cdc Delete README.md 2019-08-07 13:14:39 -07:00
Shané Winner
a84f6636f1 Delete README.md 2019-08-07 13:14:24 -07:00
Roope Astala
41be10d1c1 Delete authentication-in-azure-ml.ipynb 2019-08-07 10:12:48 -04:00
vizhur
429eb43914 Merge pull request #513 from Azure/release_update/Release-139
update samples from Release-139 as a part of 1.0.55 SDK release
2019-08-05 16:22:25 -04:00
vizhur
c0dae0c645 update samples from Release-139 as a part of 1.0.55 SDK release 2019-08-05 18:39:19 +00:00
Shané Winner
e4d9a2b4c5 Delete score.py 2019-07-29 09:33:11 -07:00
Shané Winner
7648e8f516 Delete readme.md 2019-07-29 09:32:55 -07:00
Shané Winner
b5ed94b4eb Delete azure-ml-datadrift.ipynb 2019-07-29 09:32:47 -07:00
Shané Winner
85e487f74f Delete new-york-taxi_scale-out.ipynb 2019-07-28 00:38:05 -07:00
Shané Winner
c0a5b2de79 Delete new-york-taxi.ipynb 2019-07-28 00:37:56 -07:00
Shané Winner
0a9e076e5f Delete stream-path.csv 2019-07-28 00:37:44 -07:00
Shané Winner
e3b974811d Delete secrets.dprep 2019-07-28 00:37:33 -07:00
Shané Winner
381d1a6f35 Delete parquet.parquet 2019-07-28 00:37:20 -07:00
Shané Winner
adaa55675e Delete median_income_transformed.csv 2019-07-28 00:37:12 -07:00
Shané Winner
5e3c592d4b Delete median_income.csv 2019-07-28 00:37:02 -07:00
Shané Winner
9c6f1e2571 Delete map_func.py 2019-07-28 00:36:52 -07:00
Shané Winner
bd1bedd563 Delete large_dflow.json 2019-07-28 00:36:43 -07:00
Shané Winner
9716f3614e Delete json.json 2019-07-28 00:36:30 -07:00
Shané Winner
d2c72ca149 Delete crime_multiple_separators.csv 2019-07-28 00:36:19 -07:00
Shané Winner
4f62f64207 Delete crime_fixed_width_file.txt 2019-07-28 00:36:10 -07:00
Shané Winner
16473eb33e Delete crime_duplicate_headers.csv 2019-07-28 00:36:01 -07:00
Shané Winner
d10474c249 Delete crime.zip 2019-07-28 00:35:51 -07:00
Shané Winner
6389cc16f9 Delete crime.xlsx 2019-07-28 00:35:41 -07:00
Shané Winner
bc0a8e0152 Delete crime.txt 2019-07-28 00:35:30 -07:00
Shané Winner
39384aea52 Delete crime.parquet 2019-07-28 00:35:20 -07:00
Shané Winner
5bf4b0bafe Delete crime.dprep 2019-07-28 00:35:11 -07:00
Shané Winner
f22adb7949 Delete crime-winter.csv 2019-07-28 00:35:00 -07:00
Shané Winner
8409ab7133 Delete crime-spring.csv 2019-07-28 00:34:50 -07:00
Shané Winner
32acd55774 Delete crime-full.csv 2019-07-28 00:34:39 -07:00
Shané Winner
7f65c1a255 Delete crime-dirty.csv 2019-07-28 00:34:27 -07:00
Shané Winner
bc7ccc7ef3 Delete chicago-aldermen-2015.csv 2019-07-28 00:34:17 -07:00
Shané Winner
1cc79a71e9 Delete adls-dpreptestfiles.crt 2019-07-28 00:34:05 -07:00
Shané Winner
c0bec5f110 Delete part-00000-34f8a7a7-c3cd-4926-92b2-ba2dcd3f95b7.gz.parquet 2019-07-28 00:33:51 -07:00
Shané Winner
77e5664482 Delete part-00000-34f8a7a7-c3cd-4926-92b2-ba2dcd3f95b7.gz.parquet 2019-07-28 00:33:38 -07:00
Shané Winner
e2eb64372a Delete part-00007-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:33:23 -07:00
Shané Winner
03cbb6a3a2 Delete part-00006-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:33:12 -07:00
Shané Winner
44d3d998a8 Delete part-00005-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:33:00 -07:00
Shané Winner
c626f37057 Delete part-00004-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:32:48 -07:00
Shané Winner
0175574864 Delete part-00003-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:32:37 -07:00
Shané Winner
f6e8d57da3 Delete part-00002-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:32:25 -07:00
Shané Winner
01cd31ce44 Delete part-00001-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:32:13 -07:00
Shané Winner
eb2024b3e0 Delete part-00000-0b08e77b-f17a-4c20-972c-aa382e830fca-c000.csv 2019-07-28 00:32:01 -07:00
Shané Winner
6bce41b3d7 Delete _SUCCESS 2019-07-28 00:31:49 -07:00
Shané Winner
bbdabbb552 Delete writing-data.ipynb 2019-07-28 00:31:32 -07:00
Shané Winner
65343fc263 Delete working-with-file-streams.ipynb 2019-07-28 00:31:22 -07:00
Shané Winner
b6b27fded6 Delete summarize.ipynb 2019-07-28 00:26:56 -07:00
Shané Winner
7e492cbeb6 Delete subsetting-sampling.ipynb 2019-07-28 00:26:41 -07:00
Shané Winner
4cc8f4c6af Delete split-column-by-example.ipynb 2019-07-28 00:26:25 -07:00
Shané Winner
9fba46821b Delete semantic-types.ipynb 2019-07-28 00:26:11 -07:00
Shané Winner
a45954a58f Delete secrets.ipynb 2019-07-28 00:25:58 -07:00
Shané Winner
f16dfb0e5b Delete replace-fill-error.ipynb 2019-07-28 00:25:45 -07:00
Shané Winner
edabbf9031 Delete replace-datasource-replace-reference.ipynb 2019-07-28 00:25:32 -07:00
Shané Winner
63d1d57dfb Delete random-split.ipynb 2019-07-28 00:25:21 -07:00
Shané Winner
10f7004161 Delete quantile-transformation.ipynb 2019-07-28 00:25:10 -07:00
Shané Winner
86ba4e7406 Delete open-save-dataflows.ipynb 2019-07-28 00:24:54 -07:00
Shané Winner
33bda032b8 Delete one-hot-encoder.ipynb 2019-07-28 00:24:43 -07:00
Shané Winner
0fd4bfbc56 Delete min-max-scaler.ipynb 2019-07-28 00:24:32 -07:00
Shané Winner
3fe08c944e Delete label-encoder.ipynb 2019-07-28 00:24:21 -07:00
Shané Winner
d587ea5676 Delete join.ipynb 2019-07-28 00:24:08 -07:00
Shané Winner
edd8562102 Delete impute-missing-values.ipynb 2019-07-28 00:23:55 -07:00
Shané Winner
5ac2c63336 Delete fuzzy-group.ipynb 2019-07-28 00:23:41 -07:00
Shané Winner
1f4e4cdda2 Delete filtering.ipynb 2019-07-28 00:23:28 -07:00
Shané Winner
2e245c1691 Delete external-references.ipynb 2019-07-28 00:23:11 -07:00
Shané Winner
e1b09f71fa Delete derive-column-by-example.ipynb 2019-07-28 00:22:54 -07:00
Shané Winner
8e2220d397 Delete datastore.ipynb 2019-07-28 00:22:43 -07:00
Shané Winner
f74ccf5048 Delete data-profile.ipynb 2019-07-28 00:22:32 -07:00
Shané Winner
97a6d9ca43 Delete data-ingestion.ipynb 2019-07-28 00:22:21 -07:00
Shané Winner
a0ff1c6b64 Delete custom-python-transforms.ipynb 2019-07-28 00:22:11 -07:00
Shané Winner
08f15ef4cf Delete column-type-transforms.ipynb 2019-07-28 00:21:58 -07:00
Shané Winner
7160416c0b Delete column-manipulations.ipynb 2019-07-28 00:21:47 -07:00
Shané Winner
218fed3d65 Delete cache.ipynb 2019-07-28 00:21:35 -07:00
Shané Winner
b8499dfb98 Delete auto-read-file.ipynb 2019-07-28 00:21:22 -07:00
Shané Winner
6bfd472cc2 Delete assertions.ipynb 2019-07-28 00:20:55 -07:00
Shané Winner
ecefb229e9 Delete append-columns-and-rows.ipynb 2019-07-28 00:20:40 -07:00
Shané Winner
883ad806ba Delete add-column-using-expression.ipynb 2019-07-28 00:20:22 -07:00
Shané Winner
848b5bc302 Delete getting-started.ipynb 2019-07-28 00:19:59 -07:00
Shané Winner
58087b53a0 Delete README.md 2019-07-28 00:19:45 -07:00
Shané Winner
ff4d5450a7 Delete README.md 2019-07-28 00:19:29 -07:00
Shané Winner
e2b2b89842 Delete datasets-tutorial.ipynb 2019-07-28 00:19:13 -07:00
Shané Winner
390be2ba24 Delete train.py 2019-07-28 00:19:00 -07:00
Shané Winner
cd1258f81d Delete Titanic.csv 2019-07-28 00:18:41 -07:00
Shané Winner
8a0b48ea48 Delete README.md 2019-07-28 00:18:14 -07:00
Roope Astala
b0dc904189 Merge pull request #502 from msdavx/patch-1
Add demo notebook for datasets diff attribute.
2019-07-26 19:16:13 -04:00
msdavx
82bede239a Add demo notebook for datasets diff attribute. 2019-07-26 11:10:37 -07:00
vizhur
774517e173 Merge pull request #500 from Azure/release_update/Release-137
update samples from Release-137 as a part of 1.0.53 SDK release
2019-07-25 16:36:25 -04:00
Shané Winner
c3ce2bc7fe Delete README.md 2019-07-25 13:28:15 -07:00
Shané Winner
5dd09a1f7c Delete README.md 2019-07-25 13:28:01 -07:00
vizhur
ee1da0ee19 update samples from Release-137 as a part of 1.0.53 SDK release 2019-07-24 22:37:36 +00:00
Paula Ledgerwood
ddfce6b24c Merge pull request #498 from Azure/revert-461-master
Revert "Finetune SSD VGG"
2019-07-24 14:25:43 -07:00
Paula Ledgerwood
31dfc3dc55 Revert "Finetune SSD VGG" 2019-07-24 14:08:00 -07:00
Paula Ledgerwood
168c45b188 Merge pull request #461 from borisneal/master
Finetune SSD VGG
2019-07-24 14:07:15 -07:00
fierval
159948db67 moving notice.txt 2019-07-24 08:50:41 -07:00
fierval
d842731a3b remove tf prereq item 2019-07-23 14:58:51 -07:00
fierval
7822fd4c13 notice + attribution for anchors 2019-07-23 14:49:20 -07:00
fierval
d9fbe4cd87 new folder structure 2019-07-22 10:31:22 -07:00
Shané Winner
a64f4d331a Merge pull request #488 from trevorbye/master
adding new notebook
2019-07-18 10:40:36 -07:00
Trevor Bye
c41f449208 adding new notebook 2019-07-18 10:27:21 -07:00
vizhur
4fe8c1702d Merge pull request #486 from Azure/release_update/Release-22
Fix for automl remote env
2019-07-12 19:18:13 -04:00
vizhur
18cd152591 update samples - test 2019-07-12 22:51:17 +00:00
fierval
b025816c92 remove config.json 2019-07-02 17:32:56 -07:00
fierval
c75e820107 ssd vgg 2019-07-02 17:23:56 -07:00
438 changed files with 146431 additions and 162190 deletions

View File

@@ -1,95 +1,95 @@
# Set up your notebook environment for Azure Machine Learning # Set up your notebook environment for Azure Machine Learning
To run the notebooks in this repository use one of following options. To run the notebooks in this repository use one of following options.
## **Option 1: Use Azure Notebooks** ## **Option 1: Use Azure Notebooks**
Azure Notebooks is a hosted Jupyter-based notebook service in the Azure cloud. Azure Machine Learning Python SDK is already pre-installed in the Azure Notebooks `Python 3.6` kernel. Azure Notebooks is a hosted Jupyter-based notebook service in the Azure cloud. Azure Machine Learning Python SDK is already pre-installed in the Azure Notebooks `Python 3.6` kernel.
1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks) 1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks)
[Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks [Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks
1. Follow the instructions in the [Configuration](configuration.ipynb) notebook to create and connect to a workspace 1. Follow the instructions in the [Configuration](configuration.ipynb) notebook to create and connect to a workspace
1. Open one of the sample notebooks 1. Open one of the sample notebooks
**Make sure the Azure Notebook kernel is set to `Python 3.6`** when you open a notebook by choosing Kernel > Change Kernel > Python 3.6 from the menus. **Make sure the Azure Notebook kernel is set to `Python 3.6`** when you open a notebook by choosing Kernel > Change Kernel > Python 3.6 from the menus.
## **Option 2: Use your own notebook server** ## **Option 2: Use your own notebook server**
### Quick installation ### Quick installation
We recommend you create a Python virtual environment ([Miniconda](https://conda.io/miniconda.html) preferred but [virtualenv](https://virtualenv.pypa.io/en/latest/) works too) and install the SDK in it. We recommend you create a Python virtual environment ([Miniconda](https://conda.io/miniconda.html) preferred but [virtualenv](https://virtualenv.pypa.io/en/latest/) works too) and install the SDK in it.
```sh ```sh
# install just the base SDK # install just the base SDK
pip install azureml-sdk pip install azureml-sdk
# clone the sample repoistory # clone the sample repoistory
git clone https://github.com/Azure/MachineLearningNotebooks.git git clone https://github.com/Azure/MachineLearningNotebooks.git
# below steps are optional # below steps are optional
# install the base SDK, Jupyter notebook server and tensorboard # install the base SDK, Jupyter notebook server and tensorboard
pip install azureml-sdk[notebooks,tensorboard] pip install azureml-sdk[notebooks,tensorboard]
# install model explainability component # install model explainability component
pip install azureml-sdk[explain] pip install azureml-sdk[explain]
# install automated ml components # install automated ml components
pip install azureml-sdk[automl] pip install azureml-sdk[automl]
# install experimental features (not ready for production use) # install experimental features (not ready for production use)
pip install azureml-sdk[contrib] pip install azureml-sdk[contrib]
``` ```
Note the _extras_ (the keywords inside the square brackets) can be combined. For example: Note the _extras_ (the keywords inside the square brackets) can be combined. For example:
```sh ```sh
# install base SDK, Jupyter notebook and automated ml components # install base SDK, Jupyter notebook and automated ml components
pip install azureml-sdk[notebooks,automl] pip install azureml-sdk[notebooks,automl]
``` ```
### Full instructions ### Full instructions
[Install the Azure Machine Learning SDK](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-create-workspace-with-python) [Install the Azure Machine Learning SDK](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-create-workspace-with-python)
Please make sure you start with the [Configuration](configuration.ipynb) notebook to create and connect to a workspace. Please make sure you start with the [Configuration](configuration.ipynb) notebook to create and connect to a workspace.
### Video walkthrough: ### Video walkthrough:
[!VIDEO https://youtu.be/VIsXeTuW3FU] [!VIDEO https://youtu.be/VIsXeTuW3FU]
## **Option 3: Use Docker** ## **Option 3: Use Docker**
You need to have Docker engine installed locally and running. Open a command line window and type the following command. You need to have Docker engine installed locally and running. Open a command line window and type the following command.
__Note:__ We use version `1.0.10` below as an exmaple, but you can replace that with any available version number you like. __Note:__ We use version `1.0.10` below as an exmaple, but you can replace that with any available version number you like.
```sh ```sh
# clone the sample repoistory # clone the sample repoistory
git clone https://github.com/Azure/MachineLearningNotebooks.git git clone https://github.com/Azure/MachineLearningNotebooks.git
# change current directory to the folder # change current directory to the folder
# where Dockerfile of the specific SDK version is located. # where Dockerfile of the specific SDK version is located.
cd MachineLearningNotebooks/Dockerfiles/1.0.10 cd MachineLearningNotebooks/Dockerfiles/1.0.10
# build a Docker image with the a name (azuremlsdk for example) # build a Docker image with the a name (azuremlsdk for example)
# and a version number tag (1.0.10 for example). # and a version number tag (1.0.10 for example).
# this can take several minutes depending on your computer speed and network bandwidth. # this can take several minutes depending on your computer speed and network bandwidth.
docker build . -t azuremlsdk:1.0.10 docker build . -t azuremlsdk:1.0.10
# launch the built Docker container which also automatically starts # launch the built Docker container which also automatically starts
# a Jupyter server instance listening on port 8887 of the host machine # a Jupyter server instance listening on port 8887 of the host machine
docker run -it -p 8887:8887 azuremlsdk:1.0.10 docker run -it -p 8887:8887 azuremlsdk:1.0.10
``` ```
Now you can point your browser to http://localhost:8887. We recommend that you start from the `configuration.ipynb` notebook at the root directory. Now you can point your browser to http://localhost:8887. We recommend that you start from the `configuration.ipynb` notebook at the root directory.
If you need additional Azure ML SDK components, you can either modify the Docker files before you build the Docker images to add additional steps, or install them through command line in the live container after you build the Docker image. For example: If you need additional Azure ML SDK components, you can either modify the Docker files before you build the Docker images to add additional steps, or install them through command line in the live container after you build the Docker image. For example:
```sh ```sh
# install the core SDK and automated ml components # install the core SDK and automated ml components
pip install azureml-sdk[automl] pip install azureml-sdk[automl]
# install the core SDK and model explainability component # install the core SDK and model explainability component
pip install azureml-sdk[explain] pip install azureml-sdk[explain]
# install the core SDK and experimental components # install the core SDK and experimental components
pip install azureml-sdk[contrib] pip install azureml-sdk[contrib]
``` ```
Drag and Drop Drag and Drop
The image will be downloaded by Fatkun The image will be downloaded by Fatkun

144
README.md
View File

@@ -1,68 +1,76 @@
# Azure Machine Learning service example notebooks # Azure Machine Learning service example notebooks
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.
![Azure ML workflow](https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/machine-learning/service/media/overview-what-is-azure-ml/aml.png) ![Azure ML Workflow](https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/machine-learning/service/media/concept-azure-machine-learning-architecture/workflow.png)
## Quick installation
```sh ## Quick installation
pip install azureml-sdk ```sh
``` pip install azureml-sdk
Read more detailed instructions on [how to set up your environment](./NBSETUP.md) using Azure Notebook service, your own Jupyter notebook server, or Docker. ```
Read more detailed instructions on [how to set up your environment](./NBSETUP.md) using Azure Notebook service, your own Jupyter notebook server, or Docker.
## 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. ## 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 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).
* ...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). * ...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).
* ...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). * ...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).
* ...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). * ...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).
* ...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). * ...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 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). * ...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).
* ...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). * ...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) 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
The [Tutorials](./tutorials) folder contains notebooks for the tutorials described in the [Azure Machine Learning documentation](https://aka.ms/aml-docs).
The [Tutorials](./tutorials) folder contains notebooks for the tutorials described in the [Azure Machine Learning documentation](https://aka.ms/aml-docs).
## How to use Azure ML
## How to use Azure ML
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 with Deep Learning](./how-to-use-azureml/training-with-deep-learning) - Examples demonstrating how to build deep learning models using estimators and parameter sweeps - [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
- [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. - [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
- [Automated Machine Learning](./how-to-use-azureml/automated-machine-learning) - Examples using Automated Machine Learning to automatically generate optimal machine learning pipelines and models - [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.
- [Machine Learning Pipelines](./how-to-use-azureml/machine-learning-pipelines) - Examples showing how to create and use reusable pipelines for training and batch scoring - [Automated Machine Learning](./how-to-use-azureml/automated-machine-learning) - Examples using Automated Machine Learning to automatically generate optimal machine learning pipelines and models
- [Deployment](./how-to-use-azureml/deployment) - Examples showing how to deploy and manage machine learning models and solutions - [Machine Learning Pipelines](./how-to-use-azureml/machine-learning-pipelines) - Examples showing how to create and use reusable pipelines for training and batch scoring
- [Azure Databricks](./how-to-use-azureml/azure-databricks) - Examples showing how to use Azure ML with Azure Databricks - [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
--- - [Monitor Models](./how-to-use-azureml/monitor-models) - Examples showing how to enable model monitoring services such as DataDrift
## Documentation
---
* 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/). ## Documentation
* [Python SDK reference](https://docs.microsoft.com/en-us/python/api/overview/azure/ml/intro?view=azure-ml-py)
* Azure ML Data Prep SDK [overview](https://aka.ms/data-prep-sdk), [Python SDK reference](https://aka.ms/aml-data-prep-apiref), and [tutorials and how-tos](https://aka.ms/aml-data-prep-notebooks). * 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/).
* [Python SDK reference](https://docs.microsoft.com/en-us/python/api/overview/azure/ml/intro?view=azure-ml-py)
--- * Azure ML Data Prep SDK [overview](https://aka.ms/data-prep-sdk), [Python SDK reference](https://aka.ms/aml-data-prep-apiref), and [tutorials and how-tos](https://aka.ms/aml-data-prep-notebooks).
## Projects using Azure Machine Learning ---
Visit following repos to see projects contributed by Azure ML users:
## Community Repository
- [Fine tune natural language processing models using Azure Machine Learning service](https://github.com/Microsoft/AzureML-BERT) 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.
- [Fashion MNIST with Azure ML SDK](https://github.com/amynic/azureml-sdk-fashion)
## Projects using Azure Machine Learning
## 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) Visit following repos to see projects contributed by Azure ML users:
- [AMLSamples](https://github.com/Azure/AMLSamples) Number of end-to-end examples, including face recognition, predictive maintenance, customer churn and sentiment analysis.
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code: - [Learn about Natural Language Processing best practices using Azure Machine Learning service](https://github.com/microsoft/nlp)
- [Pre-Train BERT models using Azure Machine Learning service](https://github.com/Microsoft/AzureML-BERT)
```sh - [Fashion MNIST with Azure ML SDK](https://github.com/amynic/azureml-sdk-fashion)
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/README.png)" - [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.
```
This URL will be slightly different depending on the file. ## 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)
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/README.png)
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
```sh
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/README.png)"
```
This URL will be slightly different depending on the file.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/README.png)

View File

@@ -1,383 +1,383 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "roastala" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/configuration.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.5" "# Configuration\n",
} "\n",
}, "_**Setting up your Azure Machine Learning services workspace and configuring your notebook library**_\n",
"nbformat": 4, "\n",
"cells": [ "---\n",
{ "---\n",
"metadata": {}, "\n",
"source": [ "## Table of Contents\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "\n",
"\n", "1. [Introduction](#Introduction)\n",
"Licensed under the MIT License." " 1. What is an Azure Machine Learning workspace\n",
], "1. [Setup](#Setup)\n",
"cell_type": "markdown" " 1. Azure subscription\n",
}, " 1. Azure ML SDK and other library installation\n",
{ " 1. Azure Container Instance registration\n",
"metadata": {}, "1. [Configure your Azure ML Workspace](#Configure%20your%20Azure%20ML%20workspace)\n",
"source": [ " 1. Workspace parameters\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/configuration.png)" " 1. Access your workspace\n",
], " 1. Create a new workspace\n",
"cell_type": "markdown" " 1. Create compute resources\n",
}, "1. [Next steps](#Next%20steps)\n",
{ "\n",
"metadata": {}, "---\n",
"source": [ "\n",
"# Configuration\n", "## Introduction\n",
"\n", "\n",
"_**Setting up your Azure Machine Learning services workspace and configuring your notebook library**_\n", "This notebook configures your library of notebooks to connect to an Azure Machine Learning (ML) workspace. In this case, a library contains all of the notebooks in the current folder and any nested folders. You can configure this notebook library to use an existing workspace or create a new workspace.\n",
"\n", "\n",
"---\n", "Typically you will need to run this notebook only once per notebook library as all other notebooks will use connection information that is written here. If you want to redirect your notebook library to work with a different workspace, then you should re-run this notebook.\n",
"---\n", "\n",
"\n", "In this notebook you will\n",
"## Table of Contents\n", "* Learn about getting an Azure subscription\n",
"\n", "* Specify your workspace parameters\n",
"1. [Introduction](#Introduction)\n", "* Access or create your workspace\n",
" 1. What is an Azure Machine Learning workspace\n", "* Add a default compute cluster for your workspace\n",
"1. [Setup](#Setup)\n", "\n",
" 1. Azure subscription\n", "### What is an Azure Machine Learning workspace\n",
" 1. Azure ML SDK and other library installation\n", "\n",
" 1. Azure Container Instance registration\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, inference, and the monitoring of deployed models."
"1. [Configure your Azure ML Workspace](#Configure%20your%20Azure%20ML%20workspace)\n", ]
" 1. Workspace parameters\n", },
" 1. Access your workspace\n", {
" 1. Create a new workspace\n", "cell_type": "markdown",
" 1. Create compute resources\n", "metadata": {},
"1. [Next steps](#Next%20steps)\n", "source": [
"\n", "## Setup\n",
"---\n", "\n",
"\n", "This section describes activities required before you can access any Azure ML services functionality."
"## Introduction\n", ]
"\n", },
"This notebook configures your library of notebooks to connect to an Azure Machine Learning (ML) workspace. In this case, a library contains all of the notebooks in the current folder and any nested folders. You can configure this notebook library to use an existing workspace or create a new workspace.\n", {
"\n", "cell_type": "markdown",
"Typically you will need to run this notebook only once per notebook library as all other notebooks will use connection information that is written here. If you want to redirect your notebook library to work with a different workspace, then you should re-run this notebook.\n", "metadata": {},
"\n", "source": [
"In this notebook you will\n", "### 1. Azure Subscription\n",
"* Learn about getting an Azure subscription\n", "\n",
"* Specify your workspace parameters\n", "In order to create an Azure ML Workspace, first you need access to an Azure subscription. An Azure subscription allows you to manage storage, compute, and other assets in the Azure cloud. You can [create a new subscription](https://azure.microsoft.com/en-us/free/) or access existing subscription information from the [Azure portal](https://portal.azure.com). Later in this notebook you will need information such as your subscription ID in order to create and access AML workspaces.\n",
"* Access or create your workspace\n", "\n",
"* Add a default compute cluster for your workspace\n", "### 2. Azure ML SDK and other library installation\n",
"\n", "\n",
"### What is an Azure Machine Learning workspace\n", "If you are running in your own environment, follow [SDK installation instructions](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment). If you are running in Azure Notebooks or another Microsoft managed environment, the SDK is already installed.\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, inference, and the monitoring of deployed models." "Also install following libraries to your environment. Many of the example notebooks depend on them\n",
], "\n",
"cell_type": "markdown" "```\n",
}, "(myenv) $ conda install -y matplotlib tqdm scikit-learn\n",
{ "```\n",
"metadata": {}, "\n",
"source": [ "Once installation is complete, the following cell checks the Azure ML SDK version:"
"## Setup\n", ]
"\n", },
"This section describes activities required before you can access any Azure ML services functionality." {
], "cell_type": "code",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {
{ "tags": [
"metadata": {}, "install"
"source": [ ]
"### 1. Azure Subscription\n", },
"\n", "outputs": [],
"In order to create an Azure ML Workspace, first you need access to an Azure subscription. An Azure subscription allows you to manage storage, compute, and other assets in the Azure cloud. You can [create a new subscription](https://azure.microsoft.com/en-us/free/) or access existing subscription information from the [Azure portal](https://portal.azure.com). Later in this notebook you will need information such as your subscription ID in order to create and access AML workspaces.\n", "source": [
"\n", "import azureml.core\n",
"### 2. Azure ML SDK and other library installation\n", "\n",
"\n", "print(\"This notebook was created using version 1.0.69 of the Azure ML SDK\")\n",
"If you are running in your own environment, follow [SDK installation instructions](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment). If you are running in Azure Notebooks or another Microsoft managed environment, the SDK is already installed.\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
"\n", ]
"Also install following libraries to your environment. Many of the example notebooks depend on them\n", },
"\n", {
"```\n", "cell_type": "markdown",
"(myenv) $ conda install -y matplotlib tqdm scikit-learn\n", "metadata": {},
"```\n", "source": [
"\n", "If you are using an older version of the SDK then this notebook was created using, you should upgrade your SDK.\n",
"Once installation is complete, the following cell checks the Azure ML SDK version:" "\n",
], "### 3. Azure Container Instance registration\n",
"cell_type": "markdown" "Azure Machine Learning uses of [Azure Container Instance (ACI)](https://azure.microsoft.com/services/container-instances) to deploy dev/test web services. An Azure subscription needs to be registered to use ACI. If you or the subscription owner have not yet registered ACI on your subscription, you will need to use the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest) and execute the following commands. Note that if you ran through the AML [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) you have already registered ACI. \n",
}, "\n",
{ "```shell\n",
"metadata": { "# check to see if ACI is already registered\n",
"tags": [ "(myenv) $ az provider show -n Microsoft.ContainerInstance -o table\n",
"install" "\n",
] "# if ACI is not registered, run this command.\n",
}, "# note you need to be the subscription owner in order to execute this command successfully.\n",
"outputs": [], "(myenv) $ az provider register -n Microsoft.ContainerInstance\n",
"execution_count": null, "```\n",
"source": [ "\n",
"import azureml.core\n", "---"
"\n", ]
"print(\"This notebook was created using version 1.0.48.post1 of the Azure ML SDK\")\n", },
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" {
], "cell_type": "markdown",
"cell_type": "code" "metadata": {},
}, "source": [
{ "## Configure your Azure ML workspace\n",
"metadata": {}, "\n",
"source": [ "### Workspace parameters\n",
"If you are using an older version of the SDK then this notebook was created using, you should upgrade your SDK.\n", "\n",
"\n", "To use an AML Workspace, you will need to import the Azure ML SDK and supply the following information:\n",
"### 3. Azure Container Instance registration\n", "* Your subscription id\n",
"Azure Machine Learning uses of [Azure Container Instance (ACI)](https://azure.microsoft.com/services/container-instances) to deploy dev/test web services. An Azure subscription needs to be registered to use ACI. If you or the subscription owner have not yet registered ACI on your subscription, you will need to use the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest) and execute the following commands. Note that if you ran through the AML [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) you have already registered ACI. \n", "* A resource group name\n",
"\n", "* (optional) The region that will host your workspace\n",
"```shell\n", "* A name for your workspace\n",
"# check to see if ACI is already registered\n", "\n",
"(myenv) $ az provider show -n Microsoft.ContainerInstance -o table\n", "You can get your subscription ID from the [Azure portal](https://portal.azure.com).\n",
"\n", "\n",
"# if ACI is not registered, run this command.\n", "You will also need access to a [_resource group_](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview#resource-groups), which organizes Azure resources and provides a default region for the resources in a group. You can see what resource groups to which you have access, or create a new one in the [Azure portal](https://portal.azure.com). If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n",
"# note you need to be the subscription owner in order to execute this command successfully.\n", "\n",
"(myenv) $ az provider register -n Microsoft.ContainerInstance\n", "The region to host your workspace will be used if you are creating a new workspace. You do not need to specify this if you are using an existing workspace. You can find the list of supported regions [here](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=machine-learning-service). You should pick a region that is close to your location or that contains your data.\n",
"```\n", "\n",
"\n", "The name for your workspace is unique within the subscription and should be descriptive enough to discern among other AML Workspaces. The subscription may be used only by you, or it may be used by your department or your entire enterprise, so choose a name that makes sense for your situation.\n",
"---" "\n",
], "The following cell allows you to specify your workspace parameters. This cell uses the python method `os.getenv` to read values from environment variables which is useful for automation. If no environment variable exists, the parameters will be set to the specified default values. \n",
"cell_type": "markdown" "\n",
}, "If you ran the Azure Machine Learning [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) in Azure Notebooks, you already have a configured workspace! You can go to your Azure Machine Learning Getting Started library, view *config.json* file, and copy-paste the values for subscription ID, resource group and workspace name below.\n",
{ "\n",
"metadata": {}, "Replace the default values in the cell below with your workspace parameters"
"source": [ ]
"## Configure your Azure ML workspace\n", },
"\n", {
"### Workspace parameters\n", "cell_type": "code",
"\n", "execution_count": null,
"To use an AML Workspace, you will need to import the Azure ML SDK and supply the following information:\n", "metadata": {},
"* Your subscription id\n", "outputs": [],
"* A resource group name\n", "source": [
"* (optional) The region that will host your workspace\n", "import os\n",
"* A name for your workspace\n", "\n",
"\n", "subscription_id = os.getenv(\"SUBSCRIPTION_ID\", default=\"<my-subscription-id>\")\n",
"You can get your subscription ID from the [Azure portal](https://portal.azure.com).\n", "resource_group = os.getenv(\"RESOURCE_GROUP\", default=\"<my-resource-group>\")\n",
"\n", "workspace_name = os.getenv(\"WORKSPACE_NAME\", default=\"<my-workspace-name>\")\n",
"You will also need access to a [_resource group_](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview#resource-groups), which organizes Azure resources and provides a default region for the resources in a group. You can see what resource groups to which you have access, or create a new one in the [Azure portal](https://portal.azure.com). If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n", "workspace_region = os.getenv(\"WORKSPACE_REGION\", default=\"eastus2\")"
"\n", ]
"The region to host your workspace will be used if you are creating a new workspace. You do not need to specify this if you are using an existing workspace. You can find the list of supported regions [here](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=machine-learning-service). You should pick a region that is close to your location or that contains your data.\n", },
"\n", {
"The name for your workspace is unique within the subscription and should be descriptive enough to discern among other AML Workspaces. The subscription may be used only by you, or it may be used by your department or your entire enterprise, so choose a name that makes sense for your situation.\n", "cell_type": "markdown",
"\n", "metadata": {},
"The following cell allows you to specify your workspace parameters. This cell uses the python method `os.getenv` to read values from environment variables which is useful for automation. If no environment variable exists, the parameters will be set to the specified default values. \n", "source": [
"\n", "### Access your workspace\n",
"If you ran the Azure Machine Learning [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) in Azure Notebooks, you already have a configured workspace! You can go to your Azure Machine Learning Getting Started library, view *config.json* file, and copy-paste the values for subscription ID, resource group and workspace name below.\n", "\n",
"\n", "The following cell uses the Azure ML SDK to attempt to load the workspace specified by your parameters. If this cell succeeds, your notebook library will be configured to access the workspace from all notebooks using the `Workspace.from_config()` method. The cell can fail if the specified workspace doesn't exist or you don't have permissions to access it. "
"Replace the default values in the cell below with your workspace parameters" ]
], },
"cell_type": "markdown" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "from azureml.core import Workspace\n",
"import os\n", "\n",
"\n", "try:\n",
"subscription_id = os.getenv(\"SUBSCRIPTION_ID\", default=\"<my-subscription-id>\")\n", " ws = Workspace(subscription_id = subscription_id, resource_group = resource_group, workspace_name = workspace_name)\n",
"resource_group = os.getenv(\"RESOURCE_GROUP\", default=\"<my-resource-group>\")\n", " # write the details of the workspace to a configuration file to the notebook library\n",
"workspace_name = os.getenv(\"WORKSPACE_NAME\", default=\"<my-workspace-name>\")\n", " ws.write_config()\n",
"workspace_region = os.getenv(\"WORKSPACE_REGION\", default=\"eastus2\")" " print(\"Workspace configuration succeeded. Skip the workspace creation steps below\")\n",
], "except:\n",
"cell_type": "code" " print(\"Workspace not accessible. Change your parameters or create a new workspace below\")"
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "markdown",
"### Access your workspace\n", "metadata": {},
"\n", "source": [
"The following cell uses the Azure ML SDK to attempt to load the workspace specified by your parameters. If this cell succeeds, your notebook library will be configured to access the workspace from all notebooks using the `Workspace.from_config()` method. The cell can fail if the specified workspace doesn't exist or you don't have permissions to access it. " "### Create a new workspace\n",
], "\n",
"cell_type": "markdown" "If you don't have an existing workspace and are the owner of the subscription or resource group, you can create a new workspace. If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n",
}, "\n",
{ "**Note**: As with other Azure services, there are limits on certain resources (for example AmlCompute quota) associated with the Azure ML 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.\n",
"metadata": {}, "\n",
"outputs": [], "This cell will create an Azure ML workspace for you in a subscription provided you have the correct permissions.\n",
"execution_count": null, "\n",
"source": [ "This will fail if:\n",
"from azureml.core import Workspace\n", "* You do not have permission to create a workspace in the resource group\n",
"\n", "* You do not have permission to create a resource group if it's non-existing.\n",
"try:\n", "* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription\n",
" ws = Workspace(subscription_id = subscription_id, resource_group = resource_group, workspace_name = workspace_name)\n", "\n",
" # write the details of the workspace to a configuration file to the notebook library\n", "If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources."
" ws.write_config()\n", ]
" print(\"Workspace configuration succeeded. Skip the workspace creation steps below\")\n", },
"except:\n", {
" print(\"Workspace not accessible. Change your parameters or create a new workspace below\")" "cell_type": "code",
], "execution_count": null,
"cell_type": "code" "metadata": {
}, "tags": [
{ "create workspace"
"metadata": {}, ]
"source": [ },
"### Create a new workspace\n", "outputs": [],
"\n", "source": [
"If you don't have an existing workspace and are the owner of the subscription or resource group, you can create a new workspace. If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n", "from azureml.core import Workspace\n",
"\n", "\n",
"**Note**: As with other Azure services, there are limits on certain resources (for example AmlCompute quota) associated with the Azure ML 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.\n", "# Create the workspace using the specified parameters\n",
"\n", "ws = Workspace.create(name = workspace_name,\n",
"This cell will create an Azure ML workspace for you in a subscription provided you have the correct permissions.\n", " subscription_id = subscription_id,\n",
"\n", " resource_group = resource_group, \n",
"This will fail if:\n", " location = workspace_region,\n",
"* You do not have permission to create a workspace in the resource group\n", " create_resource_group = True,\n",
"* You do not have permission to create a resource group if it's non-existing.\n", " exist_ok = True)\n",
"* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription\n", "ws.get_details()\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." "# write the details of the workspace to a configuration file to the notebook library\n",
], "ws.write_config()"
"cell_type": "markdown" ]
}, },
{ {
"metadata": { "cell_type": "markdown",
"tags": [ "metadata": {},
"create workspace" "source": [
] "### Create compute resources for your training experiments\n",
}, "\n",
"outputs": [], "Many of the sample notebooks use Azure ML managed compute (AmlCompute) to train models using a dynamically scalable pool of compute. In this section you will create default compute clusters for use by the other notebooks and any other operations you choose.\n",
"execution_count": null, "\n",
"source": [ "To create a cluster, you need to specify a compute configuration that specifies the type of machine to be used and the scalability behaviors. Then you choose a name for the cluster that is unique within the workspace that can be used to address the cluster later.\n",
"from azureml.core import Workspace\n", "\n",
"\n", "The cluster parameters are:\n",
"# Create the workspace using the specified parameters\n", "* vm_size - this describes the virtual machine type and size used in the cluster. All machines in the cluster are the same type. You can get the list of vm sizes available in your region by using the CLI command\n",
"ws = Workspace.create(name = workspace_name,\n", "\n",
" subscription_id = subscription_id,\n", "```shell\n",
" resource_group = resource_group, \n", "az vm list-skus -o tsv\n",
" location = workspace_region,\n", "```\n",
" create_resource_group = True,\n", "* min_nodes - this sets the minimum size of the cluster. If you set the minimum to 0 the cluster will shut down all nodes while not in use. Setting this number to a value higher than 0 will allow for faster start-up times, but you will also be billed when the cluster is not in use.\n",
" exist_ok = True)\n", "* max_nodes - this sets the maximum size of the cluster. Setting this to a larger number allows for more concurrency and a greater distributed processing of scale-out jobs.\n",
"ws.get_details()\n", "\n",
"\n", "\n",
"# write the details of the workspace to a configuration file to the notebook library\n", "To create a **CPU** cluster now, run the cell below. The autoscale settings mean that the cluster will scale down to 0 nodes when inactive and up to 4 nodes when busy."
"ws.write_config()" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"### Create compute resources for your training experiments\n", "source": [
"\n", "from azureml.core.compute import ComputeTarget, AmlCompute\n",
"Many of the sample notebooks use Azure ML managed compute (AmlCompute) to train models using a dynamically scalable pool of compute. In this section you will create default compute clusters for use by the other notebooks and any other operations you choose.\n", "from azureml.core.compute_target import ComputeTargetException\n",
"\n", "\n",
"To create a cluster, you need to specify a compute configuration that specifies the type of machine to be used and the scalability behaviors. Then you choose a name for the cluster that is unique within the workspace that can be used to address the cluster later.\n", "# Choose a name for your CPU cluster\n",
"\n", "cpu_cluster_name = \"cpu-cluster\"\n",
"The cluster parameters are:\n", "\n",
"* vm_size - this describes the virtual machine type and size used in the cluster. All machines in the cluster are the same type. You can get the list of vm sizes available in your region by using the CLI command\n", "# Verify that cluster does not exist already\n",
"\n", "try:\n",
"```shell\n", " cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
"az vm list-skus -o tsv\n", " print(\"Found existing cpu-cluster\")\n",
"```\n", "except ComputeTargetException:\n",
"* min_nodes - this sets the minimum size of the cluster. If you set the minimum to 0 the cluster will shut down all nodes while not in use. Setting this number to a value higher than 0 will allow for faster start-up times, but you will also be billed when the cluster is not in use.\n", " print(\"Creating new cpu-cluster\")\n",
"* max_nodes - this sets the maximum size of the cluster. Setting this to a larger number allows for more concurrency and a greater distributed processing of scale-out jobs.\n", " \n",
"\n", " # Specify the configuration for the new cluster\n",
"\n", " compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_D2_V2\",\n",
"To create a **CPU** cluster now, run the cell below. The autoscale settings mean that the cluster will scale down to 0 nodes when inactive and up to 4 nodes when busy." " min_nodes=0,\n",
], " max_nodes=4)\n",
"cell_type": "markdown" "\n",
}, " # Create the cluster with the specified name and configuration\n",
{ " cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
"metadata": {}, " \n",
"outputs": [], " # Wait for the cluster to complete, show the output log\n",
"execution_count": null, " cpu_cluster.wait_for_completion(show_output=True)"
"source": [ ]
"from azureml.core.compute import ComputeTarget, AmlCompute\n", },
"from azureml.core.compute_target import ComputeTargetException\n", {
"\n", "cell_type": "markdown",
"# Choose a name for your CPU cluster\n", "metadata": {},
"cpu_cluster_name = \"cpu-cluster\"\n", "source": [
"\n", "To create a **GPU** cluster, run the cell below. Note that your subscription must have sufficient quota for GPU VMs or the command will fail. To increase quota, see [these instructions](https://docs.microsoft.com/en-us/azure/azure-supportability/resource-manager-core-quotas-request). "
"# Verify that cluster does not exist already\n", ]
"try:\n", },
" cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n", {
" print(\"Found existing cpu-cluster\")\n", "cell_type": "code",
"except ComputeTargetException:\n", "execution_count": null,
" print(\"Creating new cpu-cluster\")\n", "metadata": {},
" \n", "outputs": [],
" # Specify the configuration for the new cluster\n", "source": [
" compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_D2_V2\",\n", "from azureml.core.compute import ComputeTarget, AmlCompute\n",
" min_nodes=0,\n", "from azureml.core.compute_target import ComputeTargetException\n",
" max_nodes=4)\n", "\n",
"\n", "# Choose a name for your GPU cluster\n",
" # Create the cluster with the specified name and configuration\n", "gpu_cluster_name = \"gpu-cluster\"\n",
" cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n", "\n",
" \n", "# Verify that cluster does not exist already\n",
" # Wait for the cluster to complete, show the output log\n", "try:\n",
" cpu_cluster.wait_for_completion(show_output=True)" " gpu_cluster = ComputeTarget(workspace=ws, name=gpu_cluster_name)\n",
], " print(\"Found existing gpu cluster\")\n",
"cell_type": "code" "except ComputeTargetException:\n",
}, " print(\"Creating new gpu-cluster\")\n",
{ " \n",
"metadata": {}, " # Specify the configuration for the new cluster\n",
"source": [ " compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_NC6\",\n",
"To create a **GPU** cluster, run the cell below. Note that your subscription must have sufficient quota for GPU VMs or the command will fail. To increase quota, see [these instructions](https://docs.microsoft.com/en-us/azure/azure-supportability/resource-manager-core-quotas-request). " " min_nodes=0,\n",
], " max_nodes=4)\n",
"cell_type": "markdown" " # Create the cluster with the specified name and configuration\n",
}, " gpu_cluster = ComputeTarget.create(ws, gpu_cluster_name, compute_config)\n",
{ "\n",
"metadata": {}, " # Wait for the cluster to complete, show the output log\n",
"outputs": [], " gpu_cluster.wait_for_completion(show_output=True)"
"execution_count": null, ]
"source": [ },
"from azureml.core.compute import ComputeTarget, AmlCompute\n", {
"from azureml.core.compute_target import ComputeTargetException\n", "cell_type": "markdown",
"\n", "metadata": {},
"# Choose a name for your GPU cluster\n", "source": [
"gpu_cluster_name = \"gpu-cluster\"\n", "---\n",
"\n", "\n",
"# Verify that cluster does not exist already\n", "## Next steps\n",
"try:\n", "\n",
" gpu_cluster = ComputeTarget(workspace=ws, name=gpu_cluster_name)\n", "In this notebook you configured this notebook library to connect easily to an Azure ML workspace. You can copy this notebook to your own libraries to connect them to you workspace, or use it to bootstrap new workspaces completely.\n",
" print(\"Found existing gpu cluster\")\n", "\n",
"except ComputeTargetException:\n", "If you came here from another notebook, you can return there and complete that exercise, or you can try out the [Tutorials](./tutorials) or jump into \"how-to\" notebooks and start creating and deploying models. A good place to start is the [train within notebook](./how-to-use-azureml/training/train-within-notebook) example that walks through a simplified but complete end to end machine learning process."
" print(\"Creating new gpu-cluster\")\n", ]
" \n", },
" # Specify the configuration for the new cluster\n", {
" compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_NC6\",\n", "cell_type": "code",
" min_nodes=0,\n", "execution_count": null,
" max_nodes=4)\n", "metadata": {},
" # Create the cluster with the specified name and configuration\n", "outputs": [],
" gpu_cluster = ComputeTarget.create(ws, gpu_cluster_name, compute_config)\n", "source": []
"\n", }
" # Wait for the cluster to complete, show the output log\n", ],
" gpu_cluster.wait_for_completion(show_output=True)" "metadata": {
], "authors": [
"cell_type": "code" {
}, "name": "roastala"
{ }
"metadata": {}, ],
"source": [ "kernelspec": {
"---\n", "display_name": "Python 3.6",
"\n", "language": "python",
"## Next steps\n", "name": "python36"
"\n", },
"In this notebook you configured this notebook library to connect easily to an Azure ML workspace. You can copy this notebook to your own libraries to connect them to you workspace, or use it to bootstrap new workspaces completely.\n", "language_info": {
"\n", "codemirror_mode": {
"If you came here from another notebook, you can return there and complete that exercise, or you can try out the [Tutorials](./tutorials) or jump into \"how-to\" notebooks and start creating and deploying models. A good place to start is the [train within notebook](./how-to-use-azureml/training/train-within-notebook) example that walks through a simplified but complete end to end machine learning process." "name": "ipython",
], "version": 3
"cell_type": "markdown" },
}, "file_extension": ".py",
{ "mimetype": "text/x-python",
"metadata": {}, "name": "python",
"outputs": [], "nbconvert_exporter": "python",
"execution_count": null, "pygments_lexer": "ipython3",
"source": [], "version": "3.6.5"
"cell_type": "code" }
} },
], "nbformat": 4,
"nbformat_minor": 2 "nbformat_minor": 2
} }

View File

@@ -1,4 +1,4 @@
name: configuration name: configuration
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk

File diff suppressed because it is too large Load Diff

View File

@@ -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))
@@ -481,14 +457,13 @@ def main():
gpu_dfs = [gpu_df.persist() for gpu_df in gpu_dfs] gpu_dfs = [gpu_df.persist() for gpu_df in gpu_dfs]
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__':

View File

@@ -8,7 +8,7 @@ As a pre-requisite, run the [configuration Notebook](../configuration.ipynb) not
* [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. * [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-data-collection-for-models-in-aks](./deployment/enable-data-collection-for-models-in-aks) Learn about data collection APIs for deployed model.

View File

@@ -1,290 +1,299 @@
# 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 Azure Notebooks](#jupyter)
1. [Setup using Azure Databricks](#databricks) 1. [Setup using Azure Databricks](#databricks)
1. [Setup using a Local Conda environment](#localconda) 1. [Setup using a Local Conda environment](#localconda)
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)
1. [Troubleshooting](#troubleshooting) 1. [Troubleshooting](#troubleshooting)
<a name="introduction"></a> <a name="introduction"></a>
# Automated ML introduction # 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. 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 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. 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.
Below are the three execution environments supported by automated ML. 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 Azure Notebooks - Jupyter based notebooks in the Azure cloud
1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks) 1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks)
[Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks. [Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks.
1. Follow the instructions in the [configuration](../../configuration.ipynb) notebook to create and connect to a workspace. 1. Follow the instructions in the [configuration](../../configuration.ipynb) notebook to create and connect to a workspace.
1. Open one of the sample notebooks. 1. Open one of the sample notebooks.
<a name="databricks"></a> <a name="databricks"></a>
## Setup using Azure Databricks ## Setup using Azure Databricks
**NOTE**: Please create your Azure Databricks cluster as v4.x (high concurrency preferred) with **Python 3** (dropdown). **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. **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. - 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). - 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. - 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. - 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
To run these notebook on your own notebook server, use these installation instructions. 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. The instructions below will install everything you need and then start a Jupyter notebook.
### 1. Install mini-conda from [here](https://conda.io/miniconda.html), choose 64-bit Python 3.7 or higher. ### 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. - **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. There's no need to install mini-conda specifically.
### 2. Downloading the sample notebooks ### 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. - 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 ### 3. Setup a new conda environment
The **automl_setup** 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. 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. The **automl_setup** 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. 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: 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>scipy</li><li>scikit-learn</li><li>pandas</li><li>tensorflow</li><li>py-xgboost</li><li>azureml-sdk</li><li>azureml-widgets</li><li>pandas-ml</li></ul> <ul><li>python</li><li>nb_conda</li><li>matplotlib</li><li>numpy</li><li>cython</li><li>urllib3</li><li>scipy</li><li>scikit-learn</li><li>pandas</li><li>tensorflow</li><li>py-xgboost</li><li>azureml-sdk</li><li>azureml-widgets</li><li>pandas-ml</li></ul>
For more details refer to the [automl_env.yml](./automl_env.yml) For more details refer to the [automl_env.yml](./automl_env.yml)
## Windows ## Windows
Start an **Anaconda Prompt** window, cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run: Start an **Anaconda Prompt** window, cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run:
``` ```
automl_setup automl_setup
``` ```
## Mac ## Mac
Install "Command line developer tools" if it is not already installed (you can use the command: `xcode-select --install`). 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** folder where the sample notebooks were extracted and then run: Start a Terminal windows, cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run:
``` ```
bash automl_setup_mac.sh bash automl_setup_mac.sh
``` ```
## Linux ## Linux
cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run: cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run:
``` ```
bash automl_setup_linux.sh bash automl_setup_linux.sh
``` ```
### 4. Running configuration.ipynb ### 4. Running configuration.ipynb
- Before running any samples you next need to run the configuration notebook. Click on [configuration](../../configuration.ipynb) notebook - 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*) - Execute the cells in the notebook to Register Machine Learning Services Resource Provider and create a workspace. (*instructions in notebook*)
### 5. Running Samples ### 5. Running Samples
- Please make sure you use the Python [conda env:azure_automl] kernel when trying the sample Notebooks. - Please make sure you use the Python [conda env:azure_automl] kernel when trying the sample Notebooks.
- Follow the instructions in the individual notebooks to explore various features in automated ML. - Follow the instructions in the individual notebooks to explore various features in automated ML.
### 6. Starting jupyter notebook manually ### 6. Starting jupyter notebook manually
To start your Jupyter notebook manually, use: To start your Jupyter notebook manually, use:
``` ```
conda activate azure_automl conda activate azure_automl
jupyter notebook jupyter notebook
``` ```
or on Mac or Linux: or on Mac or Linux:
``` ```
source activate azure_automl source activate azure_automl
jupyter notebook jupyter notebook
``` ```
<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.ipynb](classification/auto-ml-classification.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - 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 - Simple example of using automated ML for classification
- Uses local compute for training - Uses local 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: scikit learn's [diabetes dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html)
- Simple example of using automated ML for regression - Simple example of using automated ML for regression
- Uses local compute for training - Uses local compute for training
- [auto-ml-remote-amlcompute.ipynb](remote-amlcompute/auto-ml-remote-amlcompute.ipynb) - [auto-ml-remote-amlcompute.ipynb](remote-amlcompute/auto-ml-remote-amlcompute.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
- Example of using automated ML for classification using remote AmlCompute for training - Example of using automated ML for classification using remote AmlCompute for training
- Parallel execution of iterations - Parallel execution of iterations
- Async tracking of progress - Async tracking of progress
- Cancelling individual iterations or entire run - Cancelling individual iterations or entire run
- Retrieving models for any iteration or logged metric - Retrieving models for any iteration or logged metric
- Specify automated ML settings as kwargs - 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) - [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) - 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 - Blacklist certain pipelines
- Specify a target metrics to indicate stopping criteria - Specify a target metrics to indicate stopping criteria
- Handling Missing Data in the input - 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) - [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) - Dataset: Scikit learn's [20newsgroup](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html)
- Handle sparse datasets - Handle sparse datasets
- Specify custom train and validation set - Specify custom train and validation set
- [auto-ml-exploring-previous-runs.ipynb](exploring-previous-runs/auto-ml-exploring-previous-runs.ipynb) - [auto-ml-exploring-previous-runs.ipynb](exploring-previous-runs/auto-ml-exploring-previous-runs.ipynb)
- List all projects for the workspace - List all projects for the workspace
- List all automated ML Runs for a given project - List all automated ML Runs for a given project
- Get details for a automated ML Run. (automated ML settings, run widget & all metrics) - Get details for a automated ML Run. (automated ML settings, run widget & all metrics)
- Download fitted pipeline for any iteration - Download fitted pipeline for any iteration
- [auto-ml-classification-with-deployment.ipynb](classification-with-deployment/auto-ml-classification-with-deployment.ipynb) - [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) - 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 - Simple example of using automated ML for classification
- Registering the model - Registering the model
- Creating Image and creating aci service - Creating Image and creating aci service
- Testing the aci service - Testing the aci service
- [auto-ml-sample-weight.ipynb](sample-weight/auto-ml-sample-weight.ipynb) - [auto-ml-sample-weight.ipynb](sample-weight/auto-ml-sample-weight.ipynb)
- How to specifying sample_weight - How to specifying sample_weight
- The difference that it makes to test results - The difference that it makes to test results
- [auto-ml-subsampling-local.ipynb](subsampling/auto-ml-subsampling-local.ipynb) - [auto-ml-subsampling-local.ipynb](subsampling/auto-ml-subsampling-local.ipynb)
- How to enable subsampling - How to enable subsampling
- [auto-ml-dataprep.ipynb](dataprep/auto-ml-dataprep.ipynb) - [auto-ml-dataset.ipynb](dataprep/auto-ml-dataset.ipynb)
- Using DataPrep for reading data - Using Dataset for reading data
- [auto-ml-dataprep-remote-execution.ipynb](dataprep-remote-execution/auto-ml-dataprep-remote-execution.ipynb) - [auto-ml-dataset-remote-execution.ipynb](dataprep-remote-execution/auto-ml-dataset-remote-execution.ipynb)
- Using DataPrep for reading data with remote execution - Using Dataset for reading data with remote execution
- [auto-ml-classification-with-whitelisting.ipynb](classification-with-whitelisting/auto-ml-classification-with-whitelisting.ipynb) - [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) - 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. - Simple example of using automated ML for classification with whitelisting tensorflow models.
- Uses local compute for training - 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-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-classification-with-onnx.ipynb](classification-with-onnx/auto-ml-classification-with-onnx.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - Dataset: scikit learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html)
- Simple example of using automated ML for classification with ONNX models - Simple example of using automated ML for classification with ONNX models
- Uses local compute for training - Uses local compute for training
- [auto-ml-bank-marketing-subscribers-with-deployment.ipynb](bank-marketing-subscribers-with-deployment/auto-ml-bank-marketing-with-deployment.ipynb) - [auto-ml-remote-amlcompute-with-onnx.ipynb](remote-amlcompute-with-onnx/auto-ml-remote-amlcompute-with-onnx.ipynb)
- Dataset: UCI's [bank marketing dataset](https://www.kaggle.com/janiobachmann/bank-marketing-dataset) - Dataset: scikit learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html)
- Simple example of using automated ML for classification to predict term deposit subscriptions for a bank - Example of using automated ML for classification using remote AmlCompute for training
- Uses azure compute for training - Train the models with ONNX compatible config on
- Parallel execution of iterations
- [auto-ml-creditcard-with-deployment.ipynb](credit-card-fraud-detection-with-deployment/auto-ml-creditcard-with-deployment.ipynb) - Async tracking of progress
- Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud) - Cancelling individual iterations or entire run
- Simple example of using automated ML for classification to fraudulent credit card transactions - Retrieving the ONNX models and do the inference with them
- Uses azure compute for training
- [auto-ml-bank-marketing-subscribers-with-deployment.ipynb](bank-marketing-subscribers-with-deployment/auto-ml-bank-marketing-with-deployment.ipynb)
- [auto-ml-hardware-performance-with-deployment.ipynb](hardware-performance-prediction-with-deployment/auto-ml-hardware-performance-with-deployment.ipynb) - Dataset: UCI's [bank marketing dataset](https://www.kaggle.com/janiobachmann/bank-marketing-dataset)
- Dataset: UCI's [computer hardware dataset](https://archive.ics.uci.edu/ml/datasets/Computer+Hardware) - Simple example of using automated ML for classification to predict term deposit subscriptions for a bank
- Simple example of using automated ML for regression to predict the performance of certain combinations of hardware components - Uses azure compute for training
- Uses azure compute for training
- [auto-ml-creditcard-with-deployment.ipynb](credit-card-fraud-detection-with-deployment/auto-ml-creditcard-with-deployment.ipynb)
- [auto-ml-concrete-strength-with-deployment.ipynb](predicting-concrete-strength-with-deployment/auto-ml-concrete-strength-with-deployment.ipynb) - Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud)
- Dataset: UCI's [concrete compressive strength dataset](https://www.kaggle.com/pavanraj159/concrete-compressive-strength-data-set) - Simple example of using automated ML for classification to fraudulent credit card transactions
- Simple example of using automated ML for regression to predict the strength predict the compressive strength of concrete based off of different ingredient combinations and quantities of those ingredients - Uses azure compute for training
- Uses azure compute for training
- [auto-ml-hardware-performance-with-deployment.ipynb](hardware-performance-prediction-with-deployment/auto-ml-hardware-performance-with-deployment.ipynb)
<a name="documentation"></a> - Dataset: UCI's [computer hardware dataset](https://archive.ics.uci.edu/ml/datasets/Computer+Hardware)
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. - Simple example of using automated ML for regression to predict the performance of certain combinations of hardware components
- Uses azure compute for training
<a name="pythoncommand"></a>
# Running using python command - [auto-ml-concrete-strength-with-deployment.ipynb](predicting-concrete-strength-with-deployment/auto-ml-concrete-strength-with-deployment.ipynb)
Jupyter notebook provides a File / Download as / Python (.py) option for saving the notebook as a Python file. - Dataset: UCI's [concrete compressive strength dataset](https://www.kaggle.com/pavanraj159/concrete-compressive-strength-data-set)
You can then run this file using the python command. - Simple example of using automated ML for regression to predict the strength predict the compressive strength of concrete based off of different ingredient combinations and quantities of those ingredients
However, on Windows the file needs to be modified before it can be run. - Uses azure compute for training
The following condition must be added to the main code in the file:
<a name="documentation"></a>
if __name__ == "__main__": 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.
The main code of the file must be indented so that it is under this condition. <a name="pythoncommand"></a>
# Running using python command
<a name="troubleshooting"></a> Jupyter notebook provides a File / Download as / Python (.py) option for saving the notebook as a Python file.
# Troubleshooting You can then run this file using the python command.
## automl_setup fails However, on Windows the file needs to be modified before it can be run.
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) The following condition must be added to the main code in the file:
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`. if __name__ == "__main__":
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>`. The main code of the file must be indented so that it is under this condition.
## automl_setup_linux.sh fails <a name="troubleshooting"></a>
If automl_setup_linux.sh fails on Ubuntu Linux with the error: `unable to execute 'gcc': No such file or directory` # Troubleshooting
1. Make sure that outbound ports 53 and 80 are enabled. On an Azure VM, you can do this from the Azure Portal by selecting the VM and clicking on Networking. ## automl_setup fails
2. Run the command: `sudo apt-get update` 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)
3. Run the command: `sudo apt-get install build-essential --fix-missing` 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.
4. Run `automl_setup_linux.sh` again. 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`.
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`.
## configuration.ipynb fails 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>`.
1) For local conda, make sure that you have susccessfully run automl_setup first.
2) Check that the subscription_id is correct. You can find the subscription_id in the Azure Portal by selecting All Service and then Subscriptions. The characters "<" and ">" should not be included in the subscription_id value. For example, `subscription_id = "12345678-90ab-1234-5678-1234567890abcd"` has the valid format. ## automl_setup_linux.sh fails
3) Check that you have Contributor or Owner access to the Subscription. If automl_setup_linux.sh fails on Ubuntu Linux with the error: `unable to execute 'gcc': No such file or directory`
4) Check that the region is one of the supported regions: `eastus2`, `eastus`, `westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus` 1. Make sure that outbound ports 53 and 80 are enabled. On an Azure VM, you can do this from the Azure Portal by selecting the VM and clicking on Networking.
5) Check that you have access to the region using the Azure Portal. 2. Run the command: `sudo apt-get update`
3. Run the command: `sudo apt-get install build-essential --fix-missing`
## workspace.from_config fails 4. Run `automl_setup_linux.sh` again.
If the call `ws = Workspace.from_config()` fails:
1) Make sure that you have run the `configuration.ipynb` notebook successfully. ## configuration.ipynb fails
2) If you are running a notebook from a folder that is not under the folder where you ran `configuration.ipynb`, copy the folder aml_config and the file config.json that it contains to the new folder. Workspace.from_config reads the config.json for the notebook folder or it parent folder. 1) For local conda, make sure that you have susccessfully run automl_setup first.
3) If you are switching to a new subscription, resource group, workspace or region, make sure that you run the `configuration.ipynb` notebook again. Changing config.json directly will only work if the workspace already exists in the specified resource group under the specified subscription. 2) Check that the subscription_id is correct. You can find the subscription_id in the Azure Portal by selecting All Service and then Subscriptions. The characters "<" and ">" should not be included in the subscription_id value. For example, `subscription_id = "12345678-90ab-1234-5678-1234567890abcd"` has the valid format.
4) If you want to change the region, please change the workspace, resource group or subscription. `Workspace.create` will not create or update a workspace if it already exists, even if the region specified is different. 3) Check that you have Contributor or Owner access to the Subscription.
4) Check that the region is one of the supported regions: `eastus2`, `eastus`, `westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus`
## Sample notebook fails 5) Check that you have access to the region using the Azure Portal.
If a sample notebook fails with an error that property, method or library does not exist:
1) Check that you have selected correct kernel in jupyter notebook. The kernel is displayed in the top right of the notebook page. It can be changed using the `Kernel | Change Kernel` menu option. For Azure Notebooks, it should be `Python 3.6`. For local conda environments, it should be the conda envioronment name that you specified in automl_setup. The default is azure_automl. Note that the kernel is saved as part of the notebook. So, if you switch to a new conda environment, you will have to select the new kernel in the notebook. ## workspace.from_config fails
2) Check that the notebook is for the SDK version that you are using. You can check the SDK version by executing `azureml.core.VERSION` in a jupyter notebook cell. You can download previous version of the sample notebooks from GitHub by clicking the `Branch` button, selecting the `Tags` tab and then selecting the version. If the call `ws = Workspace.from_config()` fails:
1) Make sure that you have run the `configuration.ipynb` notebook successfully.
## Numpy import fails on Windows 2) If you are running a notebook from a folder that is not under the folder where you ran `configuration.ipynb`, copy the folder aml_config and the file config.json that it contains to the new folder. Workspace.from_config reads the config.json for the notebook folder or it parent folder.
Some Windows environments see an error loading numpy with the latest Python version 3.6.8. If you see this issue, try with Python version 3.6.7. 3) If you are switching to a new subscription, resource group, workspace or region, make sure that you run the `configuration.ipynb` notebook again. Changing config.json directly will only work if the workspace already exists in the specified resource group under the specified subscription.
4) If you want to change the region, please change the workspace, resource group or subscription. `Workspace.create` will not create or update a workspace if it already exists, even if the region specified is different.
## Numpy import fails
Check the tensorflow version in the automated ml conda environment. Supported versions are < 1.13. Uninstall tensorflow from the environment if version is >= 1.13 ## Sample notebook fails
You may check the version of tensorflow and uninstall as follows If a sample notebook fails with an error that property, method or library does not exist:
1) start a command shell, activate conda environment where automated ml packages are installed 1) Check that you have selected correct kernel in jupyter notebook. The kernel is displayed in the top right of the notebook page. It can be changed using the `Kernel | Change Kernel` menu option. For Azure Notebooks, it should be `Python 3.6`. For local conda environments, it should be the conda envioronment name that you specified in automl_setup. The default is azure_automl. Note that the kernel is saved as part of the notebook. So, if you switch to a new conda environment, you will have to select the new kernel in the notebook.
2) enter `pip freeze` and look for `tensorflow` , if found, the version listed should be < 1.13 2) Check that the notebook is for the SDK version that you are using. You can check the SDK version by executing `azureml.core.VERSION` in a jupyter notebook cell. You can download previous version of the sample notebooks from GitHub by clicking the `Branch` button, selecting the `Tags` tab and then selecting the version.
3) If the listed version is a not a supported version, `pip uninstall tensorflow` in the command shell and enter y for confirmation.
## Numpy import fails on Windows
## Remote run: DsvmCompute.create fails Some Windows environments see an error loading numpy with the latest Python version 3.6.8. If you see this issue, try with Python version 3.6.7.
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. ## Numpy import fails
2) `The requested VM size xxxxx is not available in the current region.` You can select a different region or vm_size. Check the tensorflow version in the automated ml conda environment. Supported versions are < 1.13. Uninstall tensorflow from the environment if version is >= 1.13
You may check the version of tensorflow and uninstall as follows
## Remote run: Unable to establish SSH connection 1) start a command shell, activate conda environment where automated ml packages are installed
Automated ML uses the SSH protocol to communicate with remote DSVMs. This defaults to port 22. Possible causes for this error are: 2) enter `pip freeze` and look for `tensorflow` , if found, the version listed should be < 1.13
1) The DSVM is not ready for SSH connections. When DSVM creation completes, the DSVM might still not be ready to acceept SSH connections. The sample notebooks have a one minute delay to allow for this. 3) If the listed version is a not a supported version, `pip uninstall tensorflow` in the command shell and enter y for confirmation.
2) Your Azure Subscription may restrict the IP address ranges that can access the DSVM on port 22. You can check this in the Azure Portal by selecting the Virtual Machine and then clicking Networking. The Virtual Machine name is the name that you provided in the notebook plus 10 alpha numeric characters to make the name unique. The Inbound Port Rules define what can access the VM on specific ports. Note that there is a priority priority order. So, a Deny entry with a low priority number will override a Allow entry with a higher priority number.
## Remote run: DsvmCompute.create fails
## Remote run: setup iteration 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:
This is often an issue with the `get_data` method. 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) Check that the `get_data` method is valid by running it locally. 2) `The requested VM size xxxxx is not available in the current region.` You can select a different region or vm_size.
2) Make sure that `get_data` isn't referring to any local files. `get_data` is executed on the remote DSVM. So, it doesn't have direct access to local data files. Instead you can store the data files with DataStore. See [auto-ml-remote-execution-with-datastore.ipynb](remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb)
3) You can get to the error log for the setup iteration by clicking the `Click here to see the run in Azure portal` link, click `Back to Experiment`, click on the highest run number and then click on Logs. ## Remote run: Unable to establish SSH connection
Automated ML uses the SSH protocol to communicate with remote DSVMs. This defaults to port 22. Possible causes for this error are:
## Remote run: disk full 1) The DSVM is not ready for SSH connections. When DSVM creation completes, the DSVM might still not be ready to acceept SSH connections. The sample notebooks have a one minute delay to allow for this.
Automated ML creates files under /tmp/azureml_runs for each iteration that it runs. It creates a folder with the iteration id. For example: AutoML_9a038a18-77cc-48f1-80fb-65abdbc33abe_93. Under this, there is a azureml-logs folder, which contains logs. If you run too many iterations on the same DSVM, these files can fill the disk. 2) Your Azure Subscription may restrict the IP address ranges that can access the DSVM on port 22. You can check this in the Azure Portal by selecting the Virtual Machine and then clicking Networking. The Virtual Machine name is the name that you provided in the notebook plus 10 alpha numeric characters to make the name unique. The Inbound Port Rules define what can access the VM on specific ports. Note that there is a priority priority order. So, a Deny entry with a low priority number will override a Allow entry with a higher priority number.
You can delete the files under /tmp/azureml_runs or just delete the VM and create a new one.
If your get_data downloads files, make sure the delete them or they can use disk space as well. ## Remote run: setup iteration fails
When using DataStore, it is good to specify an absolute path for the files so that they are downloaded just once. If you specify a relative path, it will download a file for each iteration. This is often an issue with the `get_data` method.
1) Check that the `get_data` method is valid by running it locally.
## Remote run: Iterations fail and the log contains "MemoryError" 2) Make sure that `get_data` isn't referring to any local files. `get_data` is executed on the remote DSVM. So, it doesn't have direct access to local data files. Instead you can store the data files with DataStore. See [auto-ml-remote-execution-with-datastore.ipynb](remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb)
This can be caused by insufficient memory on the DSVM. Automated ML loads all training data into memory. So, the available memory should be more than the training data size. 3) You can get to the error log for the setup iteration by clicking the `Click here to see the run in Azure portal` link, click `Back to Experiment`, click on the highest run number and then click on Logs.
If you are using a remote DSVM, memory is needed for each concurrent iteration. The max_concurrent_iterations setting specifies the maximum concurrent iterations. For example, if the training data size is 8Gb and max_concurrent_iterations is set to 10, the minimum memory required is at least 80Gb.
To resolve this issue, allocate a DSVM with more memory or reduce the value specified for max_concurrent_iterations. ## Remote run: disk full
Automated ML creates files under /tmp/azureml_runs for each iteration that it runs. It creates a folder with the iteration id. For example: AutoML_9a038a18-77cc-48f1-80fb-65abdbc33abe_93. Under this, there is a azureml-logs folder, which contains logs. If you run too many iterations on the same DSVM, these files can fill the disk.
## Remote run: Iterations show as "Not Responding" in the RunDetails widget. You can delete the files under /tmp/azureml_runs or just delete the VM and create a new one.
This can be caused by too many concurrent iterations for a remote DSVM. Each concurrent iteration usually takes 100% of a core when it is running. Some iterations can use multiple cores. So, the max_concurrent_iterations setting should always be less than the number of cores of the DSVM. If your get_data downloads files, make sure the delete them or they can use disk space as well.
To resolve this issue, try reducing the value specified for the max_concurrent_iterations setting. When using DataStore, it is good to specify an absolute path for the files so that they are downloaded just once. If you specify a relative path, it will download a file for each iteration.
## Remote run: Iterations fail and the log contains "MemoryError"
This can be caused by insufficient memory on the DSVM. Automated ML loads all training data into memory. So, the available memory should be more than the training data size.
If you are using a remote DSVM, memory is needed for each concurrent iteration. The max_concurrent_iterations setting specifies the maximum concurrent iterations. For example, if the training data size is 8Gb and max_concurrent_iterations is set to 10, the minimum memory required is at least 80Gb.
To resolve this issue, allocate a DSVM with more memory or reduce the value specified for max_concurrent_iterations.
## Remote run: Iterations show as "Not Responding" in the RunDetails widget.
This can be caused by too many concurrent iterations for a remote DSVM. Each concurrent iteration usually takes 100% of a core when it is running. Some iterations can use multiple cores. So, the max_concurrent_iterations setting should always be less than the number of cores of the DSVM.
To resolve this issue, try reducing the value specified for the max_concurrent_iterations setting.

View File

@@ -1,22 +1,27 @@
name: azure_automl 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 - pip
- 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.16.0,<=1.16.2
- cython - cython
- urllib3<1.24 - urllib3<1.24
- scipy>=1.0.0,<=1.1.0 - scipy>=1.0.0,<=1.1.0
- scikit-learn>=0.19.0,<=0.20.3 - scikit-learn>=0.19.0,<=0.20.3
- pandas>=0.22.0,<=0.23.4 - pandas>=0.22.0,<=0.23.4
- py-xgboost<=0.80 - py-xgboost<=0.80
- pyarrow>=0.11.0
- pip: - conda-forge::fbprophet==0.5
# Required packages for AzureML execution, history, and data preparation.
- azureml-sdk[automl,explain] - pip:
- azureml-widgets # Required packages for AzureML execution, history, and data preparation.
- pandas_ml - azureml-defaults
- azureml-train-automl
- azureml-widgets
- azureml-explain-model
- azureml-contrib-interpret
- pandas_ml

View File

@@ -0,0 +1,28 @@
name: azure_automl
dependencies:
# The python interpreter version.
# Currently Azure ML only supports 3.5.2 and later.
- pip
- nomkl
- python>=3.5.2,<3.6.8
- nb_conda
- matplotlib==2.1.0
- numpy>=1.16.0,<=1.16.2
- cython
- urllib3<1.24
- scipy>=1.0.0,<=1.1.0
- scikit-learn>=0.19.0,<=0.20.3
- pandas>=0.22.0,<0.23.0
- py-xgboost<=0.80
- pyarrow>=0.11.0
- conda-forge::fbprophet==0.5
- pip:
# Required packages for AzureML execution, history, and data preparation.
- azureml-defaults
- azureml-train-automl
- azureml-widgets
- azureml-explain-model
- azureml-contrib-interpret
- pandas_ml

View File

@@ -1,62 +1,62 @@
@echo off @echo off
set conda_env_name=%1 set conda_env_name=%1
set automl_env_file=%2 set automl_env_file=%2
set options=%3 set options=%3
set PIP_NO_WARN_SCRIPT_LOCATION=0 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"
IF NOT EXIST %automl_env_file% GOTO YmlMissing IF NOT EXIST %automl_env_file% GOTO YmlMissing
IF "%CONDA_EXE%"=="" GOTO CondaMissing IF "%CONDA_EXE%"=="" GOTO CondaMissing
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 azureml-sdk[automl,notebooks,explain] in existing conda environment %conda_env_name%
call pip install --upgrade azureml-sdk[automl,notebooks,explain] call pip install --upgrade azureml-sdk[automl,notebooks,explain]
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%
) )
call conda activate %conda_env_name% 2>nul: call conda activate %conda_env_name% 2>nul:
if errorlevel 1 goto ErrorExit if errorlevel 1 goto ErrorExit
call python -m ipykernel install --user --name %conda_env_name% --display-name "Python (%conda_env_name%)" 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 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. REM Removing the old user install so that the notebooks will use the latest widget.
call jupyter nbextension uninstall --user --py azureml.widgets call jupyter nbextension uninstall --user --py azureml.widgets
echo. echo.
echo. echo.
echo *************************************** echo ***************************************
echo * AutoML setup completed successfully * echo * AutoML setup completed successfully *
echo *************************************** echo ***************************************
IF NOT "%options%"=="nolaunch" ( IF NOT "%options%"=="nolaunch" (
echo. echo.
echo Starting jupyter notebook - please run the configuration notebook echo Starting jupyter notebook - please run the configuration notebook
echo. echo.
jupyter notebook --log-level=50 --notebook-dir='..\..' jupyter notebook --log-level=50 --notebook-dir='..\..'
) )
goto End goto End
:CondaMissing :CondaMissing
echo Please run this script from an Anaconda Prompt window. echo Please run this script from an Anaconda Prompt window.
echo You can start an Anaconda Prompt window by echo You can start an Anaconda Prompt window by
echo typing Anaconda Prompt on the Start menu. echo typing Anaconda Prompt on the Start menu.
echo If you don't see the Anaconda Prompt app, install Miniconda. 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 If you are running an older version of Miniconda or Anaconda,
echo you can upgrade using the command: conda update conda echo you can upgrade using the command: conda update conda
goto End goto End
:YmlMissing :YmlMissing
echo File %automl_env_file% not found. echo File %automl_env_file% not found.
:ErrorExit :ErrorExit
echo Install failed echo Install failed
:End :End

View File

@@ -1,52 +1,52 @@
#!/bin/bash #!/bin/bash
CONDA_ENV_NAME=$1 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
if [ "$CONDA_ENV_NAME" == "" ] if [ "$CONDA_ENV_NAME" == "" ]
then then
CONDA_ENV_NAME="azure_automl" CONDA_ENV_NAME="azure_automl"
fi fi
if [ "$AUTOML_ENV_FILE" == "" ] if [ "$AUTOML_ENV_FILE" == "" ]
then then
AUTOML_ENV_FILE="automl_env.yml" AUTOML_ENV_FILE="automl_env.yml"
fi fi
if [ ! -f $AUTOML_ENV_FILE ]; then if [ ! -f $AUTOML_ENV_FILE ]; then
echo "File $AUTOML_ENV_FILE not found" echo "File $AUTOML_ENV_FILE not found"
exit 1 exit 1
fi fi
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 azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME
pip install --upgrade azureml-sdk[automl,notebooks,explain] && pip install --upgrade azureml-sdk[automl,notebooks,explain] &&
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 &&
source activate $CONDA_ENV_NAME && source activate $CONDA_ENV_NAME &&
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($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 && jupyter nbextension uninstall --user --py azureml.widgets &&
echo "" && echo "" &&
echo "" && echo "" &&
echo "***************************************" && echo "***************************************" &&
echo "* AutoML setup completed successfully *" && echo "* AutoML setup completed successfully *" &&
echo "***************************************" && echo "***************************************" &&
if [ "$OPTIONS" != "nolaunch" ] if [ "$OPTIONS" != "nolaunch" ]
then then
echo "" && echo "" &&
echo "Starting jupyter notebook - please run the configuration notebook" && echo "Starting jupyter notebook - please run the configuration notebook" &&
echo "" && echo "" &&
jupyter notebook --log-level=50 --notebook-dir '../..' jupyter notebook --log-level=50 --notebook-dir '../..'
fi fi
fi fi
if [ $? -gt 0 ] if [ $? -gt 0 ]
then then
echo "Installation failed" echo "Installation failed"
fi fi

View File

@@ -1,54 +1,54 @@
#!/bin/bash #!/bin/bash
CONDA_ENV_NAME=$1 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
if [ "$CONDA_ENV_NAME" == "" ] if [ "$CONDA_ENV_NAME" == "" ]
then then
CONDA_ENV_NAME="azure_automl" CONDA_ENV_NAME="azure_automl"
fi fi
if [ "$AUTOML_ENV_FILE" == "" ] if [ "$AUTOML_ENV_FILE" == "" ]
then then
AUTOML_ENV_FILE="automl_env_mac.yml" AUTOML_ENV_FILE="automl_env_mac.yml"
fi fi
if [ ! -f $AUTOML_ENV_FILE ]; then if [ ! -f $AUTOML_ENV_FILE ]; then
echo "File $AUTOML_ENV_FILE not found" echo "File $AUTOML_ENV_FILE not found"
exit 1 exit 1
fi fi
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 azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME
pip install --upgrade azureml-sdk[automl,notebooks,explain] && pip install --upgrade azureml-sdk[automl,notebooks,explain] &&
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 &&
source activate $CONDA_ENV_NAME && source activate $CONDA_ENV_NAME &&
conda install lightgbm -c conda-forge -y && conda install lightgbm -c conda-forge -y &&
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($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 && jupyter nbextension uninstall --user --py azureml.widgets &&
echo "" && echo "" &&
echo "" && echo "" &&
echo "***************************************" && echo "***************************************" &&
echo "* AutoML setup completed successfully *" && echo "* AutoML setup completed successfully *" &&
echo "***************************************" && echo "***************************************" &&
if [ "$OPTIONS" != "nolaunch" ] if [ "$OPTIONS" != "nolaunch" ]
then then
echo "" && echo "" &&
echo "Starting jupyter notebook - please run the configuration notebook" && echo "Starting jupyter notebook - please run the configuration notebook" &&
echo "" && echo "" &&
jupyter notebook --log-level=50 --notebook-dir '../..' jupyter notebook --log-level=50 --notebook-dir '../..'
fi fi
fi fi
if [ $? -gt 0 ] if [ $? -gt 0 ]
then then
echo "Installation failed" echo "Installation failed"
fi fi

View File

@@ -1,8 +1,11 @@
name: auto-ml-classification-bank-marketing name: auto-ml-classification-bank-marketing
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-defaults
- matplotlib - azureml-explain-model
- pandas_ml - azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml

View File

@@ -1,8 +1,11 @@
name: auto-ml-classification-credit-card-fraud name: auto-ml-classification-credit-card-fraud
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-defaults
- matplotlib - azureml-explain-model
- pandas_ml - azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml

View File

@@ -1,510 +1,479 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-deployment/auto-ml-classification-with-deployment.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Classification with Deployment**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Train](#Train)\n",
"source": [ "1. [Deploy](#Deploy)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Test](#Test)"
"\n", ]
"Licensed under the MIT License." },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Introduction\n",
"source": [ "\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-deployment/auto-ml-classification-with-deployment.png)" "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",
"cell_type": "markdown" "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
}, "\n",
{ "In this notebook you will learn how to:\n",
"metadata": {}, "1. Create an experiment using an existing workspace.\n",
"source": [ "2. Configure AutoML using `AutoMLConfig`.\n",
"# Automated Machine Learning\n", "3. Train the model using local compute.\n",
"_**Classification with Deployment**_\n", "4. Explore the results.\n",
"\n", "5. Register the model.\n",
"## Contents\n", "6. Create a container image.\n",
"1. [Introduction](#Introduction)\n", "7. Create an Azure Container Instance (ACI) service.\n",
"1. [Setup](#Setup)\n", "8. Test the ACI service."
"1. [Train](#Train)\n", ]
"1. [Deploy](#Deploy)\n", },
"1. [Test](#Test)" {
], "cell_type": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "## Setup\n",
"metadata": {}, "\n",
"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."
"## 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", "cell_type": "code",
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "execution_count": null,
"\n", "metadata": {},
"In this notebook you will learn how to:\n", "outputs": [],
"1. Create an experiment using an existing workspace.\n", "source": [
"2. Configure AutoML using `AutoMLConfig`.\n", "import json\n",
"3. Train the model using local compute.\n", "import logging\n",
"4. Explore the results.\n", "\n",
"5. Register the model.\n", "from matplotlib import pyplot as plt\n",
"6. Create a container image.\n", "import numpy as np\n",
"7. Create an Azure Container Instance (ACI) service.\n", "import pandas as pd\n",
"8. Test the ACI service." "from sklearn import datasets\n",
], "\n",
"cell_type": "markdown" "import azureml.core\n",
}, "from azureml.core.experiment import Experiment\n",
{ "from azureml.core.workspace import Workspace\n",
"metadata": {}, "from azureml.train.automl import AutoMLConfig\n",
"source": [ "from azureml.train.automl.run import AutoMLRun"
"## 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",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "ws = Workspace.from_config()\n",
"execution_count": null, "\n",
"source": [ "# choose a name for experiment\n",
"import json\n", "experiment_name = 'automl-classification-deployment'\n",
"import logging\n", "\n",
"\n", "experiment=Experiment(ws, experiment_name)\n",
"from matplotlib import pyplot as plt\n", "\n",
"import numpy as np\n", "output = {}\n",
"import pandas as pd\n", "output['SDK version'] = azureml.core.VERSION\n",
"from sklearn import datasets\n", "output['Subscription ID'] = ws.subscription_id\n",
"\n", "output['Workspace'] = ws.name\n",
"import azureml.core\n", "output['Resource Group'] = ws.resource_group\n",
"from azureml.core.experiment import Experiment\n", "output['Location'] = ws.location\n",
"from azureml.core.workspace import Workspace\n", "output['Experiment Name'] = experiment.name\n",
"from azureml.train.automl import AutoMLConfig\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.train.automl.run import AutoMLRun" "outputDf = pd.DataFrame(data = output, index = [''])\n",
], "outputDf.T"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "## Train\n",
"ws = Workspace.from_config()\n", "\n",
"\n", "Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
"# choose a name for experiment\n", "\n",
"experiment_name = 'automl-classification-deployment'\n", "|Property|Description|\n",
"# project folder\n", "|-|-|\n",
"project_folder = './sample_projects/automl-classification-deployment'\n", "|**task**|classification or regression|\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",
"experiment=Experiment(ws, experiment_name)\n", "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
"\n", "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"output = {}\n", "|**n_cross_validations**|Number of cross validation splits.|\n",
"output['SDK version'] = azureml.core.VERSION\n", "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"output['Subscription ID'] = ws.subscription_id\n", "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|"
"output['Workspace'] = ws.name\n", ]
"output['Resource Group'] = ws.resource_group\n", },
"output['Location'] = ws.location\n", {
"output['Project Directory'] = project_folder\n", "cell_type": "code",
"output['Experiment Name'] = experiment.name\n", "execution_count": null,
"pd.set_option('display.max_colwidth', -1)\n", "metadata": {},
"outputDf = pd.DataFrame(data = output, index = [''])\n", "outputs": [],
"outputDf.T" "source": [
], "digits = datasets.load_digits()\n",
"cell_type": "code" "X_train = digits.data[10:,:]\n",
}, "y_train = digits.target[10:]\n",
{ "\n",
"metadata": {}, "automl_config = AutoMLConfig(task = 'classification',\n",
"source": [ " name = experiment_name,\n",
"## Train\n", " debug_log = 'automl_errors.log',\n",
"\n", " primary_metric = 'AUC_weighted',\n",
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n", " iteration_timeout_minutes = 20,\n",
"\n", " iterations = 10,\n",
"|Property|Description|\n", " verbosity = logging.INFO,\n",
"|-|-|\n", " X = X_train, \n",
"|**task**|classification or regression|\n", " y = y_train)"
"|**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", "cell_type": "markdown",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "metadata": {},
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "source": [
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|" "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": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"digits = datasets.load_digits()\n", "source": [
"X_train = digits.data[10:,:]\n", "local_run = experiment.submit(automl_config, show_output = True)"
"y_train = digits.target[10:]\n", ]
"\n", },
"automl_config = AutoMLConfig(task = 'classification',\n", {
" name = experiment_name,\n", "cell_type": "code",
" debug_log = 'automl_errors.log',\n", "execution_count": null,
" primary_metric = 'AUC_weighted',\n", "metadata": {},
" iteration_timeout_minutes = 20,\n", "outputs": [],
" iterations = 10,\n", "source": [
" verbosity = logging.INFO,\n", "local_run"
" X = X_train, \n", ]
" y = y_train,\n", },
" path = project_folder)" {
], "cell_type": "markdown",
"cell_type": "code" "metadata": {},
}, "source": [
{ "## Deploy\n",
"metadata": {}, "\n",
"source": [ "### Retrieve the Best Model\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.\n", "\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "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": "markdown" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"local_run = experiment.submit(automl_config, show_output = True)" "best_run, fitted_model = local_run.get_output()"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"execution_count": null, "### Register the Fitted Model for Deployment\n",
"source": [ "If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered."
"local_run" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"## Deploy\n", "source": [
"\n", "description = 'AutoML Model'\n",
"### Retrieve the Best Model\n", "tags = None\n",
"\n", "model = local_run.register_model(description = description, tags = tags)\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*." "\n",
], "print(local_run.model_id) # This will be written to the script file later in the notebook."
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "### Create Scoring Script"
"best_run, fitted_model = local_run.get_output()" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"### Register the Fitted Model for Deployment\n", "source": [
"If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered." "%%writefile score.py\n",
], "import pickle\n",
"cell_type": "markdown" "import json\n",
}, "import numpy\n",
{ "import azureml.train.automl\n",
"metadata": {}, "from sklearn.externals import joblib\n",
"outputs": [], "from azureml.core.model import Model\n",
"execution_count": null, "\n",
"source": [ "\n",
"description = 'AutoML Model'\n", "def init():\n",
"tags = None\n", " global model\n",
"model = local_run.register_model(description = description, tags = tags)\n", " model_path = Model.get_model_path(model_name = '<<modelid>>') # this name is model.id of model that we want to deploy\n",
"\n", " # deserialize the model file back into a sklearn model\n",
"print(local_run.model_id) # This will be written to the script file later in the notebook." " model = joblib.load(model_path)\n",
], "\n",
"cell_type": "code" "def run(rawdata):\n",
}, " try:\n",
{ " data = json.loads(rawdata)['data']\n",
"metadata": {}, " data = numpy.array(data)\n",
"source": [ " result = model.predict(data)\n",
"### Create Scoring Script" " except Exception as e:\n",
], " result = str(e)\n",
"cell_type": "markdown" " return json.dumps({\"error\": result})\n",
}, " return json.dumps({\"result\":result.tolist()})"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "markdown",
"source": [ "metadata": {},
"%%writefile score.py\n", "source": [
"import pickle\n", "### Create a YAML File for the Environment"
"import json\n", ]
"import numpy\n", },
"import azureml.train.automl\n", {
"from sklearn.externals import joblib\n", "cell_type": "markdown",
"from azureml.core.model import Model\n", "metadata": {},
"\n", "source": [
"\n", "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."
"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", "cell_type": "code",
" model = joblib.load(model_path)\n", "execution_count": null,
"\n", "metadata": {},
"def run(rawdata):\n", "outputs": [],
" try:\n", "source": [
" data = json.loads(rawdata)['data']\n", "experiment = Experiment(ws, experiment_name)\n",
" data = numpy.array(data)\n", "ml_run = AutoMLRun(experiment = experiment, run_id = local_run.id)"
" result = model.predict(data)\n", ]
" except Exception as e:\n", },
" result = str(e)\n", {
" return json.dumps({\"error\": result})\n", "cell_type": "code",
" return json.dumps({\"result\":result.tolist()})" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "dependencies = ml_run.get_run_sdk_dependencies(iteration = 7)"
"metadata": {}, ]
"source": [ },
"### Create a YAML File for the Environment" {
], "cell_type": "code",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "for p in ['azureml-train-automl', 'azureml-core']:\n",
"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." " print('{}\\t{}'.format(p, dependencies[p]))"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"experiment = Experiment(ws, experiment_name)\n", "from azureml.core.conda_dependencies import CondaDependencies\n",
"ml_run = AutoMLRun(experiment = experiment, run_id = local_run.id)" "\n",
], "myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn','py-xgboost<=0.80'],\n",
"cell_type": "code" " pip_packages=['azureml-defaults','azureml-train-automl'])\n",
}, "\n",
{ "conda_env_file_name = 'myenv.yml'\n",
"metadata": {}, "myenv.save_to_file('.', conda_env_file_name)"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"dependencies = ml_run.get_run_sdk_dependencies(iteration = 7)" "cell_type": "code",
], "execution_count": null,
"cell_type": "code" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "# Substitute the actual version number in the environment file.\n",
"outputs": [], "# This is not strictly needed in this notebook because the model should have been generated using the current SDK version.\n",
"execution_count": null, "# However, we include this in case this code is used on an experiment from a previous SDK version.\n",
"source": [ "\n",
"for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n", "with open(conda_env_file_name, 'r') as cefr:\n",
" print('{}\\t{}'.format(p, dependencies[p]))" " content = cefr.read()\n",
], "\n",
"cell_type": "code" "with open(conda_env_file_name, 'w') as cefw:\n",
}, " cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-train-automl']))\n",
{ "\n",
"metadata": {}, "# Substitute the actual model id in the script file.\n",
"outputs": [], "\n",
"execution_count": null, "script_file_name = 'score.py'\n",
"source": [ "\n",
"from azureml.core.conda_dependencies import CondaDependencies\n", "with open(script_file_name, 'r') as cefr:\n",
"\n", " content = cefr.read()\n",
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn','py-xgboost<=0.80'],\n", "\n",
" pip_packages=['azureml-sdk[automl]'])\n", "with open(script_file_name, 'w') as cefw:\n",
"\n", " cefw.write(content.replace('<<modelid>>', local_run.model_id))"
"conda_env_file_name = 'myenv.yml'\n", ]
"myenv.save_to_file('.', conda_env_file_name)" },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "### Deploy the model as a Web Service on Azure Container Instance\n",
"outputs": [], "\n",
"execution_count": null, "Create the configuration needed for deploying the model as a web service service."
"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", "cell_type": "code",
"\n", "execution_count": null,
"with open(conda_env_file_name, 'r') as cefr:\n", "metadata": {},
" content = cefr.read()\n", "outputs": [],
"\n", "source": [
"with open(conda_env_file_name, 'w') as cefw:\n", "from azureml.core.model import InferenceConfig\n",
" cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n", "from azureml.core.webservice import AciWebservice\n",
"\n", "\n",
"# Substitute the actual model id in the script file.\n", "inference_config = InferenceConfig(runtime = \"python\", \n",
"\n", " entry_script = script_file_name,\n",
"script_file_name = 'score.py'\n", " conda_file = conda_env_file_name)\n",
"\n", "\n",
"with open(script_file_name, 'r') as cefr:\n", "aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
" content = cefr.read()\n", " memory_gb = 1, \n",
"\n", " tags = {'area': \"digits\", 'type': \"automl_classification\"}, \n",
"with open(script_file_name, 'w') as cefw:\n", " description = 'sample service for Automl Classification')"
" cefw.write(content.replace('<<modelid>>', local_run.model_id))" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"### Create a Container Image" "source": [
], "from azureml.core.webservice import Webservice\n",
"cell_type": "markdown" "from azureml.core.model import Model\n",
}, "\n",
{ "aci_service_name = 'automl-sample-01'\n",
"metadata": {}, "print(aci_service_name)\n",
"outputs": [], "aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig)\n",
"execution_count": null, "aci_service.wait_for_deployment(True)\n",
"source": [ "print(aci_service.state)"
"from azureml.core.image import Image, ContainerImage\n", ]
"\n", },
"image_config = ContainerImage.image_configuration(runtime= \"python\",\n", {
" execution_script = script_file_name,\n", "cell_type": "markdown",
" conda_file = conda_env_file_name,\n", "metadata": {},
" tags = {'area': \"digits\", 'type': \"automl_classification\"},\n", "source": [
" description = \"Image for automl classification sample\")\n", "### Get the logs from service deployment"
"\n", ]
"image = Image.create(name = \"automlsampleimage\",\n", },
" # this is the model object \n", {
" models = [model],\n", "cell_type": "code",
" image_config = image_config, \n", "execution_count": null,
" workspace = ws)\n", "metadata": {},
"\n", "outputs": [],
"image.wait_for_creation(show_output = True)\n", "source": [
"\n", "if aci_service.state != 'Healthy':\n",
"if image.creation_state == 'Failed':\n", " # run this command for debugging.\n",
" print(\"Image build log at: \" + image.image_build_log_uri)" " print(aci_service.get_logs())"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"### Deploy the Image as a Web Service on Azure Container Instance" "### Delete a Web Service"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"from azureml.core.webservice import AciWebservice\n", "#aci_service.delete()"
"\n", ]
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n", },
" memory_gb = 1, \n", {
" tags = {'area': \"digits\", 'type': \"automl_classification\"}, \n", "cell_type": "markdown",
" description = 'sample service for Automl Classification')" "metadata": {},
], "source": [
"cell_type": "code" "## Test"
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "code",
"execution_count": null, "execution_count": null,
"source": [ "metadata": {},
"from azureml.core.webservice import Webservice\n", "outputs": [],
"\n", "source": [
"aci_service_name = 'automl-sample-01'\n", "#Randomly select digits and test\n",
"print(aci_service_name)\n", "digits = datasets.load_digits()\n",
"aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n", "X_test = digits.data[:10, :]\n",
" image = image,\n", "y_test = digits.target[:10]\n",
" name = aci_service_name,\n", "images = digits.images[:10]\n",
" workspace = ws)\n", "\n",
"aci_service.wait_for_deployment(True)\n", "for index in np.random.choice(len(y_test), 3, replace = False):\n",
"print(aci_service.state)" " print(index)\n",
], " test_sample = json.dumps({'data':X_test[index:index + 1].tolist()})\n",
"cell_type": "code" " predicted = aci_service.run(input_data = test_sample)\n",
}, " label = y_test[index]\n",
{ " predictedDict = json.loads(predicted)\n",
"metadata": {}, " title = \"Label value = %d Predicted value = %s \" % ( label,predictedDict['result'][0])\n",
"source": [ " fig = plt.figure(1, figsize = (3,3))\n",
"### Delete a Web Service" " ax1 = fig.add_axes((0,0,.8,.8))\n",
], " ax1.set_title(title)\n",
"cell_type": "markdown" " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
}, " plt.show()"
{ ]
"metadata": {}, }
"outputs": [], ],
"execution_count": null, "metadata": {
"source": [ "authors": [
"#aci_service.delete()" {
], "name": "savitam"
"cell_type": "code" }
}, ],
{ "kernelspec": {
"metadata": {}, "display_name": "Python 3.6",
"source": [ "language": "python",
"### Get Logs from a Deployed Web Service" "name": "python36"
], },
"cell_type": "markdown" "language_info": {
}, "codemirror_mode": {
{ "name": "ipython",
"metadata": {}, "version": 3
"outputs": [], },
"execution_count": null, "file_extension": ".py",
"source": [ "mimetype": "text/x-python",
"#aci_service.get_logs()" "name": "python",
], "nbconvert_exporter": "python",
"cell_type": "code" "pygments_lexer": "ipython3",
}, "version": "3.6.6"
{ }
"metadata": {}, },
"source": [ "nbformat": 4,
"## Test" "nbformat_minor": 2
],
"cell_type": "markdown"
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"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()"
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-classification-with-deployment name: auto-ml-classification-with-deployment
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,381 +1,375 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-onnx/auto-ml-classification-with-onnx.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Classification with Local Compute**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Results](#Results)\n",
"\n", "\n"
"Licensed under the MIT License." ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "## Introduction\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-onnx/auto-ml-classification-with-onnx.png)" "\n",
], "In this example we use the scikit-learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) to showcase how you can use AutoML for a simple classification problem.\n",
"cell_type": "markdown" "\n",
}, "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
{ "\n",
"metadata": {}, "Please find the ONNX related documentations [here](https://github.com/onnx/onnx).\n",
"source": [ "\n",
"# Automated Machine Learning\n", "In this notebook you will learn how to:\n",
"_**Classification with Local Compute**_\n", "1. Create an `Experiment` in an existing `Workspace`.\n",
"\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"## Contents\n", "3. Train the model using local compute with ONNX compatible config on.\n",
"1. [Introduction](#Introduction)\n", "4. Explore the results and save the ONNX model.\n",
"1. [Setup](#Setup)\n", "5. Inference with the ONNX model."
"1. [Data](#Data)\n", ]
"1. [Train](#Train)\n", },
"1. [Results](#Results)\n", {
"1. [Test](#Test)\n", "cell_type": "markdown",
"\n" "metadata": {},
], "source": [
"cell_type": "markdown" "## 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."
"metadata": {}, ]
"source": [ },
"## Introduction\n", {
"\n", "cell_type": "code",
"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", "execution_count": null,
"\n", "metadata": {},
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "outputs": [],
"\n", "source": [
"Please find the ONNX related documentations [here](https://github.com/onnx/onnx).\n", "import logging\n",
"\n", "\n",
"In this notebook you will learn how to:\n", "from matplotlib import pyplot as plt\n",
"1. Create an `Experiment` in an existing `Workspace`.\n", "import numpy as np\n",
"2. Configure AutoML using `AutoMLConfig`.\n", "import pandas as pd\n",
"3. Train the model using local compute with ONNX compatible config on.\n", "from sklearn import datasets\n",
"4. Explore the results and save the ONNX model." "from sklearn.model_selection import train_test_split\n",
], "\n",
"cell_type": "markdown" "import azureml.core\n",
}, "from azureml.core.experiment import Experiment\n",
{ "from azureml.core.workspace import Workspace\n",
"metadata": {}, "from azureml.train.automl import AutoMLConfig, constants"
"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,
"cell_type": "markdown" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "ws = Workspace.from_config()\n",
"outputs": [], "\n",
"execution_count": null, "# Choose a name for the experiment.\n",
"source": [ "experiment_name = 'automl-classification-onnx'\n",
"import logging\n", "\n",
"\n", "experiment = Experiment(ws, experiment_name)\n",
"from matplotlib import pyplot as plt\n", "\n",
"import numpy as np\n", "output = {}\n",
"import pandas as pd\n", "output['SDK version'] = azureml.core.VERSION\n",
"from sklearn import datasets\n", "output['Subscription ID'] = ws.subscription_id\n",
"from sklearn.model_selection import train_test_split\n", "output['Workspace Name'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"import azureml.core\n", "output['Location'] = ws.location\n",
"from azureml.core.experiment import Experiment\n", "output['Experiment Name'] = experiment.name\n",
"from azureml.core.workspace import Workspace\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.train.automl import AutoMLConfig, constants" "outputDf = pd.DataFrame(data = output, index = [''])\n",
], "outputDf.T"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "## Data\n",
"ws = Workspace.from_config()\n", "\n",
"\n", "This uses scikit-learn's [load_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) method."
"# 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", "cell_type": "code",
"experiment = Experiment(ws, experiment_name)\n", "execution_count": null,
"\n", "metadata": {},
"output = {}\n", "outputs": [],
"output['SDK version'] = azureml.core.VERSION\n", "source": [
"output['Subscription ID'] = ws.subscription_id\n", "iris = datasets.load_iris()\n",
"output['Workspace Name'] = ws.name\n", "X_train, X_test, y_train, y_test = train_test_split(iris.data, \n",
"output['Resource Group'] = ws.resource_group\n", " iris.target, \n",
"output['Location'] = ws.location\n", " test_size=0.2, \n",
"output['Project Directory'] = project_folder\n", " random_state=0)"
"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": {},
"cell_type": "code" "source": [
}, "### Ensure the x_train and x_test are pandas DataFrame."
{ ]
"metadata": {}, },
"source": [ {
"## Data\n", "cell_type": "code",
"\n", "execution_count": null,
"This uses scikit-learn's [load_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) method." "metadata": {},
], "outputs": [],
"cell_type": "markdown" "source": [
}, "# 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",
"metadata": {}, "# and the prediction with the ONNX model using the inference helper.\n",
"outputs": [], "X_train = pd.DataFrame(X_train, columns=['c1', 'c2', 'c3', 'c4'])\n",
"execution_count": null, "X_test = pd.DataFrame(X_test, columns=['c1', 'c2', 'c3', 'c4'])"
"source": [ ]
"iris = datasets.load_iris()\n", },
"X_train, X_test, y_train, y_test = train_test_split(iris.data, \n", {
" iris.target, \n", "cell_type": "markdown",
" test_size=0.2, \n", "metadata": {},
" random_state=0)\n", "source": [
"\n", "## Train\n",
"\n" "\n",
], "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
"cell_type": "code" "\n",
}, "**Note:** 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",
"metadata": {}, "|Property|Description|\n",
"source": [ "|-|-|\n",
"### Ensure the x_train and x_test are pandas DataFrame." "|**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",
"cell_type": "markdown" "|**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",
"metadata": {}, "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"outputs": [], "|**enable_onnx_compatible_models**|Enable the ONNX compatible models in the experiment.|"
"execution_count": null, ]
"source": [ },
"# 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", "cell_type": "markdown",
"# and the prediction with the ONNX model using the inference helper.\n", "metadata": {},
"X_train = pd.DataFrame(X_train, columns=['c1', 'c2', 'c3', 'c4'])\n", "source": [
"X_test = pd.DataFrame(X_test, columns=['c1', 'c2', 'c3', 'c4'])" "### Set the preprocess=True, currently the InferenceHelper only supports this mode."
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"## Train with enable ONNX compatible models config on\n", "outputs": [],
"\n", "source": [
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", "automl_config = AutoMLConfig(task = 'classification',\n",
"\n", " debug_log = 'automl_errors.log',\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", " primary_metric = 'AUC_weighted',\n",
"\n", " iteration_timeout_minutes = 60,\n",
"|Property|Description|\n", " iterations = 10,\n",
"|-|-|\n", " verbosity = logging.INFO, \n",
"|**task**|classification or regression|\n", " X = X_train, \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", " y = y_train,\n",
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", " preprocess=True,\n",
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", " enable_onnx_compatible_models=True)"
"|**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": "markdown",
], "metadata": {},
"cell_type": "markdown" "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."
"metadata": {}, ]
"source": [ },
"### Set the preprocess=True, currently the InferenceHelper only supports this mode." {
], "cell_type": "code",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "local_run = experiment.submit(automl_config, show_output = True)"
"execution_count": null, ]
"source": [ },
"automl_config = AutoMLConfig(task = 'classification',\n", {
" debug_log = 'automl_errors.log',\n", "cell_type": "code",
" primary_metric = 'AUC_weighted',\n", "execution_count": null,
" iteration_timeout_minutes = 60,\n", "metadata": {},
" iterations = 10,\n", "outputs": [],
" verbosity = logging.INFO, \n", "source": [
" X = X_train, \n", "local_run"
" y = y_train,\n", ]
" preprocess=True,\n", },
" enable_onnx_compatible_models=True,\n", {
" path = project_folder)" "cell_type": "markdown",
], "metadata": {},
"cell_type": "code" "source": [
}, "## Results"
{ ]
"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", "cell_type": "markdown",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "metadata": {},
], "source": [
"cell_type": "markdown" "#### 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",
"metadata": {}, "\n",
"outputs": [], "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"execution_count": null, ]
"source": [ },
"local_run = experiment.submit(automl_config, show_output = True)" {
], "cell_type": "code",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "from azureml.widgets import RunDetails\n",
"execution_count": null, "RunDetails(local_run).show() "
"source": [ ]
"local_run" },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "### Retrieve the Best ONNX Model\n",
"source": [ "\n",
"## Results" "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",
"cell_type": "markdown" "Set the parameter return_onnx_model=True to retrieve the best ONNX model, instead of the Python model."
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"#### Widget for Monitoring Runs\n", "execution_count": null,
"\n", "metadata": {},
"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", "outputs": [],
"\n", "source": [
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "best_run, onnx_mdl = local_run.get_output(return_onnx_model=True)"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"execution_count": null, "### Save the best ONNX model"
"source": [ ]
"from azureml.widgets import RunDetails\n", },
"RunDetails(local_run).show() " {
], "cell_type": "code",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "from azureml.automl.core.onnx_convert import OnnxConverter\n",
"### Retrieve the Best ONNX Model\n", "onnx_fl_path = \"./best_model.onnx\"\n",
"\n", "OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)"
"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": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "### Predict with the ONNX model, using onnxruntime package"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "code",
"best_run, onnx_mdl = local_run.get_output(return_onnx_model=True)" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "import sys\n",
"metadata": {}, "import json\n",
"source": [ "from azureml.automl.core.onnx_convert import OnnxConvertConstants\n",
"### Save the best ONNX model" "\n",
], "if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n",
"cell_type": "markdown" " python_version_compatible = True\n",
}, "else:\n",
{ " python_version_compatible = False\n",
"metadata": {}, "\n",
"outputs": [], "try:\n",
"execution_count": null, " import onnxruntime\n",
"source": [ " from azureml.automl.core.onnx_convert import OnnxInferenceHelper \n",
"from azureml.automl.core.onnx_convert import OnnxConverter\n", " onnxrt_present = True\n",
"onnx_fl_path = \"./best_model.onnx\"\n", "except ImportError:\n",
"OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)" " onnxrt_present = False\n",
], "\n",
"cell_type": "code" "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",
"metadata": {}, " with open(res_path) as f:\n",
"source": [ " onnx_res = json.load(f)\n",
"### Predict with the ONNX model, using onnxruntime package" " return onnx_res\n",
], "\n",
"cell_type": "markdown" "if onnxrt_present and python_version_compatible: \n",
}, " mdl_bytes = onnx_mdl.SerializeToString()\n",
{ " onnx_res = get_onnx_res(best_run)\n",
"metadata": {}, "\n",
"outputs": [], " onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n",
"execution_count": null, " pred_onnx, pred_prob_onnx = onnxrt_helper.predict(X_test)\n",
"source": [ "\n",
"import sys\n", " print(pred_onnx)\n",
"import json\n", " print(pred_prob_onnx)\n",
"from azureml.automl.core.onnx_convert import OnnxConvertConstants\n", "else:\n",
"\n", " if not python_version_compatible:\n",
"if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n", " print('Please use Python version 3.6 or 3.7 to run the inference helper.') \n",
" python_version_compatible = True\n", " if not onnxrt_present:\n",
"else:\n", " print('Please install the onnxruntime package to do the prediction with ONNX model.')"
" python_version_compatible = False\n", ]
"\n", },
"try:\n", {
" import onnxruntime\n", "cell_type": "code",
" from azureml.automl.core.onnx_convert import OnnxInferenceHelper \n", "execution_count": null,
" onnxrt_present = True\n", "metadata": {},
"except ImportError:\n", "outputs": [],
" onnxrt_present = False\n", "source": []
"\n", }
"def get_onnx_res(run):\n", ],
" res_path = 'onnx_resource.json'\n", "metadata": {
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n", "authors": [
" with open(res_path) as f:\n", {
" onnx_res = json.load(f)\n", "name": "savitam"
" return onnx_res\n", }
"\n", ],
"if onnxrt_present and python_version_compatible: \n", "kernelspec": {
" mdl_bytes = onnx_mdl.SerializeToString()\n", "display_name": "Python 3.6",
" onnx_res = get_onnx_res(best_run)\n", "language": "python",
"\n", "name": "python36"
" onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n", },
" pred_onnx, pred_prob_onnx = onnxrt_helper.predict(X_test)\n", "language_info": {
"\n", "codemirror_mode": {
" print(pred_onnx)\n", "name": "ipython",
" print(pred_prob_onnx)\n", "version": 3
"else:\n", },
" if not python_version_compatible:\n", "file_extension": ".py",
" print('Please use Python version 3.6 or 3.7 to run the inference helper.') \n", "mimetype": "text/x-python",
" if not onnxrt_present:\n", "name": "python",
" print('Please install the onnxruntime package to do the prediction with ONNX model.')" "nbconvert_exporter": "python",
], "pygments_lexer": "ipython3",
"cell_type": "code" "version": "3.6.6"
}, }
{ },
"metadata": {}, "nbformat": 4,
"outputs": [], "nbformat_minor": 2
"execution_count": null,
"source": [],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,9 +1,9 @@
name: auto-ml-classification-with-onnx name: auto-ml-classification-with-onnx
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- onnxruntime - onnxruntime

View File

@@ -1,399 +1,395 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-whitelisting/auto-ml-classification-with-whitelisting.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Classification using whitelist models**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Results](#Results)\n",
"\n", "1. [Test](#Test)"
"Licensed under the MIT License." ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "## Introduction\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-whitelisting/auto-ml-classification-with-whitelisting.png)" "\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",
"cell_type": "markdown" "\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 selected list of models, see the readme.md for the models.\n",
"metadata": {}, "This trains the model exclusively on tensorflow based models.\n",
"source": [ "\n",
"# Automated Machine Learning\n", "In this notebook you will learn how to:\n",
"_**Classification using whitelist models**_\n", "1. Create an `Experiment` in an existing `Workspace`.\n",
"\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"## Contents\n", "3. Train the model on a whilelisted models using local compute. \n",
"1. [Introduction](#Introduction)\n", "4. Explore the results.\n",
"1. [Setup](#Setup)\n", "5. Test the best fitted model."
"1. [Data](#Data)\n", ]
"1. [Train](#Train)\n", },
"1. [Results](#Results)\n", {
"1. [Test](#Test)" "cell_type": "markdown",
], "metadata": {},
"cell_type": "markdown" "source": [
}, "## Setup\n",
{ "\n",
"metadata": {}, "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."
"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", "cell_type": "code",
"\n", "execution_count": null,
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "metadata": {},
"This notebooks shows how can automl can be trained on a a selected list of models,see the readme.md for the models.\n", "outputs": [],
"This trains the model exclusively on tensorflow based models.\n", "source": [
"\n", "#Note: This notebook will install tensorflow if not already installed in the enviornment..\n",
"In this notebook you will learn how to:\n", "import logging\n",
"1. Create an `Experiment` in an existing `Workspace`.\n", "\n",
"2. Configure AutoML using `AutoMLConfig`.\n", "from matplotlib import pyplot as plt\n",
"3. Train the model on a whilelisted models using local compute. \n", "import numpy as np\n",
"4. Explore the results.\n", "import pandas as pd\n",
"5. Test the best fitted model." "from sklearn import datasets\n",
], "\n",
"cell_type": "markdown" "import azureml.core\n",
}, "from azureml.core.experiment import Experiment\n",
{ "from azureml.core.workspace import Workspace\n",
"metadata": {}, "import sys\n",
"source": [ "whitelist_models=[\"LightGBM\"]\n",
"## Setup\n", "if \"3.7\" != sys.version[0:3]:\n",
"\n", " try:\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." " import tensorflow as tf1\n",
], " except ImportError:\n",
"cell_type": "markdown" " from pip._internal import main\n",
}, " main(['install', 'tensorflow>=1.10.0,<=1.12.0'])\n",
{ " logging.getLogger().setLevel(logging.ERROR)\n",
"metadata": {}, " whitelist_models=[\"TensorFlowLinearClassifier\", \"TensorFlowDNN\"]\n",
"outputs": [], "\n",
"execution_count": null, "from azureml.train.automl import AutoMLConfig"
"source": [ ]
"#Note: This notebook will install tensorflow if not already installed in the enviornment..\n", },
"import logging\n", {
"\n", "cell_type": "code",
"from matplotlib import pyplot as plt\n", "execution_count": null,
"import numpy as np\n", "metadata": {},
"import pandas as pd\n", "outputs": [],
"from sklearn import datasets\n", "source": [
"\n", "ws = Workspace.from_config()\n",
"import azureml.core\n", "\n",
"from azureml.core.experiment import Experiment\n", "# Choose a name for the experiment.\n",
"from azureml.core.workspace import Workspace\n", "experiment_name = 'automl-local-whitelist'\n",
"import sys\n", "\n",
"whitelist_models=[\"LightGBM\"]\n", "experiment = Experiment(ws, experiment_name)\n",
"if \"3.7\" != sys.version[0:3]:\n", "\n",
" try:\n", "output = {}\n",
" import tensorflow as tf1\n", "output['SDK version'] = azureml.core.VERSION\n",
" except ImportError:\n", "output['Subscription ID'] = ws.subscription_id\n",
" from pip._internal import main\n", "output['Workspace Name'] = ws.name\n",
" main(['install', 'tensorflow>=1.10.0,<=1.12.0'])\n", "output['Resource Group'] = ws.resource_group\n",
" logging.getLogger().setLevel(logging.ERROR)\n", "output['Location'] = ws.location\n",
" whitelist_models=[\"TensorFlowLinearClassifier\", \"TensorFlowDNN\"]\n", "output['Experiment Name'] = experiment.name\n",
"\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.train.automl import AutoMLConfig" "outputDf = pd.DataFrame(data = output, index = [''])\n",
], "outputDf.T"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "## Data\n",
"ws = Workspace.from_config()\n", "\n",
"\n", "This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method."
"# 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", "cell_type": "code",
"experiment = Experiment(ws, experiment_name)\n", "execution_count": null,
"\n", "metadata": {},
"output = {}\n", "outputs": [],
"output['SDK version'] = azureml.core.VERSION\n", "source": [
"output['Subscription ID'] = ws.subscription_id\n", "digits = datasets.load_digits()\n",
"output['Workspace Name'] = ws.name\n", "\n",
"output['Resource Group'] = ws.resource_group\n", "# Exclude the first 100 rows from training so that they can be used for test.\n",
"output['Location'] = ws.location\n", "X_train = digits.data[100:,:]\n",
"output['Project Directory'] = project_folder\n", "y_train = digits.target[100:]"
"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": {},
"cell_type": "code" "source": [
}, "## Train\n",
{ "\n",
"metadata": {}, "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
"source": [ "\n",
"## Data\n", "|Property|Description|\n",
"\n", "|-|-|\n",
"This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method." "|**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",
"cell_type": "markdown" "|**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",
"metadata": {}, "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"outputs": [], "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"execution_count": null, "|**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).|"
"source": [ ]
"digits = datasets.load_digits()\n", },
"\n", {
"# Exclude the first 100 rows from training so that they can be used for test.\n", "cell_type": "code",
"X_train = digits.data[100:,:]\n", "execution_count": null,
"y_train = digits.target[100:]" "metadata": {},
], "outputs": [],
"cell_type": "code" "source": [
}, "automl_config = AutoMLConfig(task = 'classification',\n",
{ " debug_log = 'automl_errors.log',\n",
"metadata": {}, " primary_metric = 'AUC_weighted',\n",
"source": [ " iteration_timeout_minutes = 60,\n",
"## Train\n", " iterations = 10,\n",
"\n", " verbosity = logging.INFO,\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", " X = X_train, \n",
"\n", " y = y_train,\n",
"|Property|Description|\n", " enable_tf=True,\n",
"|-|-|\n", " whitelist_models=whitelist_models)"
"|**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", "cell_type": "markdown",
"|**n_cross_validations**|Number of cross validation splits.|\n", "metadata": {},
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "source": [
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\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.\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", "In this example, we specify `show_output = True` to print currently running iterations to the console."
"|**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": "markdown" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "local_run = experiment.submit(automl_config, show_output = True)"
"automl_config = AutoMLConfig(task = 'classification',\n", ]
" debug_log = 'automl_errors.log',\n", },
" primary_metric = 'AUC_weighted',\n", {
" iteration_timeout_minutes = 60,\n", "cell_type": "code",
" iterations = 10,\n", "execution_count": null,
" verbosity = logging.INFO,\n", "metadata": {},
" X = X_train, \n", "outputs": [],
" y = y_train,\n", "source": [
" enable_tf=True,\n", "local_run"
" whitelist_models=whitelist_models,\n", ]
" path = project_folder)" },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Results"
"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": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "#### Widget for Monitoring Runs\n",
"metadata": {}, "\n",
"outputs": [], "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",
"execution_count": null, "\n",
"source": [ "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"local_run = experiment.submit(automl_config, show_output = True)" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "from azureml.widgets import RunDetails\n",
"local_run" "RunDetails(local_run).show() "
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Results" "\n",
], "#### Retrieve All Child Runs\n",
"cell_type": "markdown" "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"#### Widget for Monitoring Runs\n", "execution_count": null,
"\n", "metadata": {},
"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", "outputs": [],
"\n", "source": [
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "children = list(local_run.get_children())\n",
], "metricslist = {}\n",
"cell_type": "markdown" "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",
"metadata": {}, " metricslist[int(properties['iteration'])] = metrics\n",
"outputs": [], "\n",
"execution_count": null, "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"source": [ "rundata"
"from azureml.widgets import RunDetails\n", ]
"RunDetails(local_run).show() " },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "### Retrieve the Best Model\n",
"source": [ "\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 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": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "best_run, fitted_model = local_run.get_output()\n",
"source": [ "print(best_run)\n",
"children = list(local_run.get_children())\n", "print(fitted_model)"
"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", "cell_type": "markdown",
" metricslist[int(properties['iteration'])] = metrics\n", "metadata": {},
"\n", "source": [
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "#### Best Model Based on Any Other Metric\n",
"rundata" "Show the run and the model that has the smallest `log_loss` value:"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"### Retrieve the Best Model\n", "outputs": [],
"\n", "source": [
"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*." "lookup_metric = \"log_loss\"\n",
], "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
"cell_type": "markdown" "print(best_run)\n",
}, "print(fitted_model)"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "markdown",
"source": [ "metadata": {},
"best_run, fitted_model = local_run.get_output()\n", "source": [
"print(best_run)\n", "#### Model from a Specific Iteration\n",
"print(fitted_model)" "Show the run and the model from the third iteration:"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"#### Best Model Based on Any Other Metric\n", "outputs": [],
"Show the run and the model that has the smallest `log_loss` value:" "source": [
], "iteration = 3\n",
"cell_type": "markdown" "third_run, third_model = local_run.get_output(iteration = iteration)\n",
}, "print(third_run)\n",
{ "print(third_model)"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "markdown",
"lookup_metric = \"log_loss\"\n", "metadata": {},
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", "source": [
"print(best_run)\n", "## Test\n",
"print(fitted_model)" "\n",
], "#### Load Test Data"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"source": [ "execution_count": null,
"#### Model from a Specific Iteration\n", "metadata": {},
"Show the run and the model from the third iteration:" "outputs": [],
], "source": [
"cell_type": "markdown" "digits = datasets.load_digits()\n",
}, "X_test = digits.data[:10, :]\n",
{ "y_test = digits.target[:10]\n",
"metadata": {}, "images = digits.images[:10]"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"iteration = 3\n", "cell_type": "markdown",
"third_run, third_model = local_run.get_output(iteration = iteration)\n", "metadata": {},
"print(third_run)\n", "source": [
"print(third_model)" "#### Testing Our Best Fitted Model\n",
], "We will try to predict 2 digits and see how our model works."
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"source": [ "execution_count": null,
"## Test\n", "metadata": {},
"\n", "outputs": [],
"#### Load Test Data" "source": [
], "# Randomly select digits and test.\n",
"cell_type": "markdown" "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",
"metadata": {}, " label = y_test[index]\n",
"outputs": [], " title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
"execution_count": null, " fig = plt.figure(1, figsize = (3,3))\n",
"source": [ " ax1 = fig.add_axes((0,0,.8,.8))\n",
"digits = datasets.load_digits()\n", " ax1.set_title(title)\n",
"X_test = digits.data[:10, :]\n", " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
"y_test = digits.target[:10]\n", " plt.show()"
"images = digits.images[:10]" ]
], }
"cell_type": "code" ],
}, "metadata": {
{ "authors": [
"metadata": {}, {
"source": [ "name": "savitam"
"#### Testing Our Best Fitted Model\n", }
"We will try to predict 2 digits and see how our model works." ],
], "kernelspec": {
"cell_type": "markdown" "display_name": "Python 3.6",
}, "language": "python",
{ "name": "python36"
"metadata": {}, },
"outputs": [], "language_info": {
"execution_count": null, "codemirror_mode": {
"source": [ "name": "ipython",
"# Randomly select digits and test.\n", "version": 3
"for index in np.random.choice(len(y_test), 2, replace = False):\n", },
" print(index)\n", "file_extension": ".py",
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", "mimetype": "text/x-python",
" label = y_test[index]\n", "name": "python",
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n", "nbconvert_exporter": "python",
" fig = plt.figure(1, figsize = (3,3))\n", "pygments_lexer": "ipython3",
" ax1 = fig.add_axes((0,0,.8,.8))\n", "version": "3.6.6"
" ax1.set_title(title)\n", }
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", },
" plt.show()" "nbformat": 4,
], "nbformat_minor": 2
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-classification-with-whitelisting name: auto-ml-classification-with-whitelisting
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,482 +1,484 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification/auto-ml-classification.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Classification with Local Compute**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Results](#Results)\n",
"\n", "1. [Test](#Test)\n",
"Licensed under the MIT License." "\n"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification/auto-ml-classification.png)" "## Introduction\n",
], "\n",
"cell_type": "markdown" "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",
"metadata": {}, "\n",
"source": [ "In this notebook you will learn how to:\n",
"# Automated Machine Learning\n", "1. Create an `Experiment` in an existing `Workspace`.\n",
"_**Classification with Local Compute**_\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"\n", "3. Train the model using local compute.\n",
"## Contents\n", "4. Explore the results.\n",
"1. [Introduction](#Introduction)\n", "5. Test the best fitted model."
"1. [Setup](#Setup)\n", ]
"1. [Data](#Data)\n", },
"1. [Train](#Train)\n", {
"1. [Results](#Results)\n", "cell_type": "markdown",
"1. [Test](#Test)\n", "metadata": {},
"\n" "source": [
], "## Setup\n",
"cell_type": "markdown" "\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."
{ ]
"metadata": {}, },
"source": [ {
"## Introduction\n", "cell_type": "code",
"\n", "execution_count": null,
"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", "metadata": {},
"\n", "outputs": [],
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "source": [
"\n", "import logging\n",
"In this notebook you will learn how to:\n", "\n",
"1. Create an `Experiment` in an existing `Workspace`.\n", "from matplotlib import pyplot as plt\n",
"2. Configure AutoML using `AutoMLConfig`.\n", "import numpy as np\n",
"3. Train the model using local compute.\n", "import pandas as pd\n",
"4. Explore the results.\n", "from sklearn import datasets\n",
"5. Test the best fitted model." "\n",
], "import azureml.core\n",
"cell_type": "markdown" "from azureml.core.experiment import Experiment\n",
}, "from azureml.core.workspace import Workspace\n",
{ "from azureml.train.automl import AutoMLConfig"
"metadata": {}, ]
"source": [ },
"## Setup\n", {
"\n", "cell_type": "markdown",
"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." "metadata": {},
], "source": [
"cell_type": "markdown" "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",
"metadata": {}, "\n",
"outputs": [], "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",
"execution_count": null, "\n",
"source": [ "```\n",
"import logging\n", "from azureml.core.authentication import InteractiveLoginAuthentication\n",
"\n", "auth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\n",
"from matplotlib import pyplot as plt\n", "ws = Workspace.from_config(auth = auth)\n",
"import numpy as np\n", "```\n",
"import pandas as pd\n", "\n",
"from sklearn import datasets\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",
"import azureml.core\n", "```\n",
"from azureml.core.experiment import Experiment\n", "from azureml.core.authentication import ServicePrincipalAuthentication\n",
"from azureml.core.workspace import Workspace\n", "auth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\n",
"from azureml.train.automl import AutoMLConfig" "ws = Workspace.from_config(auth = auth)\n",
], "```\n",
"cell_type": "code" "For more details, see [aka.ms/aml-notebook-auth](http://aka.ms/aml-notebook-auth)"
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"Accessing the Azure ML workspace requires authentication with Azure.\n", "execution_count": null,
"\n", "metadata": {},
"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", "outputs": [],
"\n", "source": [
"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", "ws = Workspace.from_config()\n",
"\n", "\n",
"```\n", "# Choose a name for the experiment.\n",
"from azureml.core.authentication import InteractiveLoginAuthentication\n", "experiment_name = 'automl-classification'\n",
"auth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\n", "\n",
"ws = Workspace.from_config(auth = auth)\n", "experiment = Experiment(ws, experiment_name)\n",
"```\n", "\n",
"\n", "output = {}\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", "output['SDK version'] = azureml.core.VERSION\n",
"\n", "output['Subscription ID'] = ws.subscription_id\n",
"```\n", "output['Workspace Name'] = ws.name\n",
"from azureml.core.authentication import ServicePrincipalAuthentication\n", "output['Resource Group'] = ws.resource_group\n",
"auth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\n", "output['Location'] = ws.location\n",
"ws = Workspace.from_config(auth = auth)\n", "output['Experiment Name'] = experiment.name\n",
"```\n", "pd.set_option('display.max_colwidth', -1)\n",
"For more details, see [aka.ms/aml-notebook-auth](http://aka.ms/aml-notebook-auth)" "outputDf = pd.DataFrame(data = output, index = [''])\n",
], "outputDf.T"
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "## Data\n",
"ws = Workspace.from_config()\n", "\n",
"\n", "This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method."
"# 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", "cell_type": "code",
"experiment = Experiment(ws, experiment_name)\n", "execution_count": null,
"\n", "metadata": {},
"output = {}\n", "outputs": [],
"output['SDK version'] = azureml.core.VERSION\n", "source": [
"output['Subscription ID'] = ws.subscription_id\n", "digits = datasets.load_digits()\n",
"output['Workspace Name'] = ws.name\n", "\n",
"output['Resource Group'] = ws.resource_group\n", "# Exclude the first 100 rows from training so that they can be used for test.\n",
"output['Location'] = ws.location\n", "X_train = digits.data[100:,:]\n",
"output['Project Directory'] = project_folder\n", "y_train = digits.target[100:]"
"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": {},
"cell_type": "code" "source": [
}, "## Train\n",
{ "\n",
"metadata": {}, "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
"source": [ "\n",
"## Data\n", "|Property|Description|\n",
"\n", "|-|-|\n",
"This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method." "|**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",
"cell_type": "markdown" "|**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",
"metadata": {}, "|\n",
"outputs": [], "\n",
"execution_count": null, "Automated machine learning trains multiple machine learning pipelines. Each pipelines training is known as an iteration.\n",
"source": [ "* You can specify a maximum number of iterations using the `iterations` parameter.\n",
"digits = datasets.load_digits()\n", "* You can specify a maximum time for the run using the `experiment_timeout_minutes` parameter.\n",
"\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",
"# Exclude the first 100 rows from training so that they can be used for test.\n", "\n",
"X_train = digits.data[100:,:]\n", "The following example doesn't specify `iterations` or `experiment_timeout_minutes` and so runs until the scores stop improving.\n"
"y_train = digits.target[100:]" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"## Train\n", "source": [
"\n", "automl_config = AutoMLConfig(task = 'classification',\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", " primary_metric = 'AUC_weighted',\n",
"\n", " X = X_train, \n",
"|Property|Description|\n", " y = y_train,\n",
"|-|-|\n", " n_cross_validations = 3)"
"|**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", "cell_type": "markdown",
"|**n_cross_validations**|Number of cross validation splits.|\n", "metadata": {},
"|\n", "source": [
"\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.\n",
"Automated machine learning trains multiple machine learning pipelines. Each pipelines training is known as an iteration.\n", "In this example, we specify `show_output = True` to print currently running iterations to the console."
"* 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", "cell_type": "code",
"The following example doesn't specify `iterations` or `experiment_timeout_minutes` and so runs until the scores stop improving.\n" "execution_count": null,
], "metadata": {},
"cell_type": "markdown" "outputs": [],
}, "source": [
{ "local_run = experiment.submit(automl_config, show_output = True)"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "code",
"automl_config = AutoMLConfig(task = 'classification',\n", "execution_count": null,
" primary_metric = 'AUC_weighted',\n", "metadata": {},
" X = X_train, \n", "outputs": [],
" y = y_train,\n", "source": [
" n_cross_validations = 3)" "local_run"
], ]
"cell_type": "code" },
}, {
{ "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", "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:"
"In this example, we specify `show_output = True` to print currently running iterations to the console." ]
], },
"cell_type": "markdown" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "local_run = local_run.continue_experiment(X = X_train, \n",
"local_run = experiment.submit(automl_config, show_output = True)" " y = y_train, \n",
], " show_output = True,\n",
"cell_type": "code" " iterations = 5)"
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "markdown",
"execution_count": null, "metadata": {},
"source": [ "source": [
"local_run" "## Results"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "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:" "#### Widget for Monitoring Runs\n",
], "\n",
"cell_type": "markdown" "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."
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "code",
"local_run = local_run.continue_experiment(X = X_train, \n", "execution_count": null,
" y = y_train, \n", "metadata": {
" show_output = True,\n", "tags": [
" iterations = 5)" "widget-rundetails-sample"
], ]
"cell_type": "code" },
}, "outputs": [],
{ "source": [
"metadata": {}, "from azureml.widgets import RunDetails\n",
"source": [ "RunDetails(local_run).show() "
"## Results" ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "\n",
"#### Widget for Monitoring Runs\n", "#### Retrieve All Child Runs\n",
"\n", "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
"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",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "children = list(local_run.get_children())\n",
"execution_count": null, "metricslist = {}\n",
"source": [ "for run in children:\n",
"from azureml.widgets import RunDetails\n", " properties = run.get_properties()\n",
"RunDetails(local_run).show() " " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
], " metricslist[int(properties['iteration'])] = metrics\n",
"cell_type": "code" "\n",
}, "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
{ "rundata"
"metadata": {}, ]
"source": [ },
"\n", {
"#### Retrieve All Child Runs\n", "cell_type": "markdown",
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." "metadata": {},
], "source": [
"cell_type": "markdown" "### 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*."
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "code",
"children = list(local_run.get_children())\n", "execution_count": null,
"metricslist = {}\n", "metadata": {},
"for run in children:\n", "outputs": [],
" properties = run.get_properties()\n", "source": [
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n", "best_run, fitted_model = local_run.get_output()\n",
" metricslist[int(properties['iteration'])] = metrics\n", "print(best_run)"
"\n", ]
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", },
"rundata" {
], "cell_type": "markdown",
"cell_type": "code" "metadata": {},
}, "source": [
{ "#### Print the properties of the model\n",
"metadata": {}, "The fitted_model is a python object and you can read the different properties of the object.\n",
"source": [ "The following shows printing hyperparameters for each step in the pipeline."
"### 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",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "from pprint import pprint\n",
"execution_count": null, "\n",
"source": [ "def print_model(model, prefix=\"\"):\n",
"best_run, fitted_model = local_run.get_output()\n", " for step in model.steps:\n",
"print(best_run)" " print(prefix + step[0])\n",
], " if hasattr(step[1], 'estimators') and hasattr(step[1], 'weights'):\n",
"cell_type": "code" " 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",
"metadata": {}, " print_model(estimator[1], estimator[0]+ ' - ')\n",
"source": [ " elif hasattr(step[1], '_base_learners') and hasattr(step[1], '_meta_learner'):\n",
"#### Print the properties of the model\n", " print(\"\\nMeta Learner\")\n",
"The fitted_model is a python object and you can read the different properties of the object.\n", " pprint(step[1]._meta_learner)\n",
"The following shows printing hyperparameters for each step in the pipeline." " print()\n",
], " for estimator in step[1]._base_learners:\n",
"cell_type": "markdown" " print_model(estimator[1], estimator[0]+ ' - ')\n",
}, " else:\n",
{ " pprint(step[1].get_params())\n",
"metadata": {}, " print()\n",
"outputs": [], " \n",
"execution_count": null, "print_model(fitted_model)"
"source": [ ]
"from pprint import pprint\n", },
"\n", {
"def print_model(model, prefix=\"\"):\n", "cell_type": "markdown",
" for step in model.steps:\n", "metadata": {},
" print(prefix + step[0])\n", "source": [
" if hasattr(step[1], 'estimators') and hasattr(step[1], 'weights'):\n", "#### Best Model Based on Any Other Metric\n",
" pprint({'estimators': list(e[0] for e in step[1].estimators), 'weights': step[1].weights})\n", "Show the run and the model that has the smallest `log_loss` value:"
" 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", "cell_type": "code",
" print(\"\\nMeta Learner\")\n", "execution_count": null,
" pprint(step[1]._meta_learner)\n", "metadata": {},
" print()\n", "outputs": [],
" for estimator in step[1]._base_learners:\n", "source": [
" print_model(estimator[1], estimator[0]+ ' - ')\n", "lookup_metric = \"log_loss\"\n",
" else:\n", "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
" pprint(step[1].get_params())\n", "print(best_run)"
" print()\n", ]
" \n", },
"print_model(fitted_model)" {
], "cell_type": "code",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "print_model(fitted_model)"
"#### Best Model Based on Any Other Metric\n", ]
"Show the run and the model that has the smallest `log_loss` value:" },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "#### Model from a Specific Iteration\n",
"outputs": [], "Show the run and the model from the third iteration:"
"execution_count": null, ]
"source": [ },
"lookup_metric = \"log_loss\"\n", {
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", "cell_type": "code",
"print(best_run)" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "iteration = 3\n",
"metadata": {}, "third_run, third_model = local_run.get_output(iteration = iteration)\n",
"outputs": [], "print(third_run)"
"execution_count": null, ]
"source": [ },
"print_model(fitted_model)" {
], "cell_type": "code",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "print_model(third_model)"
"#### Model from a Specific Iteration\n", ]
"Show the run and the model from the third iteration:" },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Test \n",
"outputs": [], "\n",
"execution_count": null, "#### Load Test Data"
"source": [ ]
"iteration = 3\n", },
"third_run, third_model = local_run.get_output(iteration = iteration)\n", {
"print(third_run)" "cell_type": "code",
], "execution_count": null,
"cell_type": "code" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "digits = datasets.load_digits()\n",
"outputs": [], "X_test = digits.data[:10, :]\n",
"execution_count": null, "y_test = digits.target[:10]\n",
"source": [ "images = digits.images[:10]"
"print_model(third_model)" ]
], },
"cell_type": "code" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "#### Testing Our Best Fitted Model\n",
"## Test \n", "We will try to predict 2 digits and see how our model works."
"\n", ]
"#### Load Test Data" },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "# Randomly select digits and test.\n",
"source": [ "for index in np.random.choice(len(y_test), 2, replace = False):\n",
"digits = datasets.load_digits()\n", " print(index)\n",
"X_test = digits.data[:10, :]\n", " predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
"y_test = digits.target[:10]\n", " label = y_test[index]\n",
"images = digits.images[:10]" " title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
], " fig = plt.figure(1, figsize = (3,3))\n",
"cell_type": "code" " 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",
"metadata": {}, " plt.show()"
"source": [ ]
"#### Testing Our Best Fitted Model\n", }
"We will try to predict 2 digits and see how our model works." ],
], "metadata": {
"cell_type": "markdown" "authors": [
}, {
{ "name": "savitam"
"metadata": {}, }
"outputs": [], ],
"execution_count": null, "kernelspec": {
"source": [ "display_name": "Python 3.6",
"# Randomly select digits and test.\n", "language": "python",
"for index in np.random.choice(len(y_test), 2, replace = False):\n", "name": "python36"
" print(index)\n", },
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", "language_info": {
" label = y_test[index]\n", "codemirror_mode": {
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n", "name": "ipython",
" fig = plt.figure(1, figsize = (3,3))\n", "version": 3
" ax1 = fig.add_axes((0,0,.8,.8))\n", },
" ax1.set_title(title)\n", "file_extension": ".py",
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", "mimetype": "text/x-python",
" plt.show()" "name": "python",
], "nbconvert_exporter": "python",
"cell_type": "code" "pygments_lexer": "ipython3",
} "version": "3.6.6"
], }
"nbformat_minor": 2 },
"nbformat": 4,
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-classification name: auto-ml-classification
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,10 +1,11 @@
name: regression-part2-automated-ml name: auto-ml-dataset-remote-execution
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-defaults
- azureml-explain-model - azureml-explain-model
- matplotlib - azureml-train-automl
- pandas_ml - azureml-widgets
- seaborn - matplotlib
- pandas_ml

View File

@@ -1,417 +1,399 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/dataprep/auto-ml-dataprep.png)"
"authors": [ ]
{ },
"name": "savitam" {
} "cell_type": "markdown",
], "metadata": {},
"language_info": { "source": [
"mimetype": "text/x-python", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"codemirror_mode": { "\n",
"name": "ipython", "Licensed under the MIT License."
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.5" "# Automated Machine Learning\n",
} "_**Load Data using `TabularDataset` for Local Execution**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/dataprep/auto-ml-dataprep.png)" "1. [Results](#Results)\n",
], "1. [Test](#Test)"
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"source": [ "metadata": {},
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "source": [
"\n", "## Introduction\n",
"Licensed under the MIT License." "In this example we showcase how you can use AzureML Dataset to load data for AutoML.\n",
], "\n",
"cell_type": "markdown" "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
}, "\n",
{ "In this notebook you will learn how to:\n",
"metadata": {}, "1. Create a `TabularDataset` pointing to the training data.\n",
"source": [ "2. Pass the `TabularDataset` to AutoML for a local run."
"# Automated Machine Learning\n", ]
"_**Prepare Data using `azureml.dataprep` for Local Execution**_\n", },
"\n", {
"## Contents\n", "cell_type": "markdown",
"1. [Introduction](#Introduction)\n", "metadata": {},
"1. [Setup](#Setup)\n", "source": [
"1. [Data](#Data)\n", "## Setup"
"1. [Train](#Train)\n", ]
"1. [Results](#Results)\n", },
"1. [Test](#Test)" {
], "cell_type": "markdown",
"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."
"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", "cell_type": "code",
"\n", "execution_count": null,
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "metadata": {},
"\n", "outputs": [],
"In this notebook you will learn how to:\n", "source": [
"1. Define data loading and preparation steps in a `Dataflow` using `azureml.dataprep`.\n", "import logging\n",
"2. Pass the `Dataflow` to AutoML for a local run.\n", "\n",
"3. Pass the `Dataflow` to AutoML for a remote run." "import pandas as pd\n",
], "\n",
"cell_type": "markdown" "import azureml.core\n",
}, "from azureml.core.experiment import Experiment\n",
{ "from azureml.core.workspace import Workspace\n",
"metadata": {}, "from azureml.core.dataset import Dataset\n",
"source": [ "from azureml.train.automl import AutoMLConfig"
"## 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": "code",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "ws = Workspace.from_config()\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." " \n",
], "# choose a name for experiment\n",
"cell_type": "markdown" "experiment_name = 'automl-dataset-local'\n",
}, " \n",
{ "experiment = Experiment(ws, experiment_name)\n",
"metadata": {}, " \n",
"outputs": [], "output = {}\n",
"execution_count": null, "output['SDK version'] = azureml.core.VERSION\n",
"source": [ "output['Subscription ID'] = ws.subscription_id\n",
"import logging\n", "output['Workspace Name'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"import pandas as pd\n", "output['Location'] = ws.location\n",
"\n", "output['Experiment Name'] = experiment.name\n",
"import azureml.core\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.core.experiment import Experiment\n", "outputDf = pd.DataFrame(data = output, index = [''])\n",
"from azureml.core.workspace import Workspace\n", "outputDf.T"
"import azureml.dataprep as dprep\n", ]
"from azureml.train.automl import AutoMLConfig" },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Data"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"ws = Workspace.from_config()\n", "cell_type": "code",
" \n", "execution_count": null,
"# choose a name for experiment\n", "metadata": {},
"experiment_name = 'automl-dataprep-local'\n", "outputs": [],
"# project folder\n", "source": [
"project_folder = './sample_projects/automl-dataprep-local'\n", "# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n",
" \n", "example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\n",
"experiment = Experiment(ws, experiment_name)\n", "dataset = Dataset.Tabular.from_delimited_files(example_data)\n",
" \n", "dataset.take(5).to_pandas_dataframe()"
"output = {}\n", ]
"output['SDK version'] = azureml.core.VERSION\n", },
"output['Subscription ID'] = ws.subscription_id\n", {
"output['Workspace Name'] = ws.name\n", "cell_type": "markdown",
"output['Resource Group'] = ws.resource_group\n", "metadata": {},
"output['Location'] = ws.location\n", "source": [
"output['Project Directory'] = project_folder\n", "### Review the data\n",
"output['Experiment Name'] = experiment.name\n", "\n",
"pd.set_option('display.max_colwidth', -1)\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, which makes it fast even against large datasets.\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "\n",
"outputDf.T" "`TabularDataset` objects are immutable and are composed of a list of subsetting transformations (optional)."
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"## Data" "outputs": [],
], "source": [
"cell_type": "markdown" "training_data = dataset.drop_columns(columns=['FBI Code'])\n",
}, "label_column_name = 'Primary Type'"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "markdown",
"source": [ "metadata": {},
"# You can use `auto_read_file` which intelligently figures out delimiters and datatypes of a file.\n", "source": [
"# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n", "## Train\n",
"# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n", "\n",
"# and convert column types manually.\n", "This creates a general AutoML settings object applicable for both local and remote runs."
"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",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "automl_settings = {\n",
"execution_count": null, " \"iteration_timeout_minutes\" : 10,\n",
"source": [ " \"iterations\" : 2,\n",
"# As `Primary Type` is our y data, we need to drop the values those are null in this column.\n", " \"primary_metric\" : 'AUC_weighted',\n",
"dflow = dflow.drop_nulls('Primary Type')\n", " \"preprocess\" : True,\n",
"dflow.head(5)" " \"verbosity\" : logging.INFO\n",
], "}"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"source": [ "metadata": {},
"### Review the Data Preparation Result\n", "source": [
"\n", "### Pass Data with `TabularDataset` Objects\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",
"\n", "The `TabularDataset` objects captured above can be passed to the `submit` method for a local run. AutoML will retrieve the results from the `TabularDataset` for model training."
"`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": "markdown" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "automl_config = AutoMLConfig(task = 'classification',\n",
"X = dflow.drop_columns(columns=['Primary Type', 'FBI Code'])\n", " debug_log = 'automl_errors.log',\n",
"y = dflow.keep_columns(columns=['Primary Type'], validate_column_exists=True)" " training_data = training_data,\n",
], " label_column_name = label_column_name,\n",
"cell_type": "code" " **automl_settings)"
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"## Train\n", "execution_count": null,
"\n", "metadata": {},
"This creates a general AutoML settings object applicable for both local and remote runs." "outputs": [],
], "source": [
"cell_type": "markdown" "local_run = experiment.submit(automl_config, show_output = True)"
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "code",
"execution_count": null, "execution_count": null,
"source": [ "metadata": {},
"automl_settings = {\n", "outputs": [],
" \"iteration_timeout_minutes\" : 10,\n", "source": [
" \"iterations\" : 2,\n", "local_run"
" \"primary_metric\" : 'AUC_weighted',\n", ]
" \"preprocess\" : True,\n", },
" \"verbosity\" : logging.INFO\n", {
"}" "cell_type": "markdown",
], "metadata": {},
"cell_type": "code" "source": [
}, "## Results"
{ ]
"metadata": {}, },
"source": [ {
"### Pass Data with `Dataflow` Objects\n", "cell_type": "markdown",
"\n", "metadata": {},
"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." "source": [
], "#### Widget for Monitoring Runs\n",
"cell_type": "markdown" "\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",
"metadata": {}, "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"outputs": [], ]
"execution_count": null, },
"source": [ {
"automl_config = AutoMLConfig(task = 'classification',\n", "cell_type": "code",
" debug_log = 'automl_errors.log',\n", "execution_count": null,
" X = X,\n", "metadata": {},
" y = y,\n", "outputs": [],
" **automl_settings)" "source": [
], "from azureml.widgets import RunDetails\n",
"cell_type": "code" "RunDetails(local_run).show()"
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "markdown",
"execution_count": null, "metadata": {},
"source": [ "source": [
"local_run = experiment.submit(automl_config, show_output = True)" "#### 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" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"local_run" "source": [
], "children = list(local_run.get_children())\n",
"cell_type": "code" "metricslist = {}\n",
}, "for run in children:\n",
{ " properties = run.get_properties()\n",
"metadata": {}, " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
"source": [ " metricslist[int(properties['iteration'])] = metrics\n",
"## Results" " \n",
], "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"cell_type": "markdown" "rundata"
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "markdown",
"#### Widget for Monitoring Runs\n", "metadata": {},
"\n", "source": [
"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", "### Retrieve the Best Model\n",
"\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." "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" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"from azureml.widgets import RunDetails\n", "best_run, fitted_model = local_run.get_output()\n",
"RunDetails(local_run).show()" "print(best_run)\n",
], "print(fitted_model)"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"source": [ "metadata": {},
"#### Retrieve All Child Runs\n", "source": [
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." "#### Best Model Based on Any Other Metric\n",
], "Show the run and the model that has the smallest `log_loss` value:"
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"children = list(local_run.get_children())\n", "source": [
"metricslist = {}\n", "lookup_metric = \"log_loss\"\n",
"for run in children:\n", "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
" properties = run.get_properties()\n", "print(best_run)\n",
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n", "print(fitted_model)"
" metricslist[int(properties['iteration'])] = metrics\n", ]
" \n", },
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", {
"rundata" "cell_type": "markdown",
], "metadata": {},
"cell_type": "code" "source": [
}, "#### Model from a Specific Iteration\n",
{ "Show the run and the model from the first iteration:"
"metadata": {}, ]
"source": [ },
"### Retrieve the Best Model\n", {
"\n", "cell_type": "code",
"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*." "execution_count": null,
], "metadata": {},
"cell_type": "markdown" "outputs": [],
}, "source": [
{ "iteration = 0\n",
"metadata": {}, "best_run, fitted_model = local_run.get_output(iteration = iteration)\n",
"outputs": [], "print(best_run)\n",
"execution_count": null, "print(fitted_model)"
"source": [ ]
"best_run, fitted_model = local_run.get_output()\n", },
"print(best_run)\n", {
"print(fitted_model)" "cell_type": "markdown",
], "metadata": {},
"cell_type": "code" "source": [
}, "## Test\n",
{ "\n",
"metadata": {}, "#### Load Test Data\n",
"source": [ "For the test data, it should have the same preparation step as the train data. Otherwise it might get failed at the preprocessing step."
"#### Best Model Based on Any Other Metric\n", ]
"Show the run and the model that has the smallest `log_loss` value:" },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "dataset_test = Dataset.Tabular.from_delimited_files(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv')\n",
"source": [ "\n",
"lookup_metric = \"log_loss\"\n", "df_test = dataset_test.to_pandas_dataframe()\n",
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", "df_test = df_test[pd.notnull(df_test['Primary Type'])]\n",
"print(best_run)\n", "\n",
"print(fitted_model)" "y_test = df_test[['Primary Type']]\n",
], "X_test = df_test.drop(['Primary Type', 'FBI Code'], axis=1)"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"source": [ "metadata": {},
"#### Model from a Specific Iteration\n", "source": [
"Show the run and the model from the first iteration:" "#### Testing Our Best Fitted Model\n",
], "We will use confusion matrix to see how our model works."
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"iteration = 0\n", "source": [
"best_run, fitted_model = local_run.get_output(iteration = iteration)\n", "from pandas_ml import ConfusionMatrix\n",
"print(best_run)\n", "\n",
"print(fitted_model)" "ypred = fitted_model.predict(X_test)\n",
], "\n",
"cell_type": "code" "cm = ConfusionMatrix(y_test['Primary Type'], ypred)\n",
}, "\n",
{ "print(cm)\n",
"metadata": {}, "\n",
"source": [ "cm.plot()"
"## 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." "metadata": {
], "authors": [
"cell_type": "markdown" {
}, "name": "savitam"
{ }
"metadata": {}, ],
"outputs": [], "kernelspec": {
"execution_count": null, "display_name": "Python 3.6",
"source": [ "language": "python",
"dflow_test = dprep.auto_read_file(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv').skip(1)\n", "name": "python36"
"dflow_test = dflow_test.drop_nulls('Primary Type')" },
], "language_info": {
"cell_type": "code" "codemirror_mode": {
}, "name": "ipython",
{ "version": 3
"metadata": {}, },
"source": [ "file_extension": ".py",
"#### Testing Our Best Fitted Model\n", "mimetype": "text/x-python",
"We will use confusion matrix to see how our model works." "name": "python",
], "nbconvert_exporter": "python",
"cell_type": "markdown" "pygments_lexer": "ipython3",
}, "version": "3.6.5"
{ }
"metadata": {}, },
"outputs": [], "nbformat": 4,
"execution_count": null, "nbformat_minor": 2
"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()"
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,9 @@
name: auto-ml-dataprep name: auto-ml-dataset
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- azureml-dataprep[pandas]

View File

@@ -1,349 +1,349 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/exploring-previous-runs/auto-ml-exploring-previous-runs.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Exploring Previous Runs**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Explore](#Explore)\n",
"source": [ "1. [Download](#Download)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Register](#Register)"
"\n", ]
"Licensed under the MIT License." },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Introduction\n",
"source": [ "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",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/exploring-previous-runs/auto-ml-exploring-previous-runs.png)" "\n",
], "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"cell_type": "markdown" "\n",
}, "In this notebook you will learn how to:\n",
{ "1. List all experiments in a workspace.\n",
"metadata": {}, "2. List all AutoML runs in an experiment.\n",
"source": [ "3. Get details for an AutoML run, including settings, run widget, and all metrics.\n",
"# Automated Machine Learning\n", "4. Download a fitted pipeline for any iteration."
"_**Exploring Previous Runs**_\n", ]
"\n", },
"## Contents\n", {
"1. [Introduction](#Introduction)\n", "cell_type": "markdown",
"1. [Setup](#Setup)\n", "metadata": {},
"1. [Explore](#Explore)\n", "source": [
"1. [Download](#Download)\n", "## Setup"
"1. [Register](#Register)" ]
], },
"cell_type": "markdown" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"## Introduction\n", "source": [
"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", "import pandas as pd\n",
"\n", "import json\n",
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "\n",
"\n", "from azureml.core.experiment import Experiment\n",
"In this notebook you will learn how to:\n", "from azureml.core.workspace import Workspace\n",
"1. List all experiments in a workspace.\n", "from azureml.train.automl.run import AutoMLRun"
"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": "code",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "ws = Workspace.from_config()"
"## Setup" ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"outputs": [], "## Explore"
"execution_count": null, ]
"source": [ },
"import pandas as pd\n", {
"import json\n", "cell_type": "markdown",
"\n", "metadata": {},
"from azureml.core.experiment import Experiment\n", "source": [
"from azureml.core.workspace import Workspace\n", "### List Experiments"
"from azureml.train.automl.run import AutoMLRun" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "experiment_list = Experiment.list(workspace=ws)\n",
"ws = Workspace.from_config()" "\n",
], "summary_df = pd.DataFrame(index = ['No of Runs'])\n",
"cell_type": "code" "for experiment in experiment_list:\n",
}, " automl_runs = list(experiment.get_runs(type='automl'))\n",
{ " summary_df[experiment.name] = [len(automl_runs)]\n",
"metadata": {}, " \n",
"source": [ "pd.set_option('display.max_colwidth', -1)\n",
"## Explore" "summary_df.T"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"### List Experiments" "### 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": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"experiment_list = Experiment.list(workspace=ws)\n", "source": [
"\n", "experiment_name = 'automl-local-classification' # Replace this with any project name from previous cell.\n",
"summary_df = pd.DataFrame(index = ['No of Runs'])\n", "\n",
"for experiment in experiment_list:\n", "proj = ws.experiments[experiment_name]\n",
" automl_runs = list(experiment.get_runs(type='automl'))\n", "summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name'])\n",
" summary_df[experiment.name] = [len(automl_runs)]\n", "automl_runs = list(proj.get_runs(type='automl'))\n",
" \n", "automl_runs_project = []\n",
"pd.set_option('display.max_colwidth', -1)\n", "for run in automl_runs:\n",
"summary_df.T" " properties = run.get_properties()\n",
], " tags = run.get_tags()\n",
"cell_type": "code" " amlsettings = json.loads(properties['AMLSettingsJsonString'])\n",
}, " if 'iterations' in tags:\n",
{ " iterations = tags['iterations']\n",
"metadata": {}, " else:\n",
"source": [ " iterations = properties['num_iterations']\n",
"### List runs for an experiment\n", " summary_df[run.id] = [amlsettings['task_type'], run.get_details()['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name']]\n",
"Set `experiment_name` to any experiment name from the result of the Experiment.list cell to load the AutoML runs." " if run.get_details()['status'] == 'Completed':\n",
], " automl_runs_project.append(run.id)\n",
"cell_type": "markdown" " \n",
}, "from IPython.display import HTML\n",
{ "projname_html = HTML(\"<h3>{}</h3>\".format(proj.name))\n",
"metadata": {}, "\n",
"outputs": [], "from IPython.display import display\n",
"execution_count": null, "display(projname_html)\n",
"source": [ "display(summary_df.T)"
"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", "cell_type": "markdown",
"automl_runs = list(proj.get_runs(type='automl'))\n", "metadata": {},
"automl_runs_project = []\n", "source": [
"for run in automl_runs:\n", "### Get details for a run\n",
" properties = run.get_properties()\n", "\n",
" tags = run.get_tags()\n", "Copy the project name and run id from the previous cell output to find more details on a particular run."
" amlsettings = json.loads(properties['AMLSettingsJsonString'])\n", ]
" if 'iterations' in tags:\n", },
" iterations = tags['iterations']\n", {
" else:\n", "cell_type": "code",
" iterations = properties['num_iterations']\n", "execution_count": null,
" summary_df[run.id] = [amlsettings['task_type'], run.get_details()['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name']]\n", "metadata": {},
" if run.get_details()['status'] == 'Completed':\n", "outputs": [],
" automl_runs_project.append(run.id)\n", "source": [
" \n", "run_id = automl_runs_project[0] # Replace with your own run_id from above run ids\n",
"from IPython.display import HTML\n", "assert (run_id in summary_df.keys()), \"Run id not found! Please set run id to a value from above run ids\"\n",
"projname_html = HTML(\"<h3>{}</h3>\".format(proj.name))\n", "\n",
"\n", "from azureml.widgets import RunDetails\n",
"from IPython.display import display\n", "\n",
"display(projname_html)\n", "experiment = Experiment(ws, experiment_name)\n",
"display(summary_df.T)" "ml_run = AutoMLRun(experiment = experiment, run_id = run_id)\n",
], "\n",
"cell_type": "code" "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",
"metadata": {}, "status = ml_run.get_details()\n",
"source": [ "amlsettings = json.loads(properties['AMLSettingsJsonString'])\n",
"### Get details for a run\n", "if 'iterations' in tags:\n",
"\n", " iterations = tags['iterations']\n",
"Copy the project name and run id from the previous cell output to find more details on a particular run." "else:\n",
], " iterations = properties['num_iterations']\n",
"cell_type": "markdown" "start_time = None\n",
}, "if 'startTimeUtc' in status:\n",
{ " start_time = status['startTimeUtc']\n",
"metadata": {}, "end_time = None\n",
"outputs": [], "if 'endTimeUtc' in status:\n",
"execution_count": null, " end_time = status['endTimeUtc']\n",
"source": [ "summary_df[ml_run.id] = [amlsettings['task_type'], status['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name'], start_time, end_time]\n",
"run_id = automl_runs_project[0] # Replace with your own run_id from above run ids\n", "display(HTML('<h3>Runtime Details</h3>'))\n",
"assert (run_id in summary_df.keys()), \"Run id not found! Please set run id to a value from above run ids\"\n", "display(summary_df)\n",
"\n", "\n",
"from azureml.widgets import RunDetails\n", "#settings_df = pd.DataFrame(data = amlsettings, index = [''])\n",
"\n", "display(HTML('<h3>AutoML Settings</h3>'))\n",
"experiment = Experiment(ws, experiment_name)\n", "display(amlsettings)\n",
"ml_run = AutoMLRun(experiment = experiment, run_id = run_id)\n", "\n",
"\n", "display(HTML('<h3>Iterations</h3>'))\n",
"summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name', 'Start Time', 'End Time'])\n", "RunDetails(ml_run).show() \n",
"properties = ml_run.get_properties()\n", "\n",
"tags = ml_run.get_tags()\n", "all_metrics = ml_run.get_metrics(recursive=True)\n",
"status = ml_run.get_details()\n", "metricslist = {}\n",
"amlsettings = json.loads(properties['AMLSettingsJsonString'])\n", "for run_id, metrics in all_metrics.items():\n",
"if 'iterations' in tags:\n", " iteration = int(run_id.split('_')[-1])\n",
" iterations = tags['iterations']\n", " float_metrics = {k: v for k, v in metrics.items() if isinstance(v, float)}\n",
"else:\n", " metricslist[iteration] = float_metrics\n",
" iterations = properties['num_iterations']\n", "\n",
"start_time = None\n", "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"if 'startTimeUtc' in status:\n", "display(HTML('<h3>Metrics</h3>'))\n",
" start_time = status['startTimeUtc']\n", "display(rundata)\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", "cell_type": "markdown",
"display(HTML('<h3>Runtime Details</h3>'))\n", "metadata": {},
"display(summary_df)\n", "source": [
"\n", "## Download"
"#settings_df = pd.DataFrame(data = amlsettings, index = [''])\n", ]
"display(HTML('<h3>AutoML Settings</h3>'))\n", },
"display(amlsettings)\n", {
"\n", "cell_type": "markdown",
"display(HTML('<h3>Iterations</h3>'))\n", "metadata": {},
"RunDetails(ml_run).show() \n", "source": [
"\n", "### Download the Best Model for Any Given Metric"
"children = list(ml_run.get_children())\n", ]
"metricslist = {}\n", },
"for run in children:\n", {
" properties = run.get_properties()\n", "cell_type": "code",
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n", "execution_count": null,
" metricslist[int(properties['iteration'])] = metrics\n", "metadata": {},
"\n", "outputs": [],
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "source": [
"display(HTML('<h3>Metrics</h3>'))\n", "metric = 'AUC_weighted' # Replace with a metric name.\n",
"display(rundata)\n" "best_run, fitted_model = ml_run.get_output(metric = metric)\n",
], "fitted_model"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"source": [ "metadata": {},
"## Download" "source": [
], "### Download the Model for Any Given Iteration"
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"source": [ "execution_count": null,
"### Download the Best Model for Any Given Metric" "metadata": {},
], "outputs": [],
"cell_type": "markdown" "source": [
}, "iteration = 1 # Replace with an iteration number.\n",
{ "best_run, fitted_model = ml_run.get_output(iteration = iteration)\n",
"metadata": {}, "fitted_model"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"metric = 'AUC_weighted' # Replace with a metric name.\n", "cell_type": "markdown",
"best_run, fitted_model = ml_run.get_output(metric = metric)\n", "metadata": {},
"fitted_model" "source": [
], "## Register"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"source": [ "metadata": {},
"### Download the Model for Any Given Iteration" "source": [
], "### Register fitted model for deployment\n",
"cell_type": "markdown" "If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered."
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "code",
"execution_count": null, "execution_count": null,
"source": [ "metadata": {},
"iteration = 1 # Replace with an iteration number.\n", "outputs": [],
"best_run, fitted_model = ml_run.get_output(iteration = iteration)\n", "source": [
"fitted_model" "description = 'AutoML Model'\n",
], "tags = None\n",
"cell_type": "code" "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."
{ ]
"metadata": {}, },
"source": [ {
"## Register" "cell_type": "markdown",
], "metadata": {},
"cell_type": "markdown" "source": [
}, "### Register the Best Model for Any Given Metric"
{ ]
"metadata": {}, },
"source": [ {
"### Register fitted model for deployment\n", "cell_type": "code",
"If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered." "execution_count": null,
], "metadata": {},
"cell_type": "markdown" "outputs": [],
}, "source": [
{ "metric = 'AUC_weighted' # Replace with a metric name.\n",
"metadata": {}, "description = 'AutoML Model'\n",
"outputs": [], "tags = None\n",
"execution_count": null, "ml_run.register_model(description = description, tags = tags, metric = metric)\n",
"source": [ "print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
"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": {},
"cell_type": "code" "source": [
}, "### Register the Model for Any Given Iteration"
{ ]
"metadata": {}, },
"source": [ {
"### Register the Best Model for Any Given Metric" "cell_type": "code",
], "execution_count": null,
"cell_type": "markdown" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "iteration = 1 # Replace with an iteration number.\n",
"outputs": [], "description = 'AutoML Model'\n",
"execution_count": null, "tags = None\n",
"source": [ "ml_run.register_model(description = description, tags = tags, iteration = iteration)\n",
"metric = 'AUC_weighted' # Replace with a metric name.\n", "print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
"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." "metadata": {
], "authors": [
"cell_type": "code" {
}, "name": "savitam"
{ }
"metadata": {}, ],
"source": [ "kernelspec": {
"### Register the Model for Any Given Iteration" "display_name": "Python 3.6",
], "language": "python",
"cell_type": "markdown" "name": "python36"
}, },
{ "language_info": {
"metadata": {}, "codemirror_mode": {
"outputs": [], "name": "ipython",
"execution_count": null, "version": 3
"source": [ },
"iteration = 1 # Replace with an iteration number.\n", "file_extension": ".py",
"description = 'AutoML Model'\n", "mimetype": "text/x-python",
"tags = None\n", "name": "python",
"ml_run.register_model(description = description, tags = tags, iteration = iteration)\n", "nbconvert_exporter": "python",
"print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure." "pygments_lexer": "ipython3",
], "version": "3.6.6"
"cell_type": "code" }
} },
], "nbformat": 4,
"nbformat_minor": 2 "nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-exploring-previous-runs name: auto-ml-exploring-previous-runs
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,9 +1,9 @@
name: auto-ml-forecasting-bike-share name: auto-ml-forecasting-bike-share
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- statsmodels - statsmodels

View File

@@ -1,10 +1,12 @@
name: auto-ml-forecasting-energy-demand name: auto-ml-forecasting-energy-demand
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-train-automl
- matplotlib - azureml-widgets
- pandas_ml - matplotlib
- statsmodels - pandas_ml
- azureml-explain-model - statsmodels
- azureml-explain-model
- azureml-contrib-interpret

View File

@@ -0,0 +1,615 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Automated Machine Learning\n",
"\n",
"## Forecasting away from training data\n",
"\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",
"* forecast horizon: the number of forecast periods\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",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/automl-forecasting-function.png)"
]
},
{
"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 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",
"np.set_printoptions(precision=4, suppress=True, linewidth=120)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import azureml.core\n",
"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['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['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",
"GRAIN_COLUMN_NAME = 'grain'\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",
" grain_column_name: str,\n",
" grains: 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\n",
" :param grains: The number of grains.\n",
" :type grains: 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(grains):\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",
" grain_column_name: np.repeat('g{}'.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",
" grain_column_name=GRAIN_COLUMN_NAME,\n",
" grains=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",
"whole_data['y'] = y_train\n",
"for g in whole_data.groupby('grain'): \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": [
"## Create the configuration and train a forecaster\n",
"First generate the configuration, in which we:\n",
"* Set metadata columns: target, time column and grain column names.\n",
"* Ask for 10 iterations through models, last of which will represent the Ensemble of previous ones.\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",
"\n",
"* Finally, we set the task to be forecasting.\n",
"* By default, we apply the lag lead operator and rolling window 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": [
"lags = [1,2,3]\n",
"rolling_window_length = 0 # don't do rolling windows\n",
"max_horizon = n_test_periods\n",
"time_series_settings = { \n",
" 'time_column_name': TIME_COLUMN_NAME,\n",
" 'grain_column_names': [ GRAIN_COLUMN_NAME ],\n",
" 'max_horizon': max_horizon,\n",
" 'target_lags': lags\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run the model selection and training process."
]
},
{
"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",
" iterations=10, \n",
" X=X_train,\n",
" y=y_train,\n",
" n_cross_validations=3,\n",
" verbosity = logging.INFO,\n",
" **time_series_settings)\n",
"\n",
"local_run = experiment.submit(automl_config, show_output=True)\n",
"\n",
"# Retrieve the best model to use it further.\n",
"_, fitted_model = local_run.get_output()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Forecasting from the trained model"
]
},
{
"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",
"![Forecasting after training](forecast_function_at_train.png)\n",
"\n",
"The `X_test` and `y_query` below, taken together, form the **forecast request**. The two are interpreted as aligned - `y_query` could actally be a column in `X_test`. `NaN`s in `y_query` are the question marks. These will be filled with the forecasts.\n",
"\n",
"When the forecast period immediately follows the training period, the models retain the last few points of data. You can simply fill `y_query` filled with question marks - the model has the data for the lookback already.\n"
]
},
{
"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_query = np.repeat(np.NaN, X_test.shape[0])\n",
"y_pred_no_gap, xy_nogap = fitted_model.forecast(X_test, y_query)\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": [
"#### 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 of 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, y_query)\n",
"\n",
"# it all nicely aligns column-wise\n",
"pd.concat([X_test.reset_index(), pd.DataFrame({'query' : y_query}), y_pred_quantiles], axis=1)"
]
},
{
"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, becaus eit 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 maximum 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\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",
"![Forecasting after training](forecast_function_away_from_train.png)\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 grain, so each grain 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",
" grain_column_name=GRAIN_COLUMN_NAME,\n",
" grains=2)\n",
"\n",
"# end of the data we trained on\n",
"print(X_train.groupby(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].max())\n",
"# start of the data we want to predict on\n",
"print(X_away.groupby(GRAIN_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_query = y_away.copy()\n",
" y_query.fill(np.NaN)\n",
" y_pred_away, xy_away = fitted_model.forecast(X_away, y_query)\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 themodel saw an actual values of `y` (the target). That was at the end of the training data! Because the model received all `NaN` (and not an actual target value), it is attempting to forecast from the end of training data. But the requested forecast periods are past the maximum 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 grain 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(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))\n",
"print( X_away.groupby(GRAIN_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(max(lags), rolling_window_length)\n",
"lookback = pd.DateOffset(hours=n_lookback_periods)\n",
"\n",
"horizon = pd.DateOffset(hours=max_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 grains, 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', 'grain', 'ext_predictor', '_automl_target_col']]\n",
"# prediction is in _automl_target_col"
]
}
],
"metadata": {
"authors": [
{
"name": "erwright, nirovins"
}
],
"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
}

View File

@@ -1,8 +1,9 @@
name: auto-ml-dataprep-remote-execution name: automl-forecasting-function
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - pandas_ml
- pandas_ml - statsmodels
- matplotlib

View File

@@ -1,9 +1,9 @@
name: auto-ml-forecasting-orange-juice-sales name: auto-ml-forecasting-orange-juice-sales
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- statsmodels - statsmodels

View File

@@ -1,424 +1,423 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/missing-data-blacklist-early-termination/auto-ml-missing-data-blacklist-early-termination.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Blacklisting Models, Early Termination, and Handling Missing Data**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Results](#Results)\n",
"\n", "1. [Test](#Test)\n"
"Licensed under the MIT License." ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "## Introduction\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/missing-data-blacklist-early-termination/auto-ml-missing-data-blacklist-early-termination.png)" "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",
"cell_type": "markdown" "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
}, "\n",
{ "In this notebook you will learn how to:\n",
"metadata": {}, "1. Create an `Experiment` in an existing `Workspace`.\n",
"source": [ "2. Configure AutoML using `AutoMLConfig`.\n",
"# Automated Machine Learning\n", "3. Train the model.\n",
"_**Blacklisting Models, Early Termination, and Handling Missing Data**_\n", "4. Explore the results.\n",
"\n", "5. Viewing the engineered names for featurized data and featurization summary for all raw features.\n",
"## Contents\n", "6. Test the best fitted model.\n",
"1. [Introduction](#Introduction)\n", "\n",
"1. [Setup](#Setup)\n", "In addition this notebook showcases the following features\n",
"1. [Data](#Data)\n", "- **Blacklisting** certain pipelines\n",
"1. [Train](#Train)\n", "- Specifying **target metrics** to indicate stopping criteria\n",
"1. [Results](#Results)\n", "- Handling **missing data** in the input"
"1. [Test](#Test)\n" ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "## Setup\n",
"## 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 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", "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."
"\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", "cell_type": "code",
"1. Create an `Experiment` in an existing `Workspace`.\n", "execution_count": null,
"2. Configure AutoML using `AutoMLConfig`.\n", "metadata": {},
"3. Train the model.\n", "outputs": [],
"4. Explore the results.\n", "source": [
"5. Viewing the engineered names for featurized data and featurization summary for all raw features.\n", "import logging\n",
"6. Test the best fitted model.\n", "\n",
"\n", "from matplotlib import pyplot as plt\n",
"In addition this notebook showcases the following features\n", "import numpy as np\n",
"- **Blacklisting** certain pipelines\n", "import pandas as pd\n",
"- Specifying **target metrics** to indicate stopping criteria\n", "from sklearn import datasets\n",
"- Handling **missing data** in the input" "\n",
], "import azureml.core\n",
"cell_type": "markdown" "from azureml.core.experiment import Experiment\n",
}, "from azureml.core.workspace import Workspace\n",
{ "from azureml.train.automl import AutoMLConfig"
"metadata": {}, ]
"source": [ },
"## Setup\n", {
"\n", "cell_type": "code",
"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." "execution_count": null,
], "metadata": {},
"cell_type": "markdown" "outputs": [],
}, "source": [
{ "ws = Workspace.from_config()\n",
"metadata": {}, "\n",
"outputs": [], "# Choose a name for the experiment.\n",
"execution_count": null, "experiment_name = 'automl-local-missing-data'\n",
"source": [ "\n",
"import logging\n", "experiment = Experiment(ws, experiment_name)\n",
"\n", "\n",
"from matplotlib import pyplot as plt\n", "output = {}\n",
"import numpy as np\n", "output['SDK version'] = azureml.core.VERSION\n",
"import pandas as pd\n", "output['Subscription ID'] = ws.subscription_id\n",
"from sklearn import datasets\n", "output['Workspace'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"import azureml.core\n", "output['Location'] = ws.location\n",
"from azureml.core.experiment import Experiment\n", "output['Experiment Name'] = experiment.name\n",
"from azureml.core.workspace import Workspace\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.train.automl import AutoMLConfig" "outputDf = pd.DataFrame(data = output, index = [''])\n",
], "outputDf.T"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "## Data"
"ws = Workspace.from_config()\n", ]
"\n", },
"# Choose a name for the experiment.\n", {
"experiment_name = 'automl-local-missing-data'\n", "cell_type": "code",
"project_folder = './sample_projects/automl-local-missing-data'\n", "execution_count": null,
"\n", "metadata": {},
"experiment = Experiment(ws, experiment_name)\n", "outputs": [],
"\n", "source": [
"output = {}\n", "digits = datasets.load_digits()\n",
"output['SDK version'] = azureml.core.VERSION\n", "X_train = digits.data[10:,:]\n",
"output['Subscription ID'] = ws.subscription_id\n", "y_train = digits.target[10:]\n",
"output['Workspace'] = ws.name\n", "\n",
"output['Resource Group'] = ws.resource_group\n", "# Add missing values in 75% of the lines.\n",
"output['Location'] = ws.location\n", "missing_rate = 0.75\n",
"output['Project Directory'] = project_folder\n", "n_missing_samples = int(np.floor(X_train.shape[0] * missing_rate))\n",
"output['Experiment Name'] = experiment.name\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",
"pd.set_option('display.max_colwidth', -1)\n", "rng = np.random.RandomState(0)\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "rng.shuffle(missing_samples)\n",
"outputDf.T" "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" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"source": [ "execution_count": null,
"## Data" "metadata": {},
], "outputs": [],
"cell_type": "markdown" "source": [
}, "df = pd.DataFrame(data = X_train)\n",
{ "df['Label'] = pd.Series(y_train, index=df.index)\n",
"metadata": {}, "df.head()"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"digits = datasets.load_digits()\n", "cell_type": "markdown",
"X_train = digits.data[10:,:]\n", "metadata": {},
"y_train = digits.target[10:]\n", "source": [
"\n", "## Train\n",
"# Add missing values in 75% of the lines.\n", "\n",
"missing_rate = 0.75\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_missing_samples = int(np.floor(X_train.shape[0] * missing_rate))\n", "\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", "|Property|Description|\n",
"rng = np.random.RandomState(0)\n", "|-|-|\n",
"rng.shuffle(missing_samples)\n", "|**task**|classification or regression|\n",
"missing_features = rng.randint(0, X_train.shape[1], n_missing_samples)\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_train[np.where(missing_samples)[0], missing_features] = np.nan" "|**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",
"cell_type": "code" "|**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",
"metadata": {}, "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"outputs": [], "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|"
"execution_count": null, ]
"source": [ },
"df = pd.DataFrame(data = X_train)\n", {
"df['Label'] = pd.Series(y_train, index=df.index)\n", "cell_type": "code",
"df.head()" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "automl_config = AutoMLConfig(task = 'classification',\n",
"metadata": {}, " debug_log = 'automl_errors.log',\n",
"source": [ " primary_metric = 'AUC_weighted',\n",
"## Train\n", " iteration_timeout_minutes = 60,\n",
"\n", " iterations = 20,\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", " preprocess = True,\n",
"\n", " experiment_exit_score = 0.9984,\n",
"|Property|Description|\n", " blacklist_models = ['KNN','LinearSVM'],\n",
"|-|-|\n", " verbosity = logging.INFO,\n",
"|**task**|classification or regression|\n", " X = X_train, \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", " y = y_train)"
"|**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", "cell_type": "markdown",
"|**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", "metadata": {},
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "source": [
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\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.\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.|" "In this example, we specify `show_output = True` to print currently running iterations to the console."
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"automl_config = AutoMLConfig(task = 'classification',\n", "local_run = experiment.submit(automl_config, show_output = True)"
" debug_log = 'automl_errors.log',\n", ]
" primary_metric = 'AUC_weighted',\n", },
" iteration_timeout_minutes = 60,\n", {
" iterations = 20,\n", "cell_type": "code",
" preprocess = True,\n", "execution_count": null,
" experiment_exit_score = 0.9984,\n", "metadata": {},
" blacklist_models = ['KNN','LinearSVM'],\n", "outputs": [],
" verbosity = logging.INFO,\n", "source": [
" X = X_train, \n", "local_run"
" y = y_train,\n", ]
" path = project_folder)" },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Results"
"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": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "#### Widget for Monitoring Runs\n",
"metadata": {}, "\n",
"outputs": [], "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",
"execution_count": null, "\n",
"source": [ "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"local_run = experiment.submit(automl_config, show_output = True)" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "from azureml.widgets import RunDetails\n",
"local_run" "RunDetails(local_run).show() "
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Results" "\n",
], "#### Retrieve All Child Runs\n",
"cell_type": "markdown" "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"#### Widget for Monitoring Runs\n", "execution_count": null,
"\n", "metadata": {},
"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", "outputs": [],
"\n", "source": [
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "children = list(local_run.get_children())\n",
], "metricslist = {}\n",
"cell_type": "markdown" "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",
"metadata": {}, " metricslist[int(properties['iteration'])] = metrics\n",
"outputs": [], "\n",
"execution_count": null, "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"source": [ "rundata"
"from azureml.widgets import RunDetails\n", ]
"RunDetails(local_run).show() " },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "### Retrieve the Best Model\n",
"source": [ "\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 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": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "best_run, fitted_model = local_run.get_output()"
"source": [ ]
"children = list(local_run.get_children())\n", },
"metricslist = {}\n", {
"for run in children:\n", "cell_type": "markdown",
" properties = run.get_properties()\n", "metadata": {},
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n", "source": [
" metricslist[int(properties['iteration'])] = metrics\n", "#### Best Model Based on Any Other Metric\n",
"\n", "Show the run and the model which has the smallest `accuracy` value:"
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", ]
"rundata" },
], {
"cell_type": "code" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "source": [
"### Retrieve the Best Model\n", "# lookup_metric = \"accuracy\"\n",
"\n", "# best_run, fitted_model = local_run.get_output(metric = lookup_metric)"
"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": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"outputs": [], "#### Model from a Specific Iteration\n",
"execution_count": null, "Show the run and the model from the third iteration:"
"source": [ ]
"best_run, fitted_model = local_run.get_output()" },
], {
"cell_type": "code" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "source": [
"#### Best Model Based on Any Other Metric\n", "# iteration = 3\n",
"Show the run and the model which has the smallest `accuracy` value:" "# best_run, fitted_model = local_run.get_output(iteration = iteration)"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"execution_count": null, "#### View the engineered names for featurized data\n",
"source": [ "Below we display the engineered feature names generated for the featurized data using the preprocessing featurization."
"# lookup_metric = \"accuracy\"\n", ]
"# best_run, fitted_model = local_run.get_output(metric = lookup_metric)" },
], {
"cell_type": "code" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "source": [
"#### Model from a Specific Iteration\n", "fitted_model.named_steps['datatransformer'].get_engineered_feature_names()"
"Show the run and the model from the third iteration:" ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"outputs": [], "#### View the featurization summary\n",
"execution_count": null, "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",
"source": [ "- Raw feature name\n",
"# iteration = 3\n", "- Number of engineered features formed out of this raw feature\n",
"# best_run, fitted_model = local_run.get_output(iteration = iteration)" "- Type detected\n",
], "- If feature was dropped\n",
"cell_type": "code" "- List of feature transformations for the raw feature"
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"#### View the engineered names for featurized data\n", "execution_count": null,
"Below we display the engineered feature names generated for the featurized data using the preprocessing featurization." "metadata": {},
], "outputs": [],
"cell_type": "markdown" "source": [
}, "# Get the featurization summary as a list of JSON\n",
{ "featurization_summary = fitted_model.named_steps['datatransformer'].get_featurization_summary()\n",
"metadata": {}, "# View the featurization summary as a pandas dataframe\n",
"outputs": [], "pd.DataFrame.from_records(featurization_summary)"
"execution_count": null, ]
"source": [ },
"fitted_model.named_steps['datatransformer'].get_engineered_feature_names()" {
], "cell_type": "markdown",
"cell_type": "code" "metadata": {},
}, "source": [
{ "## Test"
"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", "cell_type": "code",
"- Raw feature name\n", "execution_count": null,
"- Number of engineered features formed out of this raw feature\n", "metadata": {},
"- Type detected\n", "outputs": [],
"- If feature was dropped\n", "source": [
"- List of feature transformations for the raw feature" "digits = datasets.load_digits()\n",
], "X_test = digits.data[:10, :]\n",
"cell_type": "markdown" "y_test = digits.target[:10]\n",
}, "images = digits.images[:10]\n",
{ "\n",
"metadata": {}, "# Randomly select digits and test.\n",
"outputs": [], "for index in np.random.choice(len(y_test), 2, replace = False):\n",
"execution_count": null, " print(index)\n",
"source": [ " predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
"fitted_model.named_steps['datatransformer'].get_featurization_summary()" " label = y_test[index]\n",
], " title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
"cell_type": "code" " fig = plt.figure(1, figsize=(3,3))\n",
}, " ax1 = fig.add_axes((0,0,.8,.8))\n",
{ " ax1.set_title(title)\n",
"metadata": {}, " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
"source": [ " plt.show()\n"
"## Test" ]
], }
"cell_type": "markdown" ],
}, "metadata": {
{ "authors": [
"metadata": {}, {
"outputs": [], "name": "savitam"
"execution_count": null, }
"source": [ ],
"digits = datasets.load_digits()\n", "kernelspec": {
"X_test = digits.data[:10, :]\n", "display_name": "Python 3.6",
"y_test = digits.target[:10]\n", "language": "python",
"images = digits.images[:10]\n", "name": "python36"
"\n", },
"# Randomly select digits and test.\n", "language_info": {
"for index in np.random.choice(len(y_test), 2, replace = False):\n", "codemirror_mode": {
" print(index)\n", "name": "ipython",
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", "version": 3
" label = y_test[index]\n", },
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n", "file_extension": ".py",
" fig = plt.figure(1, figsize=(3,3))\n", "mimetype": "text/x-python",
" ax1 = fig.add_axes((0,0,.8,.8))\n", "name": "python",
" ax1.set_title(title)\n", "nbconvert_exporter": "python",
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", "pygments_lexer": "ipython3",
" plt.show()\n" "version": "3.6.6"
], }
"cell_type": "code" },
} "nbformat": 4,
], "nbformat_minor": 2
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-missing-data-blacklist-early-termination name: auto-ml-missing-data-blacklist-early-termination
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -0,0 +1,593 @@
{
"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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-bank-marketing/auto-ml-classification-bank-marketing.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Automated Machine Learning\n",
"_**Regression on remote compute using Computer Hardware dataset with model explanations**_\n",
"\n",
"## Contents\n",
"1. [Introduction](#Introduction)\n",
"1. [Setup](#Setup)\n",
"1. [Train](#Train)\n",
"1. [Results](#Results)\n",
"1. [Explanations](#Explanations)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"\n",
"In this example we use the Hardware Performance Dataset to showcase how you can use AutoML for a simple regression problem. 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 Notebook VM, 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. 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. \n",
"8. Download the feature importance for raw features and visualize the explanations for raw features. \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",
"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": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ws = Workspace.from_config()\n",
"\n",
"# choose a name for experiment\n",
"experiment_name = 'automl-regression-computer-hardware'\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['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 AmlCompute\n",
"from azureml.core.compute import ComputeTarget\n",
"\n",
"# Choose a name for your cluster.\n",
"amlcompute_cluster_name = \"automlcl\"\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",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n",
" \n",
"print('Checking cluster status...')\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": [
"### Conda Dependecies for AutoML training experiment\n",
"\n",
"Create the conda dependencies for running AutoML experiment on remote compute."
]
},
{
"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",
"cd = CondaDependencies.create(conda_packages=['numpy','py-xgboost<=0.80'])\n",
"conda_run_config.environment.python.conda_dependencies = cd"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Setup Training and Test Data for AutoML experiment\n",
"\n",
"Here we create the train and test datasets for hardware performance dataset. 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 source\n",
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv\"\n",
"\n",
"# Create dataset from the url\n",
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
"\n",
"# Split the dataset into train and test datasets\n",
"train_dataset, test_dataset = dataset.random_split(percentage=0.8, seed=223)\n",
"\n",
"# Register the train dataset with your workspace\n",
"train_dataset.register(workspace = ws, name = 'hardware_performance_train_dataset',\n",
" description = 'hardware performance training data',\n",
" create_new_version=True)\n",
"\n",
"# Register the test dataset with your workspace\n",
"test_dataset.register(workspace = ws, name = 'hardware_performance_test_dataset',\n",
" description = 'hardware performance test data',\n",
" create_new_version=True)\n",
"\n",
"# Drop the labeled column from the train dataset\n",
"X_train = train_dataset.drop_columns(columns=['ERP'])\n",
"y_train = train_dataset.keep_columns(columns=['ERP'], validate=True)\n",
"\n",
"# Drop the labeled column from the test dataset\n",
"X_test = test_dataset.drop_columns(columns=['ERP']) \n",
"\n",
"# Display the top rows in the train dataset\n",
"X_train.take(5).to_pandas_dataframe()"
]
},
{
"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. 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",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"|**y**|(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": {},
"outputs": [],
"source": [
"automl_settings = {\n",
" \"iteration_timeout_minutes\": 5,\n",
" \"iterations\": 10,\n",
" \"n_cross_validations\": 2,\n",
" \"primary_metric\": 'spearman_correlation',\n",
" \"preprocess\": True,\n",
" \"max_concurrent_iterations\": 1,\n",
" \"verbosity\": logging.INFO,\n",
"}\n",
"\n",
"automl_config = AutoMLConfig(task = 'regression',\n",
" debug_log = 'automl_errors_model_exp.log',\n",
" run_configuration=conda_run_config,\n",
" X = X_train,\n",
" y = y_train,\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 = True)"
]
},
{
"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": "markdown",
"metadata": {},
"source": [
"## Explanations\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(iteration=5)"
]
},
{
"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",
"\n",
"# create script folder\n",
"script_folder = './sample_projects/automl-regression-computer-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('<<experimnet_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>>', 'hardware_performance_train_dataset') \n",
"# Name of your test dataset register with your workspace\n",
"content = content.replace('<<test_dataset_name>>', 'hardware_performance_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\n",
"We need `azureml-explain-model`, `azureml-train-automl` and `azureml-core` packages for computing model explanations for your AutoML model on remote compute."
]
},
{
"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",
"azureml_pip_packages = [\n",
" 'azureml-train-automl', 'azureml-core', 'azureml-explain-model'\n",
"]\n",
"\n",
"# specify CondaDependencies obj\n",
"conda_run_config.environment.python.conda_dependencies = CondaDependencies.create(\n",
" conda_packages=['scikit-learn', 'numpy','py-xgboost<=0.80'],\n",
" pip_packages=azureml_pip_packages)"
]
},
{
"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 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. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Setup for visualizing the model explanation results\n",
"For visualizing the explanation results for the *fitted_model* we need to perform the following steps:-\n",
"1. Featurize test data samples.\n",
"\n",
"The *automl_explainer_setup_obj* contains all the structures from above list. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations\n",
"explainer_setup_class = automl_setup_model_explanations(fitted_model, 'regression', X_test=X_test)"
]
},
{
"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 ExplanationDashboard 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.explain.model._internal.explanation_client import ExplanationClient\n",
"from azureml.contrib.interpret.visualize import ExplanationDashboard\n",
"client = ExplanationClient.from_run(automl_run)\n",
"engineered_explanations = client.download_model_explanation(raw=False)\n",
"print(engineered_explanations.get_feature_importance_dict())\n",
"ExplanationDashboard(engineered_explanations, explainer_setup_class.automl_estimator, explainer_setup_class.X_test_transform)"
]
},
{
"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 ExplanationDashboard 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)\n",
"print(raw_explanations.get_feature_importance_dict())\n",
"ExplanationDashboard(raw_explanations, explainer_setup_class.automl_pipeline, explainer_setup_class.X_test_raw)"
]
}
],
"metadata": {
"authors": [
{
"name": "v-rasav"
}
],
"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
}

View File

@@ -0,0 +1,11 @@
name: auto-ml-model-explanations-remote-compute
dependencies:
- pip:
- azureml-sdk
- interpret
- azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml
- azureml-explain-model
- azureml-contrib-interpret

View File

@@ -0,0 +1,64 @@
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
import os
from azureml.core.run import Run
from azureml.core.experiment import Experiment
from sklearn.externals import joblib
from azureml.core.dataset import Dataset
from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations
from azureml.explain.model.mimic.models.lightgbm_model import LGBMExplainableModel
from azureml.explain.model.mimic_wrapper import MimicWrapper
from automl.client.core.common.constants import MODEL_PATH
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, '<<experimnet_name>>')
automl_run = Run(experiment=experiment, run_id='<<run_id>>')
# 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'],
eval_dataset=automl_explainer_setup_obj.X_test_transform)
# Compute the raw explanations
raw_explanations = explainer.explain(['local', 'global'], get_raw=True,
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")

View File

@@ -1,357 +1,632 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "xif" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/model-explanation/auto-ml-model-explanation.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Explain classification model, visualize the explanation and operationalize the explainer along with AutoML model**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Results](#Results)\n",
"\n", "1. [Explanations](#Explanations)\n",
"Licensed under the MIT License." "1. [Operationailze](#Operationailze)"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/model-explanation/auto-ml-model-explanation.png)" "## 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",
"cell_type": "markdown" "\n",
}, "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
{ "\n",
"metadata": {}, "In this notebook you would see\n",
"source": [ "1. Creating an Experiment in an existing Workspace\n",
"# Automated Machine Learning\n", "2. Instantiating AutoMLConfig\n",
"_**Explain classification model and visualize the explanation**_\n", "3. Training the Model using local compute and explain the model\n",
"\n", "4. Visualization model's feature importance in widget\n",
"## Contents\n", "5. Explore any model's explanation\n",
"1. [Introduction](#Introduction)\n", "6. Operationalize the AutoML model and the explaination model"
"1. [Setup](#Setup)\n", ]
"1. [Data](#Data)\n", },
"1. [Train](#Train)\n", {
"1. [Results](#Results)" "cell_type": "markdown",
], "metadata": {},
"cell_type": "markdown" "source": [
}, "## Setup\n",
{ "\n",
"metadata": {}, "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."
"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", "cell_type": "code",
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "execution_count": null,
"\n", "metadata": {},
"In this notebook you would see\n", "outputs": [],
"1. Creating an Experiment in an existing Workspace\n", "source": [
"2. Instantiating AutoMLConfig\n", "import logging\n",
"3. Training the Model using local compute and explain the model\n", "\n",
"4. Visualization model's feature importance in widget\n", "import pandas as pd\n",
"5. Explore best model's explanation" "import azureml.core\n",
], "from azureml.core.experiment import Experiment\n",
"cell_type": "markdown" "from azureml.core.workspace import Workspace\n",
}, "from azureml.train.automl import AutoMLConfig\n",
{ "from azureml.core.dataset import Dataset\n",
"metadata": {}, "from azureml.explain.model._internal.explanation_client import ExplanationClient"
"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,
"cell_type": "markdown" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "ws = Workspace.from_config()\n",
"outputs": [], "\n",
"execution_count": null, "# choose a name for experiment\n",
"source": [ "experiment_name = 'automl-model-explanation'\n",
"import logging\n", "\n",
"\n", "experiment=Experiment(ws, experiment_name)\n",
"import pandas as pd\n", "\n",
"import azureml.core\n", "output = {}\n",
"from azureml.core.experiment import Experiment\n", "output['SDK version'] = azureml.core.VERSION\n",
"from azureml.core.workspace import Workspace\n", "output['Subscription ID'] = ws.subscription_id\n",
"from azureml.train.automl import AutoMLConfig" "output['Workspace Name'] = ws.name\n",
], "output['Resource Group'] = ws.resource_group\n",
"cell_type": "code" "output['Location'] = ws.location\n",
}, "output['Experiment Name'] = experiment.name\n",
{ "pd.set_option('display.max_colwidth', -1)\n",
"metadata": {}, "outputDf = pd.DataFrame(data = output, index = [''])\n",
"outputs": [], "outputDf.T"
"execution_count": null, ]
"source": [ },
"ws = Workspace.from_config()\n", {
"\n", "cell_type": "markdown",
"# choose a name for experiment\n", "metadata": {},
"experiment_name = 'automl-model-explanation'\n", "source": [
"# project folder\n", "## Data"
"project_folder = './sample_projects/automl-model-explanation'\n", ]
"\n", },
"experiment=Experiment(ws, experiment_name)\n", {
"\n", "cell_type": "markdown",
"output = {}\n", "metadata": {},
"output['SDK version'] = azureml.core.VERSION\n", "source": [
"output['Subscription ID'] = ws.subscription_id\n", "### Training Data"
"output['Workspace Name'] = ws.name\n", ]
"output['Resource Group'] = ws.resource_group\n", },
"output['Location'] = ws.location\n", {
"output['Project Directory'] = project_folder\n", "cell_type": "code",
"output['Experiment Name'] = experiment.name\n", "execution_count": null,
"pd.set_option('display.max_colwidth', -1)\n", "metadata": {},
"outputDf = pd.DataFrame(data = output, index = [''])\n", "outputs": [],
"outputDf.T" "source": [
], "train_data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_train.csv\"\n",
"cell_type": "code" "train_dataset = Dataset.Tabular.from_delimited_files(train_data)\n",
}, "X_train = train_dataset.drop_columns(columns=['y']).to_pandas_dataframe()\n",
{ "y_train = train_dataset.keep_columns(columns=['y'], validate=True).to_pandas_dataframe()"
"metadata": {}, ]
"source": [ },
"## Data" {
], "cell_type": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "### Test Data"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "code",
"from sklearn import datasets\n", "execution_count": null,
"\n", "metadata": {},
"iris = datasets.load_iris()\n", "outputs": [],
"y = iris.target\n", "source": [
"X = iris.data\n", "test_data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_test.csv\"\n",
"\n", "test_dataset = Dataset.Tabular.from_delimited_files(test_data)\n",
"features = iris.feature_names\n", "X_test = test_dataset.drop_columns(columns=['y']).to_pandas_dataframe()\n",
"\n", "y_test = test_dataset.keep_columns(columns=['y'], validate=True).to_pandas_dataframe()"
"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", "cell_type": "markdown",
" random_state=100,\n", "metadata": {},
" stratify=y)\n", "source": [
"\n", "## Train\n",
"X_train = pd.DataFrame(X_train, columns=features)\n", "\n",
"X_test = pd.DataFrame(X_test, columns=features)" "Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
], "\n",
"cell_type": "code" "|Property|Description|\n",
}, "|-|-|\n",
{ "|**task**|classification or regression|\n",
"metadata": {}, "|**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",
"source": [ "|**max_time_sec**|Time limit in minutes for each iterations|\n",
"## Train\n", "|**iterations**|Number of iterations. In each iteration Auto ML trains the data with a specific pipeline|\n",
"\n", "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n", "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"\n", "|**model_explainability**|Indicate to explain each trained pipeline or not |"
"|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", "cell_type": "code",
"|**max_time_sec**|Time limit in minutes for each iterations|\n", "execution_count": null,
"|**iterations**|Number of iterations. In each iteration Auto ML trains the data with a specific pipeline|\n", "metadata": {},
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "outputs": [],
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "source": [
"|**X_valid**|(sparse) array-like, shape = [n_samples, n_features]|\n", "automl_config = AutoMLConfig(task = 'classification',\n",
"|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", " debug_log = 'automl_errors.log',\n",
"|**model_explainability**|Indicate to explain each trained pipeline or not |\n", " primary_metric = 'AUC_weighted',\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. |" " iteration_timeout_minutes = 200,\n",
], " iterations = 10,\n",
"cell_type": "markdown" " verbosity = logging.INFO,\n",
}, " preprocess = True,\n",
{ " X = X_train, \n",
"metadata": {}, " y = y_train,\n",
"outputs": [], " n_cross_validations = 5,\n",
"execution_count": null, " model_explainability=True)"
"source": [ ]
"automl_config = AutoMLConfig(task = 'classification',\n", },
" debug_log = 'automl_errors.log',\n", {
" primary_metric = 'AUC_weighted',\n", "cell_type": "markdown",
" iteration_timeout_minutes = 200,\n", "metadata": {},
" iterations = 10,\n", "source": [
" verbosity = logging.INFO,\n", "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",
" X = X_train, \n", "You will see the currently running iterations printing to the console."
" y = y_train,\n", ]
" X_valid = X_test,\n", },
" y_valid = y_test,\n", {
" model_explainability=True,\n", "cell_type": "code",
" path=project_folder)" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "local_run = experiment.submit(automl_config, show_output=True)"
"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,
"cell_type": "markdown" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "local_run"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"local_run = experiment.submit(automl_config, show_output=True)" "cell_type": "markdown",
], "metadata": {},
"cell_type": "code" "source": [
}, "## Results"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "markdown",
"source": [ "metadata": {},
"local_run" "source": [
], "### Widget for monitoring runs\n",
"cell_type": "code" "\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",
"metadata": {}, "NOTE: The widget displays a link at the bottom. This links to a web-ui to explore the individual run details."
"source": [ ]
"## Results" },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "source": [
"### Widget for monitoring runs\n", "from azureml.widgets import RunDetails\n",
"\n", "RunDetails(local_run).show() "
"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": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "### Retrieve the Best Model\n",
"metadata": {}, "\n",
"outputs": [], "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*."
"execution_count": null, ]
"source": [ },
"from azureml.widgets import RunDetails\n", {
"RunDetails(local_run).show() " "cell_type": "code",
], "execution_count": null,
"cell_type": "code" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "best_run, fitted_model = local_run.get_output()\n",
"source": [ "print(best_run)\n",
"### Retrieve the Best Model\n", "print(fitted_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*." },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "### Best Model 's explanation\n",
"outputs": [], "\n",
"execution_count": null, "Retrieve the explanation from the *best_run* which includes explanations for engineered features and raw features."
"source": [ ]
"best_run, fitted_model = local_run.get_output()\n", },
"print(best_run)\n", {
"print(fitted_model)" "cell_type": "markdown",
], "metadata": {},
"cell_type": "code" "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*."
"metadata": {}, ]
"source": [ },
"### Best Model 's explanation\n", {
"\n", "cell_type": "code",
"Retrieve the explanation from the best_run. And explanation information includes:\n", "execution_count": null,
"\n", "metadata": {},
"1.\tshap_values: The explanation information generated by shap lib\n", "outputs": [],
"2.\texpected_values: The expected value of the model applied to set of X_train data.\n", "source": [
"3.\toverall_summary: The model level feature importance values sorted in descending order\n", "client = ExplanationClient.from_run(best_run)\n",
"4.\toverall_imp: The feature names sorted in the same order as in overall_summary\n", "engineered_explanations = client.download_model_explanation(raw=False)\n",
"5.\tper_class_summary: The class level feature importance values sorted in descending order. Only available for the classification case\n", "print(engineered_explanations.get_feature_importance_dict())"
"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": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "#### Download raw feature importance from artifact store\n",
"metadata": {}, "You can use *ExplanationClient* to download the raw feature explanations from the artifact store of the *best_run*."
"outputs": [], ]
"execution_count": null, },
"source": [ {
"from azureml.train.automl.automlexplainer import retrieve_model_explanation\n", "cell_type": "code",
"\n", "execution_count": null,
"shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \\\n", "metadata": {},
" retrieve_model_explanation(best_run)" "outputs": [],
], "source": [
"cell_type": "code" "client = ExplanationClient.from_run(best_run)\n",
}, "raw_explanations = client.download_model_explanation(raw=True)\n",
{ "print(raw_explanations.get_feature_importance_dict())"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "markdown",
"print(overall_summary)\n", "metadata": {},
"print(overall_imp)" "source": [
], "## Explanations\n",
"cell_type": "code" "In this section, we will show how to compute model explanations and visualize the explanations using azureml-explain-model package. 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 and raw feature importance based on your test data. "
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "markdown",
"execution_count": null, "metadata": {},
"source": [ "source": [
"print(per_class_summary)\n", "#### Retrieve any other AutoML model from training"
"print(per_class_imp)" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"Beside retrieve the existed model explanation information, explain the model with different train/test data" "source": [
], "automl_run, fitted_model = local_run.get_output(iteration=0)"
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "#### Setup the model explanations for AutoML models\n",
"from azureml.train.automl.automlexplainer import explain_model\n", "The *fitted_model* can generate the following which will be used for getting the engineered and raw feature explanations using *automl_setup_model_explanations*:-\n",
"\n", "1. Featurized data from train samples/test samples \n",
"shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \\\n", "2. Gather engineered and raw feature name lists\n",
" explain_model(fitted_model, X_train, X_test, features=features)" "3. Find the classes in your labeled column in classification scenarios\n",
], "\n",
"cell_type": "code" "The *automl_explainer_setup_obj* contains all the structures from above list. "
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "code",
"execution_count": null, "execution_count": null,
"source": [ "metadata": {},
"print(overall_summary)\n", "outputs": [],
"print(overall_imp)" "source": [
], "from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations\n",
"cell_type": "code" "\n",
} "automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, X=X_train, \n",
], " X_test=X_test, y=y_train, \n",
"nbformat_minor": 2 " 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.explain.model* package. The *MimicWrapper* can be initialized with fields in *automl_explainer_setup_obj*, your workspace and a LightGBM model which acts as a surrogate model to explain the AutoML model (*fitted_model* here). The *MimicWrapper* also takes the *automl_run* object where the raw and engineered explanations will be uploaded."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.explain.model.mimic.models.lightgbm_model import LGBMExplainableModel\n",
"from azureml.explain.model.mimic_wrapper import MimicWrapper\n",
"explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator, LGBMExplainableModel, \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)"
]
},
{
"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 *ExplanationDashboard* to view the dash board visualization of the feature importance values of the generated engineered features by AutoML featurizers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"engineered_explanations = explainer.explain(['local', 'global'], eval_dataset=automl_explainer_setup_obj.X_test_transform)\n",
"print(engineered_explanations.get_feature_importance_dict())\n",
"from azureml.contrib.interpret.visualize import ExplanationDashboard\n",
"ExplanationDashboard(engineered_explanations, automl_explainer_setup_obj.automl_estimator, automl_explainer_setup_obj.X_test_transform)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Use Mimic Explainer for computing and visualizing raw feature importance\n",
"The *explain()* method in *MimicWrapper* can be again called with the transformed test samples and setting *get_raw* to *True* to get the feature importance for the raw features. You can also use *ExplanationDashboard* 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 = explainer.explain(['local', 'global'], get_raw=True, \n",
" raw_feature_names=automl_explainer_setup_obj.raw_feature_names,\n",
" eval_dataset=automl_explainer_setup_obj.X_test_transform)\n",
"print(raw_explanations.get_feature_importance_dict())\n",
"from azureml.contrib.interpret.visualize import ExplanationDashboard\n",
"ExplanationDashboard(raw_explanations, automl_explainer_setup_obj.automl_pipeline, automl_explainer_setup_obj.X_test_raw)"
]
},
{
"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.explain.model* package to create the scoring explainer which will be used to compute the raw and engineered feature importances at the inference time. Note that, we initialize the scoring explainer with the *feature_map* that was computed previously. The *feature_map* will be used by the scoring explainer to return the raw feature importance.\n",
"\n",
"In the cell below, we pickle the scoring explainer and register the AutoML model and the scoring explainer with the Model Management Service."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.explain.model.scoring.scoring_explainer import TreeScoringExplainer, save\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\n",
"save(scoring_explainer, exist_ok=True)\n",
"\n",
"# 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",
"\n",
"# Register scoring explainer\n",
"automl_run.upload_file('scoring_explainer.pkl', 'scoring_explainer.pkl')\n",
"scoring_explainer_model = automl_run.register_model(model_name='scoring_explainer', model_path='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-explain-model*, *azureml-train-automl* and *azureml-defaults* packages. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.conda_dependencies import CondaDependencies \n",
"\n",
"azureml_pip_packages = [\n",
" 'azureml-explain-model', 'azureml-train-automl', 'azureml-defaults'\n",
"]\n",
" \n",
"\n",
"# specify CondaDependencies obj\n",
"myenv = CondaDependencies.create(conda_packages=['scikit-learn', 'pandas', 'numpy', 'py-xgboost<=0.80'],\n",
" pip_packages=azureml_pip_packages,\n",
" pin_sdk_version=True)\n",
"\n",
"with open(\"myenv.yml\",\"w\") as f:\n",
" f.write(myenv.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_local_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",
"\n",
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
" memory_gb=1, \n",
" tags={\"data\": \"Bank Marketing\", \n",
" \"method\" : \"local_explanation\"}, \n",
" description='Get local explanations for Bank marketing test data')\n",
"\n",
"inference_config = InferenceConfig(runtime= \"python\", \n",
" entry_script=\"score_local_explain.py\",\n",
" conda_file=\"myenv.yml\")\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",
" # 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()"
]
}
],
"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.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
} }

View File

@@ -1,9 +1,11 @@
name: auto-ml-model-explanation name: auto-ml-model-explanation
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-train-automl
- matplotlib - azureml-widgets
- pandas_ml - matplotlib
- azureml-explain-model - pandas_ml
- azureml-explain-model
- azureml-contrib-interpret

View File

@@ -0,0 +1,42 @@
import json
import numpy as np
import pandas as pd
import os
import pickle
import azureml.train.automl
import azureml.explain.model
from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations
from sklearn.externals import joblib
from azureml.core.model import Model
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='classification')
# 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}

View File

@@ -1,8 +1,12 @@
name: auto-ml-regression-concrete-strength name: auto-ml-regression-concrete-strength
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-defaults
- matplotlib - azureml-explain-model
- pandas_ml - azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml
- azureml-dataprep[pandas]

View File

@@ -1,8 +1,12 @@
name: auto-ml-regression-hardware-performance name: auto-ml-regression-hardware-performance
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-defaults
- matplotlib - azureml-explain-model
- pandas_ml - azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml
- azureml-dataprep[pandas]

View File

@@ -1,407 +1,403 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Regression with Local Compute**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Results](#Results)\n",
"\n", "1. [Test](#Test)\n"
"Licensed under the MIT License." ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "## Introduction\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.png)" "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",
], "\n",
"cell_type": "markdown" "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
}, "\n",
{ "In this notebook you will learn how to:\n",
"metadata": {}, "1. Create an `Experiment` in an existing `Workspace`.\n",
"source": [ "2. Configure AutoML using `AutoMLConfig`.\n",
"# Automated Machine Learning\n", "3. Train the model using local compute.\n",
"_**Regression with Local Compute**_\n", "4. Explore the results.\n",
"\n", "5. Test the best fitted model."
"## Contents\n", ]
"1. [Introduction](#Introduction)\n", },
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "cell_type": "markdown",
"1. [Train](#Train)\n", "metadata": {},
"1. [Results](#Results)\n", "source": [
"1. [Test](#Test)\n" "## Setup\n",
], "\n",
"cell_type": "markdown" "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."
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"## Introduction\n", "execution_count": null,
"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", "metadata": {},
"\n", "outputs": [],
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "source": [
"\n", "import logging\n",
"In this notebook you will learn how to:\n", "\n",
"1. Create an `Experiment` in an existing `Workspace`.\n", "from matplotlib import pyplot as plt\n",
"2. Configure AutoML using `AutoMLConfig`.\n", "import numpy as np\n",
"3. Train the model using local compute.\n", "import pandas as pd\n",
"4. Explore the results.\n", "\n",
"5. Test the best fitted model." "import azureml.core\n",
], "from azureml.core.experiment import Experiment\n",
"cell_type": "markdown" "from azureml.core.workspace import Workspace\n",
}, "from azureml.train.automl import AutoMLConfig"
{ ]
"metadata": {}, },
"source": [ {
"## Setup\n", "cell_type": "code",
"\n", "execution_count": null,
"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." "metadata": {},
], "outputs": [],
"cell_type": "markdown" "source": [
}, "ws = Workspace.from_config()\n",
{ "\n",
"metadata": {}, "# Choose a name for the experiment.\n",
"outputs": [], "experiment_name = 'automl-local-regression'\n",
"execution_count": null, "\n",
"source": [ "experiment = Experiment(ws, experiment_name)\n",
"import logging\n", "\n",
"\n", "output = {}\n",
"from matplotlib import pyplot as plt\n", "output['SDK version'] = azureml.core.VERSION\n",
"import numpy as np\n", "output['Subscription ID'] = ws.subscription_id\n",
"import pandas as pd\n", "output['Workspace Name'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"import azureml.core\n", "output['Location'] = ws.location\n",
"from azureml.core.experiment import Experiment\n", "output['Experiment Name'] = experiment.name\n",
"from azureml.core.workspace import Workspace\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.train.automl import AutoMLConfig" "outputDf = pd.DataFrame(data = output, index = [''])\n",
], "outputDf.T"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "## Data\n",
"ws = Workspace.from_config()\n", "This uses scikit-learn's [load_diabetes](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html) method."
"\n", ]
"# Choose a name for the experiment and specify the project folder.\n", },
"experiment_name = 'automl-local-regression'\n", {
"project_folder = './sample_projects/automl-local-regression'\n", "cell_type": "code",
"\n", "execution_count": null,
"experiment = Experiment(ws, experiment_name)\n", "metadata": {},
"\n", "outputs": [],
"output = {}\n", "source": [
"output['SDK version'] = azureml.core.VERSION\n", "# Load the diabetes dataset, a well-known built-in small dataset that comes with scikit-learn.\n",
"output['Subscription ID'] = ws.subscription_id\n", "from sklearn.datasets import load_diabetes\n",
"output['Workspace Name'] = ws.name\n", "from sklearn.model_selection import train_test_split\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "X, y = load_diabetes(return_X_y = True)\n",
"output['Project Directory'] = project_folder\n", "\n",
"output['Experiment Name'] = experiment.name\n", "columns = ['age', 'gender', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n",
"pd.set_option('display.max_colwidth', -1)\n", "\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"
"outputDf.T" ]
], },
"cell_type": "code" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "## Train\n",
"## Data\n", "\n",
"This uses scikit-learn's [load_diabetes](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html) method." "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
], "\n",
"cell_type": "markdown" "|Property|Description|\n",
}, "|-|-|\n",
{ "|**task**|classification or regression|\n",
"metadata": {}, "|**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",
"outputs": [], "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
"execution_count": null, "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"source": [ "|**n_cross_validations**|Number of cross validation splits.|\n",
"# Load the diabetes dataset, a well-known built-in small dataset that comes with scikit-learn.\n", "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"from sklearn.datasets import load_diabetes\n", "|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|"
"from sklearn.model_selection import train_test_split\n", ]
"\n", },
"X, y = load_diabetes(return_X_y = True)\n", {
"\n", "cell_type": "code",
"columns = ['age', 'gender', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n", "execution_count": null,
"\n", "metadata": {},
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)" "outputs": [],
], "source": [
"cell_type": "code" "automl_config = AutoMLConfig(task = 'regression',\n",
}, " iteration_timeout_minutes = 10,\n",
{ " iterations = 10,\n",
"metadata": {}, " primary_metric = 'spearman_correlation',\n",
"source": [ " n_cross_validations = 5,\n",
"## Train\n", " debug_log = 'automl.log',\n",
"\n", " verbosity = logging.INFO,\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", " X = X_train, \n",
"\n", " y = y_train)"
"|Property|Description|\n", ]
"|-|-|\n", },
"|**task**|classification or regression|\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", "cell_type": "markdown",
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "metadata": {},
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", "source": [
"|**n_cross_validations**|Number of cross validation splits.|\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.\n",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "In this example, we specify `show_output = True` to print currently running iterations to the console."
"|**y**|(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.|" },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "local_run = experiment.submit(automl_config, show_output = True)"
"source": [ ]
"automl_config = AutoMLConfig(task = 'regression',\n", },
" iteration_timeout_minutes = 10,\n", {
" iterations = 10,\n", "cell_type": "code",
" primary_metric = 'spearman_correlation',\n", "execution_count": null,
" n_cross_validations = 5,\n", "metadata": {},
" debug_log = 'automl.log',\n", "outputs": [],
" verbosity = logging.INFO,\n", "source": [
" X = X_train, \n", "local_run"
" y = y_train,\n", ]
" path = project_folder)" },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Results"
"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": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "#### Widget for Monitoring Runs\n",
"metadata": {}, "\n",
"outputs": [], "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",
"execution_count": null, "\n",
"source": [ "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"local_run = experiment.submit(automl_config, show_output = True)" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "from azureml.widgets import RunDetails\n",
"local_run" "RunDetails(local_run).show() "
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Results" "\n",
], "#### Retrieve All Child Runs\n",
"cell_type": "markdown" "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"#### Widget for Monitoring Runs\n", "execution_count": null,
"\n", "metadata": {},
"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", "outputs": [],
"\n", "source": [
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "children = list(local_run.get_children())\n",
], "metricslist = {}\n",
"cell_type": "markdown" "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",
"metadata": {}, " metricslist[int(properties['iteration'])] = metrics\n",
"outputs": [], "\n",
"execution_count": null, "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"source": [ "rundata"
"from azureml.widgets import RunDetails\n", ]
"RunDetails(local_run).show() " },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "### Retrieve the Best Model\n",
"source": [ "\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 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": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "best_run, fitted_model = local_run.get_output()\n",
"source": [ "print(best_run)\n",
"children = list(local_run.get_children())\n", "print(fitted_model)"
"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", "cell_type": "markdown",
" metricslist[int(properties['iteration'])] = metrics\n", "metadata": {},
"\n", "source": [
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "#### Best Model Based on Any Other Metric\n",
"rundata" "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" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"### Retrieve the Best Model\n", "outputs": [],
"\n", "source": [
"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*." "lookup_metric = \"root_mean_squared_error\"\n",
], "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
"cell_type": "markdown" "print(best_run)\n",
}, "print(fitted_model)"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "markdown",
"source": [ "metadata": {},
"best_run, fitted_model = local_run.get_output()\n", "source": [
"print(best_run)\n", "#### Model from a Specific Iteration\n",
"print(fitted_model)" "Show the run and the model from the third iteration:"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"#### Best Model Based on Any Other Metric\n", "outputs": [],
"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):" "source": [
], "iteration = 3\n",
"cell_type": "markdown" "third_run, third_model = local_run.get_output(iteration = iteration)\n",
}, "print(third_run)\n",
{ "print(third_model)"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "markdown",
"lookup_metric = \"root_mean_squared_error\"\n", "metadata": {},
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", "source": [
"print(best_run)\n", "## Test"
"print(fitted_model)" ]
], },
"cell_type": "code" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "Predict on training and test set, and calculate residual values."
"#### Model from a Specific Iteration\n", ]
"Show the run and the model from the third iteration:" },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "y_pred_train = fitted_model.predict(X_train)\n",
"source": [ "y_residual_train = y_train - y_pred_train\n",
"iteration = 3\n", "\n",
"third_run, third_model = local_run.get_output(iteration = iteration)\n", "y_pred_test = fitted_model.predict(X_test)\n",
"print(third_run)\n", "y_residual_test = y_test - y_pred_test"
"print(third_model)" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"## Test" "source": [
], "%matplotlib inline\n",
"cell_type": "markdown" "from sklearn.metrics import mean_squared_error, r2_score\n",
}, "\n",
{ "# Set up a multi-plot chart.\n",
"metadata": {}, "f, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})\n",
"source": [ "f.suptitle('Regression Residual Values', fontsize = 18)\n",
"Predict on training and test set, and calculate residual values." "f.set_figheight(6)\n",
], "f.set_figwidth(16)\n",
"cell_type": "markdown" "\n",
}, "# Plot residual values of training set.\n",
{ "a0.axis([0, 360, -200, 200])\n",
"metadata": {}, "a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
"outputs": [], "a0.plot([-10,360],[0,0], 'r-', lw = 3)\n",
"execution_count": null, "a0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\n",
"source": [ "a0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)), fontsize = 12)\n",
"y_pred_train = fitted_model.predict(X_train)\n", "a0.set_xlabel('Training samples', fontsize = 12)\n",
"y_residual_train = y_train - y_pred_train\n", "a0.set_ylabel('Residual Values', fontsize = 12)\n",
"\n", "\n",
"y_pred_test = fitted_model.predict(X_test)\n", "# Plot a histogram.\n",
"y_residual_test = y_test - y_pred_test" "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",
"cell_type": "code" "\n",
}, "# Plot residual values of test set.\n",
{ "a1.axis([0, 90, -200, 200])\n",
"metadata": {}, "a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
"outputs": [], "a1.plot([-10,360],[0,0], 'r-', lw = 3)\n",
"execution_count": null, "a1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\n",
"source": [ "a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)), fontsize = 12)\n",
"%matplotlib inline\n", "a1.set_xlabel('Test samples', fontsize = 12)\n",
"from sklearn.metrics import mean_squared_error, r2_score\n", "a1.set_yticklabels([])\n",
"\n", "\n",
"# Set up a multi-plot chart.\n", "# Plot a histogram.\n",
"f, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})\n", "a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n",
"f.suptitle('Regression Residual Values', fontsize = 18)\n", "a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n",
"f.set_figheight(6)\n", "\n",
"f.set_figwidth(16)\n", "plt.show()"
"\n", ]
"# Plot residual values of training set.\n", }
"a0.axis([0, 360, -200, 200])\n", ],
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n", "metadata": {
"a0.plot([-10,360],[0,0], 'r-', lw = 3)\n", "authors": [
"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", "name": "savitam"
"a0.set_xlabel('Training samples', fontsize = 12)\n", }
"a0.set_ylabel('Residual Values', fontsize = 12)\n", ],
"\n", "kernelspec": {
"# Plot a histogram.\n", "display_name": "Python 3.6",
"a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n", "language": "python",
"a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n", "name": "python36"
"\n", },
"# Plot residual values of test set.\n", "language_info": {
"a1.axis([0, 90, -200, 200])\n", "codemirror_mode": {
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n", "name": "ipython",
"a1.plot([-10,360],[0,0], 'r-', lw = 3)\n", "version": 3
"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", "file_extension": ".py",
"a1.set_xlabel('Test samples', fontsize = 12)\n", "mimetype": "text/x-python",
"a1.set_yticklabels([])\n", "name": "python",
"\n", "nbconvert_exporter": "python",
"# Plot a histogram.\n", "pygments_lexer": "ipython3",
"a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n", "version": "3.6.6"
"a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n", }
"\n", },
"plt.show()" "nbformat": 4,
], "nbformat_minor": 2
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,9 +1,9 @@
name: auto-ml-regression name: auto-ml-regression
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- paramiko<2.5.0 - paramiko<2.5.0

View File

@@ -0,0 +1,542 @@
{
"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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/remote-amlcompute/auto-ml-remote-amlcompute.png)"
]
},
{
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"In this example we use the scikit-learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) 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 with ONNX compatible config on.\n",
"5. Explore the results and save the ONNX model.\n",
"6. Inference with the ONNX 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",
"\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.core.dataset import Dataset\n",
"from azureml.train.automl import AutoMLConfig"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ws = Workspace.from_config()\n",
"\n",
"# Choose an experiment name.\n",
"experiment_name = 'automl-remote-amlcompute-with-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['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 = \"automlc2\"\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",
"print('Checking cluster status...')\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_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"iris = datasets.load_iris()\n",
"\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)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Ensure the x_train and x_test are pandas DataFrame."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 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'])\n",
"y_train = pd.DataFrame(y_train, columns=['label'])\n",
"\n",
"if not os.path.isdir('data'):\n",
" os.mkdir('data')\n",
"\n",
"X_train.to_csv(\"data/X_train.csv\", index=False)\n",
"y_train.to_csv(\"data/y_train.csv\", index=False)\n",
"\n",
"ds = ws.get_default_datastore()\n",
"ds.upload(src_dir='./data', target_path='irisdata', overwrite=True, show_progress=True)"
]
},
{
"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",
"cd = CondaDependencies.create(conda_packages=['numpy','py-xgboost<=0.80'])\n",
"conda_run_config.environment.python.conda_dependencies = cd"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Creating a TabularDataset\n",
"\n",
"Defined X and y as `TabularDataset`s, which are passed to automated machine learning in the AutoMLConfig."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X = Dataset.Tabular.from_delimited_files(path=ds.path('irisdata/X_train.csv'))\n",
"y = Dataset.Tabular.from_delimited_files(path=ds.path('irisdata/y_train.csv'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train\n",
"\n",
"You can specify `automl_settings` as `**kwargs` as well. \n",
"\n",
"**Note:** 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",
"**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 nodes in the AmlCompute cluster.|\n",
"|**enable_onnx_compatible_models**|Enable the ONNX compatible models in the experiment.|"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set the preprocess=True, currently the InferenceHelper only supports this mode."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"automl_settings = {\n",
" \"iteration_timeout_minutes\": 10,\n",
" \"iterations\": 10,\n",
" \"n_cross_validations\": 5,\n",
" \"primary_metric\": 'AUC_weighted',\n",
" \"preprocess\": True,\n",
" \"max_concurrent_iterations\": 5,\n",
" \"verbosity\": logging.INFO\n",
"}\n",
"\n",
"automl_config = AutoMLConfig(task = 'classification',\n",
" debug_log = 'automl_errors.log',\n",
" run_configuration=conda_run_config,\n",
" X = X,\n",
" y = y,\n",
" enable_onnx_compatible_models=True, # This will generate ONNX compatible models.\n",
" **automl_settings\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": [
"### 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 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.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",
"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",
"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 = '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",
" return json.load(f)\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 or 3.7 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
}

View File

@@ -0,0 +1,12 @@
name: auto-ml-remote-amlcompute-with-onnx
dependencies:
- pip:
- azureml-sdk
- interpret
- azureml-defaults
- azureml-explain-model
- azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml
- onnxruntime

View File

@@ -1,8 +1,11 @@
name: auto-ml-remote-amlcompute name: auto-ml-remote-amlcompute
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - interpret
- azureml-widgets - azureml-defaults
- matplotlib - azureml-explain-model
- pandas_ml - azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml

View File

@@ -1,247 +1,242 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sample-weight/auto-ml-sample-weight.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.5" "# Automated Machine Learning\n",
} "_**Sample Weight**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Train](#Train)\n",
"source": [ "1. [Test](#Test)\n"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", ]
"\n", },
"Licensed under the MIT License." {
], "cell_type": "markdown",
"cell_type": "markdown" "metadata": {},
}, "source": [
{ "## Introduction\n",
"metadata": {}, "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",
"source": [ "\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sample-weight/auto-ml-sample-weight.png)" "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
], "\n",
"cell_type": "markdown" "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."
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "markdown",
"# Automated Machine Learning\n", "metadata": {},
"_**Sample Weight**_\n", "source": [
"\n", "## Setup\n",
"## Contents\n", "\n",
"1. [Introduction](#Introduction)\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."
"1. [Setup](#Setup)\n", ]
"1. [Train](#Train)\n", },
"1. [Test](#Test)\n" {
], "cell_type": "code",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "import logging\n",
"## 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 sample weight with AutoML. Sample weight is used where some sample values are more important than others.\n", "from matplotlib import pyplot as plt\n",
"\n", "import numpy as np\n",
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "import pandas as pd\n",
"\n", "from sklearn import datasets\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." "\n",
], "import azureml.core\n",
"cell_type": "markdown" "from azureml.core.experiment import Experiment\n",
}, "from azureml.core.workspace import Workspace\n",
{ "from azureml.train.automl import AutoMLConfig"
"metadata": {}, ]
"source": [ },
"## Setup\n", {
"\n", "cell_type": "code",
"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." "execution_count": null,
], "metadata": {},
"cell_type": "markdown" "outputs": [],
}, "source": [
{ "ws = Workspace.from_config()\n",
"metadata": {}, "\n",
"outputs": [], "# Choose names for the regular and the sample weight experiments.\n",
"execution_count": null, "experiment_name = 'non_sample_weight_experiment'\n",
"source": [ "sample_weight_experiment_name = 'sample_weight_experiment'\n",
"import logging\n", "\n",
"\n", "experiment = Experiment(ws, experiment_name)\n",
"from matplotlib import pyplot as plt\n", "sample_weight_experiment=Experiment(ws, sample_weight_experiment_name)\n",
"import numpy as np\n", "\n",
"import pandas as pd\n", "output = {}\n",
"from sklearn import datasets\n", "output['SDK version'] = azureml.core.VERSION\n",
"\n", "output['Subscription ID'] = ws.subscription_id\n",
"import azureml.core\n", "output['Workspace Name'] = ws.name\n",
"from azureml.core.experiment import Experiment\n", "output['Resource Group'] = ws.resource_group\n",
"from azureml.core.workspace import Workspace\n", "output['Location'] = ws.location\n",
"from azureml.train.automl import AutoMLConfig" "output['Experiment Name'] = experiment.name\n",
], "pd.set_option('display.max_colwidth', -1)\n",
"cell_type": "code" "outputDf = pd.DataFrame(data = output, index = [''])\n",
}, "outputDf.T"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "markdown",
"source": [ "metadata": {},
"ws = Workspace.from_config()\n", "source": [
"\n", "## Train\n",
"# Choose names for the regular and the sample weight experiments.\n", "\n",
"experiment_name = 'non_sample_weight_experiment'\n", "Instantiate two `AutoMLConfig` objects. One will be used with `sample_weight` and one without."
"sample_weight_experiment_name = 'sample_weight_experiment'\n", ]
"\n", },
"project_folder = './sample_projects/sample_weight'\n", {
"\n", "cell_type": "code",
"experiment = Experiment(ws, experiment_name)\n", "execution_count": null,
"sample_weight_experiment=Experiment(ws, sample_weight_experiment_name)\n", "metadata": {},
"\n", "outputs": [],
"output = {}\n", "source": [
"output['SDK version'] = azureml.core.VERSION\n", "digits = datasets.load_digits()\n",
"output['Subscription ID'] = ws.subscription_id\n", "X_train = digits.data[100:,:]\n",
"output['Workspace Name'] = ws.name\n", "y_train = digits.target[100:]\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "# The example makes the sample weight 0.9 for the digit 4 and 0.1 for all other digits.\n",
"output['Project Directory'] = project_folder\n", "# This makes the model more likely to classify as 4 if the image it not clear.\n",
"output['Experiment Name'] = experiment.name\n", "sample_weight = np.array([(0.9 if x == 4 else 0.01) for x in y_train])\n",
"pd.set_option('display.max_colwidth', -1)\n", "\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "automl_classifier = AutoMLConfig(task = 'classification',\n",
"outputDf.T" " debug_log = 'automl_errors.log',\n",
], " primary_metric = 'AUC_weighted',\n",
"cell_type": "code" " iteration_timeout_minutes = 60,\n",
}, " iterations = 10,\n",
{ " n_cross_validations = 2,\n",
"metadata": {}, " verbosity = logging.INFO,\n",
"source": [ " X = X_train, \n",
"## Train\n", " y = y_train)\n",
"\n", "\n",
"Instantiate two `AutoMLConfig` objects. One will be used with `sample_weight` and one without." "automl_sample_weight = AutoMLConfig(task = 'classification',\n",
], " debug_log = 'automl_errors.log',\n",
"cell_type": "markdown" " primary_metric = 'AUC_weighted',\n",
}, " iteration_timeout_minutes = 60,\n",
{ " iterations = 10,\n",
"metadata": {}, " n_cross_validations = 2,\n",
"outputs": [], " verbosity = logging.INFO,\n",
"execution_count": null, " X = X_train, \n",
"source": [ " y = y_train,\n",
"digits = datasets.load_digits()\n", " sample_weight = sample_weight)"
"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", "cell_type": "markdown",
"# This makes the model more likely to classify as 4 if the image it not clear.\n", "metadata": {},
"sample_weight = np.array([(0.9 if x == 4 else 0.01) for x in y_train])\n", "source": [
"\n", "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",
"automl_classifier = AutoMLConfig(task = 'classification',\n", "In this example, we specify `show_output = True` to print currently running iterations to the console."
" debug_log = 'automl_errors.log',\n", ]
" primary_metric = 'AUC_weighted',\n", },
" iteration_timeout_minutes = 60,\n", {
" iterations = 10,\n", "cell_type": "code",
" n_cross_validations = 2,\n", "execution_count": null,
" verbosity = logging.INFO,\n", "metadata": {},
" X = X_train, \n", "outputs": [],
" y = y_train,\n", "source": [
" path = project_folder)\n", "local_run = experiment.submit(automl_classifier, show_output = True)\n",
"\n", "sample_weight_run = sample_weight_experiment.submit(automl_sample_weight, show_output = True)\n",
"automl_sample_weight = AutoMLConfig(task = 'classification',\n", "\n",
" debug_log = 'automl_errors.log',\n", "best_run, fitted_model = local_run.get_output()\n",
" primary_metric = 'AUC_weighted',\n", "best_run_sample_weight, fitted_model_sample_weight = sample_weight_run.get_output()"
" iteration_timeout_minutes = 60,\n", ]
" iterations = 10,\n", },
" n_cross_validations = 2,\n", {
" verbosity = logging.INFO,\n", "cell_type": "markdown",
" X = X_train, \n", "metadata": {},
" y = y_train,\n", "source": [
" sample_weight = sample_weight,\n", "## Test\n",
" path = project_folder)" "\n",
], "#### Load Test Data"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"source": [ "execution_count": null,
"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", "metadata": {},
"In this example, we specify `show_output = True` to print currently running iterations to the console." "outputs": [],
], "source": [
"cell_type": "markdown" "digits = datasets.load_digits()\n",
}, "X_test = digits.data[:100, :]\n",
{ "y_test = digits.target[:100]\n",
"metadata": {}, "images = digits.images[:100]"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"local_run = experiment.submit(automl_classifier, show_output = True)\n", "cell_type": "markdown",
"sample_weight_run = sample_weight_experiment.submit(automl_sample_weight, show_output = True)\n", "metadata": {},
"\n", "source": [
"best_run, fitted_model = local_run.get_output()\n", "#### Compare the Models\n",
"best_run_sample_weight, fitted_model_sample_weight = sample_weight_run.get_output()" "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" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"## Test\n", "outputs": [],
"\n", "source": [
"#### Load Test Data" "# Randomly select digits and test.\n",
], "for index in range(0,len(y_test)):\n",
"cell_type": "markdown" " 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",
"metadata": {}, " if predicted == 4 or predicted_sample_weight == 4 or label == 4:\n",
"outputs": [], " title = \"Label value = %d Predicted value = %d Prediced with sample weight = %d\" % (label, predicted, predicted_sample_weight)\n",
"execution_count": null, " fig = plt.figure(1, figsize=(3,3))\n",
"source": [ " ax1 = fig.add_axes((0,0,.8,.8))\n",
"digits = datasets.load_digits()\n", " ax1.set_title(title)\n",
"X_test = digits.data[:100, :]\n", " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
"y_test = digits.target[:100]\n", " plt.show()"
"images = digits.images[:100]" ]
], }
"cell_type": "code" ],
}, "metadata": {
{ "authors": [
"metadata": {}, {
"source": [ "name": "savitam"
"#### 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." ],
], "kernelspec": {
"cell_type": "markdown" "display_name": "Python 3.6",
}, "language": "python",
{ "name": "python36"
"metadata": {}, },
"outputs": [], "language_info": {
"execution_count": null, "codemirror_mode": {
"source": [ "name": "ipython",
"# Randomly select digits and test.\n", "version": 3
"for index in range(0,len(y_test)):\n", },
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", "file_extension": ".py",
" predicted_sample_weight = fitted_model_sample_weight.predict(X_test[index:index + 1])[0]\n", "mimetype": "text/x-python",
" label = y_test[index]\n", "name": "python",
" if predicted == 4 or predicted_sample_weight == 4 or label == 4:\n", "nbconvert_exporter": "python",
" title = \"Label value = %d Predicted value = %d Prediced with sample weight = %d\" % (label, predicted, predicted_sample_weight)\n", "pygments_lexer": "ipython3",
" fig = plt.figure(1, figsize=(3,3))\n", "version": "3.6.5"
" 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", "nbformat": 4,
" plt.show()" "nbformat_minor": 2
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-sample-weight name: auto-ml-sample-weight
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,387 +1,382 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "savitam" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sparse-data-train-test-split/auto-ml-sparse-data-train-test-split.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Train Test Split and Handling Sparse Data**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "1. [Results](#Results)\n",
"\n", "1. [Test](#Test)\n"
"Licensed under the MIT License." ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "## Introduction\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sparse-data-train-test-split/auto-ml-sparse-data-train-test-split.png)" "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",
"cell_type": "markdown" "\n",
}, "In this notebook you will learn how to:\n",
{ "1. Create an `Experiment` in an existing `Workspace`.\n",
"metadata": {}, "2. Configure AutoML using `AutoMLConfig`.\n",
"source": [ "4. Train the model.\n",
"# Automated Machine Learning\n", "5. Explore the results.\n",
"_**Train Test Split and Handling Sparse Data**_\n", "6. Test the best fitted model.\n",
"\n", "\n",
"## Contents\n", "In addition this notebook showcases the following features\n",
"1. [Introduction](#Introduction)\n", "- Explicit train test splits \n",
"1. [Setup](#Setup)\n", "- Handling **sparse data** in the input"
"1. [Data](#Data)\n", ]
"1. [Train](#Train)\n", },
"1. [Results](#Results)\n", {
"1. [Test](#Test)\n" "cell_type": "markdown",
], "metadata": {},
"cell_type": "markdown" "source": [
}, "## Setup\n",
{ "\n",
"metadata": {}, "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."
"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", "cell_type": "code",
"\n", "execution_count": null,
"In this notebook you will learn how to:\n", "metadata": {},
"1. Create an `Experiment` in an existing `Workspace`.\n", "outputs": [],
"2. Configure AutoML using `AutoMLConfig`.\n", "source": [
"4. Train the model.\n", "import logging\n",
"5. Explore the results.\n", "\n",
"6. Test the best fitted model.\n", "import pandas as pd\n",
"\n", "\n",
"In addition this notebook showcases the following features\n", "import azureml.core\n",
"- Explicit train test splits \n", "from azureml.core.experiment import Experiment\n",
"- Handling **sparse data** in the input" "from azureml.core.workspace import Workspace\n",
], "from azureml.train.automl import AutoMLConfig"
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"source": [ "execution_count": null,
"## Setup\n", "metadata": {},
"\n", "outputs": [],
"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." "source": [
], "ws = Workspace.from_config()\n",
"cell_type": "markdown" "\n",
}, "# choose a name for the experiment\n",
{ "experiment_name = 'sparse-data-train-test-split'\n",
"metadata": {}, "\n",
"outputs": [], "experiment = Experiment(ws, experiment_name)\n",
"execution_count": null, "\n",
"source": [ "output = {}\n",
"import logging\n", "output['SDK version'] = azureml.core.VERSION\n",
"\n", "output['Subscription ID'] = ws.subscription_id\n",
"import pandas as pd\n", "output['Workspace'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"import azureml.core\n", "output['Location'] = ws.location\n",
"from azureml.core.experiment import Experiment\n", "output['Experiment Name'] = experiment.name\n",
"from azureml.core.workspace import Workspace\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.train.automl import AutoMLConfig" "outputDf = pd.DataFrame(data = output, index = [''])\n",
], "outputDf.T"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"outputs": [], "metadata": {},
"execution_count": null, "source": [
"source": [ "## Data"
"ws = Workspace.from_config()\n", ]
"\n", },
"# choose a name for the experiment\n", {
"experiment_name = 'sparse-data-train-test-split'\n", "cell_type": "code",
"# project folder\n", "execution_count": null,
"project_folder = './sample_projects/sparse-data-train-test-split'\n", "metadata": {},
"\n", "outputs": [],
"experiment = Experiment(ws, experiment_name)\n", "source": [
"\n", "from sklearn.datasets import fetch_20newsgroups\n",
"output = {}\n", "from sklearn.feature_extraction.text import HashingVectorizer\n",
"output['SDK version'] = azureml.core.VERSION\n", "from sklearn.model_selection import train_test_split\n",
"output['Subscription ID'] = ws.subscription_id\n", "\n",
"output['Workspace'] = ws.name\n", "remove = ('headers', 'footers', 'quotes')\n",
"output['Resource Group'] = ws.resource_group\n", "categories = [\n",
"output['Location'] = ws.location\n", " 'alt.atheism',\n",
"output['Project Directory'] = project_folder\n", " 'talk.religion.misc',\n",
"output['Experiment Name'] = experiment.name\n", " 'comp.graphics',\n",
"pd.set_option('display.max_colwidth', -1)\n", " 'sci.space',\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "]\n",
"outputDf.T" "data_train = fetch_20newsgroups(subset = 'train', categories = categories,\n",
], " shuffle = True, random_state = 42,\n",
"cell_type": "code" " 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",
"metadata": {}, "\n",
"source": [ "\n",
"## Data" "vectorizer = HashingVectorizer(stop_words = 'english', alternate_sign = False,\n",
], " n_features = 2**16)\n",
"cell_type": "markdown" "X_train = vectorizer.transform(X_train)\n",
}, "X_valid = vectorizer.transform(X_valid)\n",
{ "\n",
"metadata": {}, "summary_df = pd.DataFrame(index = ['No of Samples', 'No of Features'])\n",
"outputs": [], "summary_df['Train Set'] = [X_train.shape[0], X_train.shape[1]]\n",
"execution_count": null, "summary_df['Validation Set'] = [X_valid.shape[0], X_valid.shape[1]]\n",
"source": [ "summary_df"
"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", "cell_type": "markdown",
"remove = ('headers', 'footers', 'quotes')\n", "metadata": {},
"categories = [\n", "source": [
" 'alt.atheism',\n", "## Train\n",
" 'talk.religion.misc',\n", "\n",
" 'comp.graphics',\n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
" 'sci.space',\n", "\n",
"]\n", "|Property|Description|\n",
"data_train = fetch_20newsgroups(subset = 'train', categories = categories,\n", "|-|-|\n",
" shuffle = True, random_state = 42,\n", "|**task**|classification or regression|\n",
" remove = remove)\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",
"\n", "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\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", "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"\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",
"\n", "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"vectorizer = HashingVectorizer(stop_words = 'english', alternate_sign = False,\n", "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
" n_features = 2**16)\n", "|**X_valid**|(sparse) array-like, shape = [n_samples, n_features] for the custom validation set.|\n",
"X_train = vectorizer.transform(X_train)\n", "|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|"
"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", "cell_type": "code",
"summary_df['Validation Set'] = [X_valid.shape[0], X_valid.shape[1]]\n", "execution_count": null,
"summary_df" "metadata": {},
], "outputs": [],
"cell_type": "code" "source": [
}, "automl_config = AutoMLConfig(task = 'classification',\n",
{ " debug_log = 'automl_errors.log',\n",
"metadata": {}, " primary_metric = 'AUC_weighted',\n",
"source": [ " iteration_timeout_minutes = 60,\n",
"## Train\n", " iterations = 5,\n",
"\n", " preprocess = False,\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", " verbosity = logging.INFO,\n",
"\n", " X = X_train, \n",
"|Property|Description|\n", " y = y_train,\n",
"|-|-|\n", " X_valid = X_valid, \n",
"|**task**|classification or regression|\n", " y_valid = y_valid)"
"|**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", "cell_type": "markdown",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "metadata": {},
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "source": [
"|**X_valid**|(sparse) array-like, shape = [n_samples, n_features] for the custom validation set.|\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.\n",
"|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "In this example, we specify `show_output = True` to print currently running iterations to the console."
"|**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": "markdown" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "local_run = experiment.submit(automl_config, show_output=True)"
"automl_config = AutoMLConfig(task = 'classification',\n", ]
" debug_log = 'automl_errors.log',\n", },
" primary_metric = 'AUC_weighted',\n", {
" iteration_timeout_minutes = 60,\n", "cell_type": "code",
" iterations = 5,\n", "execution_count": null,
" preprocess = False,\n", "metadata": {},
" verbosity = logging.INFO,\n", "outputs": [],
" X = X_train, \n", "source": [
" y = y_train,\n", "local_run"
" X_valid = X_valid, \n", ]
" y_valid = y_valid, \n", },
" path = project_folder)" {
], "cell_type": "markdown",
"cell_type": "code" "metadata": {},
}, "source": [
{ "## Results"
"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": "markdown",
], "metadata": {},
"cell_type": "markdown" "source": [
}, "#### Widget for Monitoring Runs\n",
{ "\n",
"metadata": {}, "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",
"outputs": [], "\n",
"execution_count": null, "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"source": [ ]
"local_run = experiment.submit(automl_config, show_output=True)" },
], {
"cell_type": "code" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "from azureml.widgets import RunDetails\n",
"source": [ "RunDetails(local_run).show() "
"local_run" ]
], },
"cell_type": "code" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "\n",
"## Results" "#### 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": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"source": [ "execution_count": null,
"#### Widget for Monitoring Runs\n", "metadata": {},
"\n", "outputs": [],
"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", "source": [
"\n", "children = list(local_run.get_children())\n",
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "metricslist = {}\n",
], "for run in children:\n",
"cell_type": "markdown" " 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",
"metadata": {}, " \n",
"outputs": [], "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"execution_count": null, "rundata"
"source": [ ]
"from azureml.widgets import RunDetails\n", },
"RunDetails(local_run).show() " {
], "cell_type": "markdown",
"cell_type": "code" "metadata": {},
}, "source": [
{ "### Retrieve the Best Model\n",
"metadata": {}, "\n",
"source": [ "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", ]
"#### 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",
"cell_type": "markdown" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "best_run, fitted_model = local_run.get_output()"
"execution_count": null, ]
"source": [ },
"children = list(local_run.get_children())\n", {
"metricslist = {}\n", "cell_type": "markdown",
"for run in children:\n", "metadata": {},
" properties = run.get_properties()\n", "source": [
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n", "#### Best Model Based on Any Other Metric\n",
" metricslist[int(properties['iteration'])] = metrics\n", "Show the run and the model which has the smallest `accuracy` value:"
" \n", ]
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", },
"rundata" {
], "cell_type": "code",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "# lookup_metric = \"accuracy\"\n",
"### Retrieve the Best Model\n", "# best_run, fitted_model = local_run.get_output(metric = lookup_metric)"
"\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": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "#### Model from a Specific Iteration\n",
"outputs": [], "Show the run and the model from the third iteration:"
"execution_count": null, ]
"source": [ },
"best_run, fitted_model = local_run.get_output()" {
], "cell_type": "code",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "# iteration = 3\n",
"#### Best Model Based on Any Other Metric\n", "# best_run, fitted_model = local_run.get_output(iteration = iteration)"
"Show the run and the model which has the smallest `accuracy` value:" ]
], },
"cell_type": "markdown" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"outputs": [], "## Test"
"execution_count": null, ]
"source": [ },
"# lookup_metric = \"accuracy\"\n", {
"# best_run, fitted_model = local_run.get_output(metric = lookup_metric)" "cell_type": "code",
], "execution_count": null,
"cell_type": "code" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "# Load test data.\n",
"source": [ "from pandas_ml import ConfusionMatrix\n",
"#### Model from a Specific Iteration\n", "\n",
"Show the run and the model from the third iteration:" "data_test = fetch_20newsgroups(subset = 'test', categories = categories,\n",
], " shuffle = True, random_state = 42,\n",
"cell_type": "markdown" " remove = remove)\n",
}, "\n",
{ "X_test = vectorizer.transform(data_test.data)\n",
"metadata": {}, "y_test = data_test.target\n",
"outputs": [], "\n",
"execution_count": null, "# Test our best pipeline.\n",
"source": [ "\n",
"# iteration = 3\n", "y_pred = fitted_model.predict(X_test)\n",
"# best_run, fitted_model = local_run.get_output(iteration = iteration)" "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",
"cell_type": "code" "\n",
}, "cm = ConfusionMatrix(y_test_strings, y_pred_strings)\n",
{ "print(cm)\n",
"metadata": {}, "cm.plot()"
"source": [ ]
"## Test" }
], ],
"cell_type": "markdown" "metadata": {
}, "authors": [
{ {
"metadata": {}, "name": "savitam"
"outputs": [], }
"execution_count": null, ],
"source": [ "kernelspec": {
"# Load test data.\n", "display_name": "Python 3.6",
"from pandas_ml import ConfusionMatrix\n", "language": "python",
"\n", "name": "python36"
"data_test = fetch_20newsgroups(subset = 'test', categories = categories,\n", },
" shuffle = True, random_state = 42,\n", "language_info": {
" remove = remove)\n", "codemirror_mode": {
"\n", "name": "ipython",
"X_test = vectorizer.transform(data_test.data)\n", "version": 3
"y_test = data_test.target\n", },
"\n", "file_extension": ".py",
"# Test our best pipeline.\n", "mimetype": "text/x-python",
"\n", "name": "python",
"y_pred = fitted_model.predict(X_test)\n", "nbconvert_exporter": "python",
"y_pred_strings = [data_test.target_names[i] for i in y_pred]\n", "pygments_lexer": "ipython3",
"y_test_strings = [data_test.target_names[i] for i in y_test]\n", "version": "3.6.6"
"\n", }
"cm = ConfusionMatrix(y_test_strings, y_pred_strings)\n", },
"print(cm)\n", "nbformat": 4,
"cm.plot()" "nbformat_minor": 2
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-sparse-data-train-test-split name: auto-ml-sparse-data-train-test-split
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,113 +1,113 @@
# Table of Contents # Table of Contents
1. [Introduction](#introduction) 1. [Introduction](#introduction)
1. [Setup using Azure Data Studio](#azuredatastudiosetup) 1. [Setup using Azure Data Studio](#azuredatastudiosetup)
1. [Energy demand example using Azure Data Studio](#azuredatastudioenergydemand) 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 2017 on Windows](#ssms2017)
1. [Set using SQL Server Management Studio for SQL Server 2019 on Linux](#ssms2019) 1. [Set using SQL Server Management Studio for SQL Server 2019 on Linux](#ssms2019)
1. [Energy demand example using SQL Server Management Studio](#ssmsenergydemand) 1. [Energy demand example using SQL Server Management Studio](#ssmsenergydemand)
<a name="introduction"></a> <a name="introduction"></a>
# Introduction # Introduction
SQL Server 2017 or 2019 can call Azure ML automated machine learning to create models trained on data from SQL Server. 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. 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. 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. 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 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. 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. These instructions show using it from Azure Data Studio or SQL Server Managment Studio.
<a name="azuredatastudiosetup"></a> <a name="azuredatastudiosetup"></a>
## Setup using Azure Data Studio ## Setup using Azure Data Studio
These step show setting up the integration 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. 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. 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. 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. 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. 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> <a name="azuredatastudioenergydemand"></a>
## Energy demand example using Azure Data Studio ## 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. 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. 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> <a name="ssms2017"></a>
## Setup using SQL Server Management Studio for SQL Server 2017 on Windows ## Setup using SQL Server Management Studio for SQL Server 2017 on Windows
These instruction setup the integration 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) 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: 2. Enable external scripts with the following commands:
```sh ```sh
sp_configure 'external scripts enabled',1 sp_configure 'external scripts enabled',1
reconfigure with override reconfigure with override
``` ```
3. Stop SQL Server. 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) 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 ```sh
cd "C:\Program Files\Microsoft SQL Server" cd "C:\Program Files\Microsoft SQL Server"
cd "MSSQL14.MSSQLSERVER\PYTHON_SERVICES" cd "MSSQL14.MSSQLSERVER\PYTHON_SERVICES"
python.exe -m pip install azureml-sdk[automl] python.exe -m pip install azureml-sdk[automl]
python.exe -m pip install --upgrade numpy python.exe -m pip install --upgrade numpy
python.exe -m pip install --upgrade sklearn python.exe -m pip install --upgrade sklearn
``` ```
5. Start SQL Server and the service "SQL Server Launchpad service". 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". 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 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) 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) 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: 10. Create an Azure service principal. You can do this with the commands:
```sh ```sh
az login az login
az account set --subscription subscriptionid az account set --subscription subscriptionid
az ad sp create-for-rbac --name principlename --password password 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 “Default”. 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 “Default”.
<a name="ssms2019"></a> <a name="ssms2019"></a>
## Setup using SQL Server Management Studio for SQL Server 2019 on Linux ## 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) 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) 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) 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: 4. Enable external scripts with the following commands:
```sh ```sh
sp_configure 'external scripts enabled',1 sp_configure 'external scripts enabled',1
reconfigure with override reconfigure with override
``` ```
5. Stop SQL Server. 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): 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 ```sh
sudo /opt/mssql/mlservices/bin/python/python -m pip install azureml-sdk[automl] 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 numpy
sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade sklearn sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade sklearn
``` ```
7. Start SQL Server. 7. Start SQL Server.
8. Execute the files aml_model.sql, aml_connection.sql, AutoMLGetMetrics.sql, AutoMLPredict.sql and AutoMLTrain.sql in SQL Server Management Studio. 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) 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) 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: 11. Create an Azure service principal. You can do this with the commands:
```sh ```sh
az login az login
az account set --subscription subscriptionid az account set --subscription subscriptionid
az ad sp create-for-rbac --name principlename --password password 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 “Default”. 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 “Default”.
<a name="ssmsenergydemand"></a> <a name="ssmsenergydemand"></a>
## Energy demand example using SQL Server Management Studio ## Energy demand example using SQL Server Management Studio
Once you have completed the setup, you can try the energy demand sample queries. 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. 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. 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. 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. 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: 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. * TrainEnergyDemand.sql runs AutoML, trains multiple models on data and selects the best model.
* PredictEnergyDemand.sql predicts based on the most recent training run. * 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. * GetMetrics.sql returns all the metrics for each model in the most recent training run.

View File

@@ -1,23 +1,23 @@
-- This shows using the AutoMLForecast stored procedure to predict using a forecasting model for the nyc_energy dataset. -- This shows using the AutoMLForecast stored procedure to predict using a forecasting model for the nyc_energy dataset.
DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model
WHERE ExperimentName = 'automl-sql-forecast' WHERE ExperimentName = 'automl-sql-forecast'
ORDER BY CreatedDate DESC) ORDER BY CreatedDate DESC)
DECLARE @max_horizon INT = 48 DECLARE @max_horizon INT = 48
DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL) DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL)
DECLARE @TestDataQuery NVARCHAR(MAX) = ' DECLARE @TestDataQuery NVARCHAR(MAX) = '
SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp, SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,
demand, demand,
precip, precip,
temp temp
FROM nyc_energy FROM nyc_energy
WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL
AND timeStamp > ''' + @split_time + '''' AND timeStamp > ''' + @split_time + ''''
EXEC dbo.AutoMLForecast @input_query=@TestDataQuery, EXEC dbo.AutoMLForecast @input_query=@TestDataQuery,
@label_column='demand', @label_column='demand',
@time_column_name='timeStamp', @time_column_name='timeStamp',
@model=@model @model=@model
WITH RESULT SETS ((timeStamp DATETIME, grain NVARCHAR(255), predicted_demand FLOAT, precip FLOAT, temp FLOAT, actual_demand FLOAT)) WITH RESULT SETS ((timeStamp DATETIME, grain NVARCHAR(255), predicted_demand FLOAT, precip FLOAT, temp FLOAT, actual_demand FLOAT))

View File

@@ -1,25 +1,25 @@
-- This shows using the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset. -- This shows using the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset.
DECLARE @max_horizon INT = 48 DECLARE @max_horizon INT = 48
DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL) DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL)
DECLARE @TrainDataQuery NVARCHAR(MAX) = ' DECLARE @TrainDataQuery NVARCHAR(MAX) = '
SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp, SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,
demand, demand,
precip, precip,
temp temp
FROM nyc_energy FROM nyc_energy
WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL
and timeStamp < ''' + @split_time + '''' and timeStamp < ''' + @split_time + ''''
INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName) INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
EXEC dbo.AutoMLTrain @input_query= @TrainDataQuery, EXEC dbo.AutoMLTrain @input_query= @TrainDataQuery,
@label_column='demand', @label_column='demand',
@task='forecasting', @task='forecasting',
@iterations=10, @iterations=10,
@iteration_timeout_minutes=5, @iteration_timeout_minutes=5,
@time_column_name='timeStamp', @time_column_name='timeStamp',
@max_horizon=@max_horizon, @max_horizon=@max_horizon,
@experiment_name='automl-sql-forecast', @experiment_name='automl-sql-forecast',
@primary_metric='normalized_root_mean_squared_error' @primary_metric='normalized_root_mean_squared_error'

View File

@@ -1,141 +1,141 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "sql" "source": [
}, "# Train a model and use it for prediction\r\n",
"authors": [ "\r\n",
{ "Before running this notebook, run the auto-ml-sql-setup.ipynb notebook."
"name": "jeffshep" ]
} },
], {
"language_info": { "cell_type": "markdown",
"name": "sql", "metadata": {},
"version": "" "source": [
} "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sql-server/energy-demand/auto-ml-sql-energy-demand.png)"
}, ]
"nbformat": 4, },
"cells": [ {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"# Train a model and use it for prediction\r\n", "## Set the default database"
"\r\n", ]
"Before running this notebook, run the auto-ml-sql-setup.ipynb notebook." },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sql-server/energy-demand/auto-ml-sql-energy-demand.png)" "USE [automl]\r\n",
], "GO"
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "markdown",
"source": [ "metadata": {},
"## Set the default database" "source": [
], "## Use the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset."
"cell_type": "markdown" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"USE [automl]\r\n", "source": [
"GO" "INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)\r\n",
], "EXEC dbo.AutoMLTrain @input_query='\r\n",
"cell_type": "code" "SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,\r\n",
}, " demand,\r\n",
{ "\t precip,\r\n",
"metadata": {}, "\t temp,\r\n",
"source": [ "\t CASE WHEN timeStamp < ''2017-01-01'' THEN 0 ELSE 1 END AS is_validate_column\r\n",
"## Use the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset." "FROM nyc_energy\r\n",
], "WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n",
"cell_type": "markdown" "and timeStamp < ''2017-02-01''',\r\n",
}, "@label_column='demand',\r\n",
{ "@task='forecasting',\r\n",
"metadata": {}, "@iterations=10,\r\n",
"outputs": [], "@iteration_timeout_minutes=5,\r\n",
"execution_count": null, "@time_column_name='timeStamp',\r\n",
"source": [ "@is_validate_column='is_validate_column',\r\n",
"INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)\r\n", "@experiment_name='automl-sql-forecast',\r\n",
"EXEC dbo.AutoMLTrain @input_query='\r\n", "@primary_metric='normalized_root_mean_squared_error'"
"SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,\r\n", ]
" demand,\r\n", },
"\t precip,\r\n", {
"\t temp,\r\n", "cell_type": "markdown",
"\t CASE WHEN timeStamp < ''2017-01-01'' THEN 0 ELSE 1 END AS is_validate_column\r\n", "metadata": {},
"FROM nyc_energy\r\n", "source": [
"WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n", "## Use the AutoMLPredict stored procedure to predict using the forecasting model for the nyc_energy dataset."
"and timeStamp < ''2017-02-01''',\r\n", ]
"@label_column='demand',\r\n", },
"@task='forecasting',\r\n", {
"@iterations=10,\r\n", "cell_type": "code",
"@iteration_timeout_minutes=5,\r\n", "execution_count": null,
"@time_column_name='timeStamp',\r\n", "metadata": {},
"@is_validate_column='is_validate_column',\r\n", "outputs": [],
"@experiment_name='automl-sql-forecast',\r\n", "source": [
"@primary_metric='normalized_root_mean_squared_error'" "DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model\r\n",
], " WHERE ExperimentName = 'automl-sql-forecast'\r\n",
"cell_type": "code" "\t\t\t\t\t\t\t\tORDER BY CreatedDate DESC)\r\n",
}, "\r\n",
{ "EXEC dbo.AutoMLPredict @input_query='\r\n",
"metadata": {}, "SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,\r\n",
"source": [ " demand,\r\n",
"## Use the AutoMLPredict stored procedure to predict using the forecasting model for the nyc_energy dataset." "\t precip,\r\n",
], "\t temp\r\n",
"cell_type": "markdown" "FROM nyc_energy\r\n",
}, "WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n",
{ "AND timeStamp >= ''2017-02-01''',\r\n",
"metadata": {}, "@label_column='demand',\r\n",
"outputs": [], "@model=@model\r\n",
"execution_count": null, "WITH RESULT SETS ((timeStamp NVARCHAR(30), actual_demand FLOAT, precip FLOAT, temp FLOAT, predicted_demand FLOAT))"
"source": [ ]
"DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model\r\n", },
" WHERE ExperimentName = 'automl-sql-forecast'\r\n", {
"\t\t\t\t\t\t\t\tORDER BY CreatedDate DESC)\r\n", "cell_type": "markdown",
"\r\n", "metadata": {},
"EXEC dbo.AutoMLPredict @input_query='\r\n", "source": [
"SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,\r\n", "## List all the metrics for all iterations for the most recent training run."
" demand,\r\n", ]
"\t precip,\r\n", },
"\t temp\r\n", {
"FROM nyc_energy\r\n", "cell_type": "code",
"WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n", "execution_count": null,
"AND timeStamp >= ''2017-02-01''',\r\n", "metadata": {},
"@label_column='demand',\r\n", "outputs": [],
"@model=@model\r\n", "source": [
"WITH RESULT SETS ((timeStamp NVARCHAR(30), actual_demand FLOAT, precip FLOAT, temp FLOAT, predicted_demand FLOAT))" "DECLARE @RunId NVARCHAR(43)\r\n",
], "DECLARE @ExperimentName NVARCHAR(255)\r\n",
"cell_type": "code" "\r\n",
}, "SELECT TOP 1 @ExperimentName=ExperimentName, @RunId=SUBSTRING(RunId, 1, 43)\r\n",
{ "FROM aml_model\r\n",
"metadata": {}, "ORDER BY CreatedDate DESC\r\n",
"source": [ "\r\n",
"## List all the metrics for all iterations for the most recent training run." "EXEC dbo.AutoMLGetMetrics @RunId, @ExperimentName"
], ]
"cell_type": "markdown" }
}, ],
{ "metadata": {
"metadata": {}, "authors": [
"outputs": [], {
"execution_count": null, "name": "jeffshep"
"source": [ }
"DECLARE @RunId NVARCHAR(43)\r\n", ],
"DECLARE @ExperimentName NVARCHAR(255)\r\n", "kernelspec": {
"\r\n", "display_name": "Python 3.6",
"SELECT TOP 1 @ExperimentName=ExperimentName, @RunId=SUBSTRING(RunId, 1, 43)\r\n", "language": "sql",
"FROM aml_model\r\n", "name": "python36"
"ORDER BY CreatedDate DESC\r\n", },
"\r\n", "language_info": {
"EXEC dbo.AutoMLGetMetrics @RunId, @ExperimentName" "name": "sql",
], "version": ""
"cell_type": "code" }
} },
], "nbformat": 4,
"nbformat_minor": 2 "nbformat_minor": 2
} }

View File

@@ -1,92 +1,92 @@
-- This procedure forecast values based on a forecasting model returned by AutoMLTrain. -- This procedure forecast values based on a forecasting model returned by AutoMLTrain.
-- It returns a dataset with the forecasted values. -- It returns a dataset with the forecasted values.
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE OR ALTER PROCEDURE [dbo].[AutoMLForecast] CREATE OR ALTER PROCEDURE [dbo].[AutoMLForecast]
( (
@input_query NVARCHAR(MAX), -- A SQL query returning data to predict on. @input_query NVARCHAR(MAX), -- A SQL query returning data to predict on.
@model NVARCHAR(MAX), -- A model returned from AutoMLTrain. @model NVARCHAR(MAX), -- A model returned from AutoMLTrain.
@time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting. @time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting.
@label_column NVARCHAR(255)='', -- Optional name of the column from input_query, which should be ignored when predicting @label_column NVARCHAR(255)='', -- Optional name of the column from input_query, which should be ignored when predicting
@y_query_column NVARCHAR(255)='', -- Optional value column that can be used for predicting. @y_query_column NVARCHAR(255)='', -- Optional value column that can be used for predicting.
-- If specified, this can contain values for past times (after the model was trained) -- If specified, this can contain values for past times (after the model was trained)
-- and contain Nan for future times. -- and contain Nan for future times.
@forecast_column_name NVARCHAR(255) = 'predicted' @forecast_column_name NVARCHAR(255) = 'predicted'
-- The name of the output column containing the forecast value. -- The name of the output column containing the forecast value.
) AS ) AS
BEGIN BEGIN
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
import azureml.core import azureml.core
import numpy as np import numpy as np
from azureml.train.automl import AutoMLConfig from azureml.train.automl import AutoMLConfig
import pickle import pickle
import codecs import codecs
model_obj = pickle.loads(codecs.decode(model.encode(), "base64")) model_obj = pickle.loads(codecs.decode(model.encode(), "base64"))
test_data = input_data.copy() test_data = input_data.copy()
if label_column != "" and label_column is not None: if label_column != "" and label_column is not None:
y_test = test_data.pop(label_column).values y_test = test_data.pop(label_column).values
else: else:
y_test = None y_test = None
if y_query_column != "" and y_query_column is not None: if y_query_column != "" and y_query_column is not None:
y_query = test_data.pop(y_query_column).values y_query = test_data.pop(y_query_column).values
else: else:
y_query = np.repeat(np.nan, len(test_data)) y_query = np.repeat(np.nan, len(test_data))
X_test = test_data X_test = test_data
if time_column_name != "" and time_column_name is not None: if time_column_name != "" and time_column_name is not None:
X_test[time_column_name] = pd.to_datetime(X_test[time_column_name]) X_test[time_column_name] = pd.to_datetime(X_test[time_column_name])
y_fcst, X_trans = model_obj.forecast(X_test, y_query) y_fcst, X_trans = model_obj.forecast(X_test, y_query)
def align_outputs(y_forecast, X_trans, X_test, y_test, forecast_column_name): def align_outputs(y_forecast, X_trans, X_test, y_test, forecast_column_name):
# Demonstrates how to get the output aligned to the inputs # Demonstrates how to get the output aligned to the inputs
# using pandas indexes. Helps understand what happened if # using pandas indexes. Helps understand what happened if
# the output shape differs from the input shape, or if # the output shape differs from the input shape, or if
# the data got re-sorted by time and grain during forecasting. # the data got re-sorted by time and grain during forecasting.
# Typical causes of misalignment are: # Typical causes of misalignment are:
# * we predicted some periods that were missing in actuals -> drop from eval # * we predicted some periods that were missing in actuals -> drop from eval
# * model was asked to predict past max_horizon -> increase max horizon # * model was asked to predict past max_horizon -> increase max horizon
# * data at start of X_test was needed for lags -> provide previous periods # * data at start of X_test was needed for lags -> provide previous periods
df_fcst = pd.DataFrame({forecast_column_name : y_forecast}) df_fcst = pd.DataFrame({forecast_column_name : y_forecast})
# y and X outputs are aligned by forecast() function contract # y and X outputs are aligned by forecast() function contract
df_fcst.index = X_trans.index df_fcst.index = X_trans.index
# align original X_test to y_test # align original X_test to y_test
X_test_full = X_test.copy() X_test_full = X_test.copy()
if y_test is not None: if y_test is not None:
X_test_full[label_column] = y_test X_test_full[label_column] = y_test
# X_test_full does not include origin, so reset for merge # X_test_full does not include origin, so reset for merge
df_fcst.reset_index(inplace=True) df_fcst.reset_index(inplace=True)
X_test_full = X_test_full.reset_index().drop(columns=''index'') X_test_full = X_test_full.reset_index().drop(columns=''index'')
together = df_fcst.merge(X_test_full, how=''right'') together = df_fcst.merge(X_test_full, how=''right'')
# drop rows where prediction or actuals are nan # drop rows where prediction or actuals are nan
# happens because of missing actuals # happens because of missing actuals
# or at edges of time due to lags/rolling windows # or at edges of time due to lags/rolling windows
clean = together[together[[label_column, forecast_column_name]].notnull().all(axis=1)] clean = together[together[[label_column, forecast_column_name]].notnull().all(axis=1)]
return(clean) return(clean)
combined_output = align_outputs(y_fcst, X_trans, X_test, y_test, forecast_column_name) combined_output = align_outputs(y_fcst, X_trans, X_test, y_test, forecast_column_name)
' '
, @input_data_1 = @input_query , @input_data_1 = @input_query
, @input_data_1_name = N'input_data' , @input_data_1_name = N'input_data'
, @output_data_1_name = N'combined_output' , @output_data_1_name = N'combined_output'
, @params = N'@model NVARCHAR(MAX), @time_column_name NVARCHAR(255), @label_column NVARCHAR(255), @y_query_column NVARCHAR(255), @forecast_column_name NVARCHAR(255)' , @params = N'@model NVARCHAR(MAX), @time_column_name NVARCHAR(255), @label_column NVARCHAR(255), @y_query_column NVARCHAR(255), @forecast_column_name NVARCHAR(255)'
, @model = @model , @model = @model
, @time_column_name = @time_column_name , @time_column_name = @time_column_name
, @label_column = @label_column , @label_column = @label_column
, @y_query_column = @y_query_column , @y_query_column = @y_query_column
, @forecast_column_name = @forecast_column_name , @forecast_column_name = @forecast_column_name
END END

View File

@@ -1,41 +1,41 @@
-- This procedure predicts values based on a model returned by AutoMLTrain and a dataset. -- This procedure predicts values based on a model returned by AutoMLTrain and a dataset.
-- It returns the dataset with a new column added, which is the predicted value. -- It returns the dataset with a new column added, which is the predicted value.
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE OR ALTER PROCEDURE [dbo].[AutoMLPredict] CREATE OR ALTER PROCEDURE [dbo].[AutoMLPredict]
( (
@input_query NVARCHAR(MAX), -- A SQL query returning data to predict on. @input_query NVARCHAR(MAX), -- A SQL query returning data to predict on.
@model NVARCHAR(MAX), -- A model returned from AutoMLTrain. @model NVARCHAR(MAX), -- A model returned from AutoMLTrain.
@label_column NVARCHAR(255)='' -- Optional name of the column from input_query, which should be ignored when predicting @label_column NVARCHAR(255)='' -- Optional name of the column from input_query, which should be ignored when predicting
) AS ) AS
BEGIN BEGIN
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
import azureml.core import azureml.core
import numpy as np import numpy as np
from azureml.train.automl import AutoMLConfig from azureml.train.automl import AutoMLConfig
import pickle import pickle
import codecs import codecs
model_obj = pickle.loads(codecs.decode(model.encode(), "base64")) model_obj = pickle.loads(codecs.decode(model.encode(), "base64"))
test_data = input_data.copy() test_data = input_data.copy()
if label_column != "" and label_column is not None: if label_column != "" and label_column is not None:
y_test = test_data.pop(label_column).values y_test = test_data.pop(label_column).values
X_test = test_data X_test = test_data
predicted = model_obj.predict(X_test) predicted = model_obj.predict(X_test)
combined_output = input_data.assign(predicted=predicted) combined_output = input_data.assign(predicted=predicted)
' '
, @input_data_1 = @input_query , @input_data_1 = @input_query
, @input_data_1_name = N'input_data' , @input_data_1_name = N'input_data'
, @output_data_1_name = N'combined_output' , @output_data_1_name = N'combined_output'
, @params = N'@model NVARCHAR(MAX), @label_column NVARCHAR(255)' , @params = N'@model NVARCHAR(MAX), @label_column NVARCHAR(255)'
, @model = @model , @model = @model
, @label_column = @label_column , @label_column = @label_column
END END

View File

@@ -1,240 +1,240 @@
-- This stored procedure uses automated machine learning to train several models -- This stored procedure uses automated machine learning to train several models
-- and returns the best model. -- and returns the best model.
-- --
-- The result set has several columns: -- The result set has several columns:
-- best_run - iteration ID for the best model -- best_run - iteration ID for the best model
-- experiment_name - experiment name pass in with the @experiment_name parameter -- experiment_name - experiment name pass in with the @experiment_name parameter
-- fitted_model - best model found -- fitted_model - best model found
-- log_file_text - AutoML debug_log contents -- log_file_text - AutoML debug_log contents
-- workspace - name of the Azure ML workspace where run history is stored -- workspace - name of the Azure ML workspace where run history is stored
-- --
-- An example call for a classification problem is: -- An example call for a classification problem is:
-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName) -- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
-- exec dbo.AutoMLTrain @input_query=' -- exec dbo.AutoMLTrain @input_query='
-- SELECT top 100000 -- SELECT top 100000
-- CAST([pickup_datetime] AS NVARCHAR(30)) AS pickup_datetime -- CAST([pickup_datetime] AS NVARCHAR(30)) AS pickup_datetime
-- ,CAST([dropoff_datetime] AS NVARCHAR(30)) AS dropoff_datetime -- ,CAST([dropoff_datetime] AS NVARCHAR(30)) AS dropoff_datetime
-- ,[passenger_count] -- ,[passenger_count]
-- ,[trip_time_in_secs] -- ,[trip_time_in_secs]
-- ,[trip_distance] -- ,[trip_distance]
-- ,[payment_type] -- ,[payment_type]
-- ,[tip_class] -- ,[tip_class]
-- FROM [dbo].[nyctaxi_sample] order by [hack_license] ', -- FROM [dbo].[nyctaxi_sample] order by [hack_license] ',
-- @label_column = 'tip_class', -- @label_column = 'tip_class',
-- @iterations=10 -- @iterations=10
-- --
-- An example call for forecasting is: -- An example call for forecasting is:
-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName) -- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
-- exec dbo.AutoMLTrain @input_query=' -- exec dbo.AutoMLTrain @input_query='
-- select cast(timeStamp as nvarchar(30)) as timeStamp, -- select cast(timeStamp as nvarchar(30)) as timeStamp,
-- demand, -- demand,
-- precip, -- precip,
-- temp, -- temp,
-- case when timeStamp < ''2017-01-01'' then 0 else 1 end as is_validate_column -- case when timeStamp < ''2017-01-01'' then 0 else 1 end as is_validate_column
-- from nyc_energy -- from nyc_energy
-- where demand is not null and precip is not null and temp is not null -- where demand is not null and precip is not null and temp is not null
-- and timeStamp < ''2017-02-01''', -- and timeStamp < ''2017-02-01''',
-- @label_column='demand', -- @label_column='demand',
-- @task='forecasting', -- @task='forecasting',
-- @iterations=10, -- @iterations=10,
-- @iteration_timeout_minutes=5, -- @iteration_timeout_minutes=5,
-- @time_column_name='timeStamp', -- @time_column_name='timeStamp',
-- @is_validate_column='is_validate_column', -- @is_validate_column='is_validate_column',
-- @experiment_name='automl-sql-forecast', -- @experiment_name='automl-sql-forecast',
-- @primary_metric='normalized_root_mean_squared_error' -- @primary_metric='normalized_root_mean_squared_error'
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE OR ALTER PROCEDURE [dbo].[AutoMLTrain] CREATE OR ALTER PROCEDURE [dbo].[AutoMLTrain]
( (
@input_query NVARCHAR(MAX), -- The SQL Query that will return the data to train and validate the model. @input_query NVARCHAR(MAX), -- The SQL Query that will return the data to train and validate the model.
@label_column NVARCHAR(255)='Label', -- The name of the column in the result of @input_query that is the label. @label_column NVARCHAR(255)='Label', -- The name of the column in the result of @input_query that is the label.
@primary_metric NVARCHAR(40)='AUC_weighted', -- The metric to optimize. @primary_metric NVARCHAR(40)='AUC_weighted', -- The metric to optimize.
@iterations INT=100, -- The maximum number of pipelines to train. @iterations INT=100, -- The maximum number of pipelines to train.
@task NVARCHAR(40)='classification', -- The type of task. Can be classification, regression or forecasting. @task NVARCHAR(40)='classification', -- The type of task. Can be classification, regression or forecasting.
@experiment_name NVARCHAR(32)='automl-sql-test', -- This can be used to find the experiment in the Azure Portal. @experiment_name NVARCHAR(32)='automl-sql-test', -- This can be used to find the experiment in the Azure Portal.
@iteration_timeout_minutes INT = 15, -- The maximum time in minutes for training a single pipeline. @iteration_timeout_minutes INT = 15, -- The maximum time in minutes for training a single pipeline.
@experiment_timeout_minutes INT = 60, -- The maximum time in minutes for training all pipelines. @experiment_timeout_minutes INT = 60, -- The maximum time in minutes for training all pipelines.
@n_cross_validations INT = 3, -- The number of cross validations. @n_cross_validations INT = 3, -- The number of cross validations.
@blacklist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that will not be used. @blacklist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that will not be used.
-- The list of possible models can be found at: -- The list of possible models can be found at:
-- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings -- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings
@whitelist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that can be used. @whitelist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that can be used.
-- The list of possible models can be found at: -- The list of possible models can be found at:
-- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings -- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings
@experiment_exit_score FLOAT = 0, -- Stop the experiment if this score is acheived. @experiment_exit_score FLOAT = 0, -- Stop the experiment if this score is acheived.
@sample_weight_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that gives a sample weight. @sample_weight_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that gives a sample weight.
@is_validate_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that indicates if the row is for training or validation. @is_validate_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that indicates if the row is for training or validation.
-- In the values of the column, 0 means for training and 1 means for validation. -- In the values of the column, 0 means for training and 1 means for validation.
@time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting. @time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting.
@connection_name NVARCHAR(255)='default', -- The AML connection to use. @connection_name NVARCHAR(255)='default', -- The AML connection to use.
@max_horizon INT = 0 -- A forecast horizon is a time span into the future (or just beyond the latest date in the training data) @max_horizon INT = 0 -- A forecast horizon is a time span into the future (or just beyond the latest date in the training data)
-- where forecasts of the target quantity are needed. -- where forecasts of the target quantity are needed.
-- For example, if data is recorded daily and max_horizon is 5, we will predict 5 days ahead. -- For example, if data is recorded daily and max_horizon is 5, we will predict 5 days ahead.
) AS ) AS
BEGIN BEGIN
DECLARE @tenantid NVARCHAR(255) DECLARE @tenantid NVARCHAR(255)
DECLARE @appid NVARCHAR(255) DECLARE @appid NVARCHAR(255)
DECLARE @password NVARCHAR(255) DECLARE @password NVARCHAR(255)
DECLARE @config_file NVARCHAR(255) DECLARE @config_file NVARCHAR(255)
SELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile SELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile
FROM aml_connection FROM aml_connection
WHERE ConnectionName = @connection_name; WHERE ConnectionName = @connection_name;
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
import logging import logging
import azureml.core import azureml.core
import pandas as pd import pandas as pd
import numpy as np import numpy as np
from azureml.core.experiment import Experiment from azureml.core.experiment import Experiment
from azureml.train.automl import AutoMLConfig from azureml.train.automl import AutoMLConfig
from sklearn import datasets from sklearn import datasets
import pickle import pickle
import codecs import codecs
from azureml.core.authentication import ServicePrincipalAuthentication from azureml.core.authentication import ServicePrincipalAuthentication
from azureml.core.workspace import Workspace from azureml.core.workspace import Workspace
if __name__.startswith("sqlindb"): if __name__.startswith("sqlindb"):
auth = ServicePrincipalAuthentication(tenantid, appid, password) auth = ServicePrincipalAuthentication(tenantid, appid, password)
ws = Workspace.from_config(path=config_file, auth=auth) ws = Workspace.from_config(path=config_file, auth=auth)
project_folder = "./sample_projects/" + experiment_name project_folder = "./sample_projects/" + experiment_name
experiment = Experiment(ws, experiment_name) experiment = Experiment(ws, experiment_name)
data_train = input_data data_train = input_data
X_valid = None X_valid = None
y_valid = None y_valid = None
sample_weight_valid = None sample_weight_valid = None
if is_validate_column != "" and is_validate_column is not None: if is_validate_column != "" and is_validate_column is not None:
data_train = input_data[input_data[is_validate_column] <= 0] data_train = input_data[input_data[is_validate_column] <= 0]
data_valid = input_data[input_data[is_validate_column] > 0] data_valid = input_data[input_data[is_validate_column] > 0]
data_train.pop(is_validate_column) data_train.pop(is_validate_column)
data_valid.pop(is_validate_column) data_valid.pop(is_validate_column)
y_valid = data_valid.pop(label_column).values y_valid = data_valid.pop(label_column).values
if sample_weight_column != "" and sample_weight_column is not None: if sample_weight_column != "" and sample_weight_column is not None:
sample_weight_valid = data_valid.pop(sample_weight_column).values sample_weight_valid = data_valid.pop(sample_weight_column).values
X_valid = data_valid X_valid = data_valid
n_cross_validations = None n_cross_validations = None
y_train = data_train.pop(label_column).values y_train = data_train.pop(label_column).values
sample_weight = None sample_weight = None
if sample_weight_column != "" and sample_weight_column is not None: if sample_weight_column != "" and sample_weight_column is not None:
sample_weight = data_train.pop(sample_weight_column).values sample_weight = data_train.pop(sample_weight_column).values
X_train = data_train X_train = data_train
if experiment_timeout_minutes == 0: if experiment_timeout_minutes == 0:
experiment_timeout_minutes = None experiment_timeout_minutes = None
if experiment_exit_score == 0: if experiment_exit_score == 0:
experiment_exit_score = None experiment_exit_score = None
if blacklist_models == "": if blacklist_models == "":
blacklist_models = None blacklist_models = None
if blacklist_models is not None: if blacklist_models is not None:
blacklist_models = blacklist_models.replace(" ", "").split(",") blacklist_models = blacklist_models.replace(" ", "").split(",")
if whitelist_models == "": if whitelist_models == "":
whitelist_models = None whitelist_models = None
if whitelist_models is not None: if whitelist_models is not None:
whitelist_models = whitelist_models.replace(" ", "").split(",") whitelist_models = whitelist_models.replace(" ", "").split(",")
automl_settings = {} automl_settings = {}
preprocess = True preprocess = True
if time_column_name != "" and time_column_name is not None: if time_column_name != "" and time_column_name is not None:
automl_settings = { "time_column_name": time_column_name } automl_settings = { "time_column_name": time_column_name }
preprocess = False preprocess = False
if max_horizon > 0: if max_horizon > 0:
automl_settings["max_horizon"] = max_horizon automl_settings["max_horizon"] = max_horizon
log_file_name = "automl_sqlindb_errors.log" log_file_name = "automl_sqlindb_errors.log"
automl_config = AutoMLConfig(task = task, automl_config = AutoMLConfig(task = task,
debug_log = log_file_name, debug_log = log_file_name,
primary_metric = primary_metric, primary_metric = primary_metric,
iteration_timeout_minutes = iteration_timeout_minutes, iteration_timeout_minutes = iteration_timeout_minutes,
experiment_timeout_minutes = experiment_timeout_minutes, experiment_timeout_minutes = experiment_timeout_minutes,
iterations = iterations, iterations = iterations,
n_cross_validations = n_cross_validations, n_cross_validations = n_cross_validations,
preprocess = preprocess, preprocess = preprocess,
verbosity = logging.INFO, verbosity = logging.INFO,
X = X_train, X = X_train,
y = y_train, y = y_train,
path = project_folder, path = project_folder,
blacklist_models = blacklist_models, blacklist_models = blacklist_models,
whitelist_models = whitelist_models, whitelist_models = whitelist_models,
experiment_exit_score = experiment_exit_score, experiment_exit_score = experiment_exit_score,
sample_weight = sample_weight, sample_weight = sample_weight,
X_valid = X_valid, X_valid = X_valid,
y_valid = y_valid, y_valid = y_valid,
sample_weight_valid = sample_weight_valid, sample_weight_valid = sample_weight_valid,
**automl_settings) **automl_settings)
local_run = experiment.submit(automl_config, show_output = True) local_run = experiment.submit(automl_config, show_output = True)
best_run, fitted_model = local_run.get_output() best_run, fitted_model = local_run.get_output()
pickled_model = codecs.encode(pickle.dumps(fitted_model), "base64").decode() pickled_model = codecs.encode(pickle.dumps(fitted_model), "base64").decode()
log_file_text = "" log_file_text = ""
try: try:
with open(log_file_name, "r") as log_file: with open(log_file_name, "r") as log_file:
log_file_text = log_file.read() log_file_text = log_file.read()
except: except:
log_file_text = "Log file not found" log_file_text = "Log file not found"
returned_model = pd.DataFrame({"best_run": [best_run.id], "experiment_name": [experiment_name], "fitted_model": [pickled_model], "log_file_text": [log_file_text], "workspace": [ws.name]}, dtype=np.dtype(np.str)) returned_model = pd.DataFrame({"best_run": [best_run.id], "experiment_name": [experiment_name], "fitted_model": [pickled_model], "log_file_text": [log_file_text], "workspace": [ws.name]}, dtype=np.dtype(np.str))
' '
, @input_data_1 = @input_query , @input_data_1 = @input_query
, @input_data_1_name = N'input_data' , @input_data_1_name = N'input_data'
, @output_data_1_name = N'returned_model' , @output_data_1_name = N'returned_model'
, @params = N'@label_column NVARCHAR(255), , @params = N'@label_column NVARCHAR(255),
@primary_metric NVARCHAR(40), @primary_metric NVARCHAR(40),
@iterations INT, @task NVARCHAR(40), @iterations INT, @task NVARCHAR(40),
@experiment_name NVARCHAR(32), @experiment_name NVARCHAR(32),
@iteration_timeout_minutes INT, @iteration_timeout_minutes INT,
@experiment_timeout_minutes INT, @experiment_timeout_minutes INT,
@n_cross_validations INT, @n_cross_validations INT,
@blacklist_models NVARCHAR(MAX), @blacklist_models NVARCHAR(MAX),
@whitelist_models NVARCHAR(MAX), @whitelist_models NVARCHAR(MAX),
@experiment_exit_score FLOAT, @experiment_exit_score FLOAT,
@sample_weight_column NVARCHAR(255), @sample_weight_column NVARCHAR(255),
@is_validate_column NVARCHAR(255), @is_validate_column NVARCHAR(255),
@time_column_name NVARCHAR(255), @time_column_name NVARCHAR(255),
@tenantid NVARCHAR(255), @tenantid NVARCHAR(255),
@appid NVARCHAR(255), @appid NVARCHAR(255),
@password NVARCHAR(255), @password NVARCHAR(255),
@config_file NVARCHAR(255), @config_file NVARCHAR(255),
@max_horizon INT' @max_horizon INT'
, @label_column = @label_column , @label_column = @label_column
, @primary_metric = @primary_metric , @primary_metric = @primary_metric
, @iterations = @iterations , @iterations = @iterations
, @task = @task , @task = @task
, @experiment_name = @experiment_name , @experiment_name = @experiment_name
, @iteration_timeout_minutes = @iteration_timeout_minutes , @iteration_timeout_minutes = @iteration_timeout_minutes
, @experiment_timeout_minutes = @experiment_timeout_minutes , @experiment_timeout_minutes = @experiment_timeout_minutes
, @n_cross_validations = @n_cross_validations , @n_cross_validations = @n_cross_validations
, @blacklist_models = @blacklist_models , @blacklist_models = @blacklist_models
, @whitelist_models = @whitelist_models , @whitelist_models = @whitelist_models
, @experiment_exit_score = @experiment_exit_score , @experiment_exit_score = @experiment_exit_score
, @sample_weight_column = @sample_weight_column , @sample_weight_column = @sample_weight_column
, @is_validate_column = @is_validate_column , @is_validate_column = @is_validate_column
, @time_column_name = @time_column_name , @time_column_name = @time_column_name
, @tenantid = @tenantid , @tenantid = @tenantid
, @appid = @appid , @appid = @appid
, @password = @password , @password = @password
, @config_file = @config_file , @config_file = @config_file
, @max_horizon = @max_horizon , @max_horizon = @max_horizon
WITH RESULT SETS ((best_run NVARCHAR(250), experiment_name NVARCHAR(100), fitted_model VARCHAR(MAX), log_file_text NVARCHAR(MAX), workspace NVARCHAR(100))) WITH RESULT SETS ((best_run NVARCHAR(250), experiment_name NVARCHAR(100), fitted_model VARCHAR(MAX), log_file_text NVARCHAR(MAX), workspace NVARCHAR(100)))
END END

View File

@@ -1,18 +1,18 @@
-- This is a table to store the Azure ML connection information. -- This is a table to store the Azure ML connection information.
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE TABLE [dbo].[aml_connection]( CREATE TABLE [dbo].[aml_connection](
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[ConnectionName] [nvarchar](255) NULL, [ConnectionName] [nvarchar](255) NULL,
[TenantId] [nvarchar](255) NULL, [TenantId] [nvarchar](255) NULL,
[AppId] [nvarchar](255) NULL, [AppId] [nvarchar](255) NULL,
[Password] [nvarchar](255) NULL, [Password] [nvarchar](255) NULL,
[ConfigFile] [nvarchar](255) NULL [ConfigFile] [nvarchar](255) NULL
) ON [PRIMARY] ) ON [PRIMARY]
GO GO

View File

@@ -1,208 +1,198 @@
{ {
"metadata": { "cells": [
"kernelspec": { {
"display_name": "Python 3.6", "cell_type": "markdown",
"name": "python36", "metadata": {},
"language": "python" "source": [
}, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"authors": [ "\n",
{ "Licensed under the MIT License."
"name": "rogehe" ]
} },
], {
"language_info": { "cell_type": "markdown",
"mimetype": "text/x-python", "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/subsampling/auto-ml-subsampling-local.png)"
"version": 3 ]
}, },
"pygments_lexer": "ipython3", {
"name": "python", "cell_type": "markdown",
"file_extension": ".py", "metadata": {},
"nbconvert_exporter": "python", "source": [
"version": "3.6.6" "# Automated Machine Learning\n",
} "_**Classification with Local Compute**_\n",
}, "\n",
"nbformat": 4, "## Contents\n",
"cells": [ "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"metadata": {}, "1. [Data](#Data)\n",
"source": [ "1. [Train](#Train)\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "\n"
"\n", ]
"Licensed under the MIT License." },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Introduction\n",
"source": [ "\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/subsampling/auto-ml-subsampling-local.png)" "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",
"cell_type": "markdown" "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"
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "markdown",
"# Automated Machine Learning\n", "metadata": {},
"_**Classification with Local Compute**_\n", "source": [
"\n", "## Setup\n",
"## Contents\n", "\n",
"1. [Introduction](#Introduction)\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."
"1. [Setup](#Setup)\n", ]
"1. [Data](#Data)\n", },
"1. [Train](#Train)\n", {
"\n" "cell_type": "code",
], "execution_count": null,
"cell_type": "markdown" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "import logging\n",
"source": [ "\n",
"## Introduction\n", "import numpy as np\n",
"\n", "import pandas as pd\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",
"\n", "import azureml.core\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" "from azureml.core.experiment import Experiment\n",
], "from azureml.core.workspace import Workspace\n",
"cell_type": "markdown" "from azureml.train.automl import AutoMLConfig\n",
}, "from azureml.train.automl.run import AutoMLRun"
{ ]
"metadata": {}, },
"source": [ {
"## Setup\n", "cell_type": "code",
"\n", "execution_count": null,
"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." "metadata": {},
], "outputs": [],
"cell_type": "markdown" "source": [
}, "ws = Workspace.from_config()\n",
{ "\n",
"metadata": {}, "# Choose a name for the experiment.\n",
"outputs": [], "experiment_name = 'automl-subsampling'\n",
"execution_count": null, "\n",
"source": [ "experiment = Experiment(ws, experiment_name)\n",
"import logging\n", "\n",
"\n", "output = {}\n",
"import numpy as np\n", "output['SDK version'] = azureml.core.VERSION\n",
"import pandas as pd\n", "output['Subscription ID'] = ws.subscription_id\n",
"\n", "output['Workspace Name'] = ws.name\n",
"import azureml.core\n", "output['Resource Group'] = ws.resource_group\n",
"from azureml.core.experiment import Experiment\n", "output['Location'] = ws.location\n",
"from azureml.core.workspace import Workspace\n", "output['Experiment Name'] = experiment.name\n",
"from azureml.train.automl import AutoMLConfig\n", "pd.set_option('display.max_colwidth', -1)\n",
"from azureml.train.automl.run import AutoMLRun" "pd.DataFrame(data = output, index = ['']).T"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"execution_count": null, "## Data\n",
"source": [ "\n",
"ws = Workspace.from_config()\n", "We will create a simple dataset using the numpy sin function just for this example. We need just over 50k rows."
"\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", "cell_type": "code",
"\n", "execution_count": null,
"experiment = Experiment(ws, experiment_name)\n", "metadata": {},
"\n", "outputs": [],
"output = {}\n", "source": [
"output['SDK version'] = azureml.core.VERSION\n", "base = np.arange(60000)\n",
"output['Subscription ID'] = ws.subscription_id\n", "cos = np.cos(base)\n",
"output['Workspace Name'] = ws.name\n", "y = np.round(np.sin(base)).astype('int')\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "# Exclude the first 100 rows from training so that they can be used for test.\n",
"output['Project Directory'] = project_folder\n", "X_train = np.hstack((base.reshape(-1, 1), cos.reshape(-1, 1)))\n",
"output['Experiment Name'] = experiment.name\n", "y_train = y"
"pd.set_option('display.max_colwidth', -1)\n", ]
"pd.DataFrame(data = output, index = ['']).T" },
], {
"cell_type": "code" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "## Train\n",
"source": [ "\n",
"## Data\n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
"\n", "\n",
"We will create a simple dataset using the numpy sin function just for this example. We need just over 50k rows." "|Property|Description|\n",
], "|-|-|\n",
"cell_type": "markdown" "|**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",
"metadata": {}, "\n"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"base = np.arange(60000)\n", "cell_type": "code",
"cos = np.cos(base)\n", "execution_count": null,
"y = np.round(np.sin(base)).astype('int')\n", "metadata": {},
"\n", "outputs": [],
"# Exclude the first 100 rows from training so that they can be used for test.\n", "source": [
"X_train = np.hstack((base.reshape(-1, 1), cos.reshape(-1, 1)))\n", "automl_config = AutoMLConfig(task = 'classification',\n",
"y_train = y" " debug_log = 'automl_errors.log',\n",
], " primary_metric = 'accuracy',\n",
"cell_type": "code" " iterations = 85,\n",
}, " experiment_timeout_minutes = 5,\n",
{ " n_cross_validations = 2,\n",
"metadata": {}, " verbosity = logging.INFO,\n",
"source": [ " X = X_train, \n",
"## Train\n", " y = y_train,\n",
"\n", " enable_subsampling=True)"
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", ]
"\n", },
"|Property|Description|\n", {
"|-|-|\n", "cell_type": "markdown",
"|**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", "metadata": {},
"|**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", "source": [
"|**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", "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",
"\n" "In this example, we specify `show_output = True` to print currently running iterations to the console."
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"automl_config = AutoMLConfig(task = 'classification',\n", "local_run = experiment.submit(automl_config, show_output = True)"
" debug_log = 'automl_errors.log',\n", ]
" primary_metric = 'accuracy',\n", }
" iterations = 85,\n", ],
" experiment_timeout_minutes = 5,\n", "metadata": {
" n_cross_validations = 2,\n", "authors": [
" verbosity = logging.INFO,\n", {
" X = X_train, \n", "name": "rogehe"
" y = y_train,\n", }
" enable_subsampling=True,\n", ],
" path = project_folder)" "kernelspec": {
], "display_name": "Python 3.6",
"cell_type": "code" "language": "python",
}, "name": "python36"
{ },
"metadata": {}, "language_info": {
"source": [ "codemirror_mode": {
"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", "name": "ipython",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "version": 3
], },
"cell_type": "markdown" "file_extension": ".py",
}, "mimetype": "text/x-python",
{ "name": "python",
"metadata": {}, "nbconvert_exporter": "python",
"outputs": [], "pygments_lexer": "ipython3",
"execution_count": null, "version": "3.6.6"
"source": [ }
"local_run = experiment.submit(automl_config, show_output = True)" },
], "nbformat": 4,
"cell_type": "code" "nbformat_minor": 2
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"source": [],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-subsampling-local name: auto-ml-subsampling-local
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,33 +1,73 @@
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. 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. 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. - 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 keep the data within the same cluster.
- You can leverage the local worker nodes with autoscale and auto termination capabilities. - 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 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. - 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. - 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. - 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. 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** - **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. 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. 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. 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. 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** **Databricks as a Compute Target from Azure ML 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). 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). # Linked Azure Databricks and Azure Machine Learning Workspaces (Preview)
Customers can now link Azure Databricks and AzureML Workspaces to better enable cross-Azure ML scenarios by [managing their tracking data in a single place when using the MLflow client](https://mlflow.org/docs/latest/tracking.html#mlflow-tracking) - the Azure ML workspace.
**Please let us know your feedback.**
## Linking the Workspaces (Admin operation)
1. The Azure Databricks Azure portal blade now includes a new button to link an Azure ML workspace.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/README.png) ![New ADB Portal Link button](./img/adb-link-button.png)
2. Both a new or existing Azure ML Workspace can be linked in the resulting prompt. Follow any instructions to set up the Azure ML Workspace.
![Link Prompt](./img/link-prompt.png)
3. After a successful link operation, you should see the Azure Databricks overview reflect the linked status
![Linked Successfully](./img/adb-successful-link.png)
## Configure MLflow to send data to Azure ML (All roles)
1. Add azureml-mlflow as a library to any notebook or cluster that should send data to Azure ML. You can do this via:
1. [DBUtils](https://docs.azuredatabricks.net/user-guide/dev-tools/dbutils.html#dbutils-library)
```
dbutils.library.installPyPI("azureml-mlflow")
dbutils.library.restartPython() # Removes Python state
```
2. [Cluster Libraries](https://docs.azuredatabricks.net/user-guide/libraries.html#install-a-library-on-a-cluster)
![Cluster Library](./img/cluster-library.png)
2. [Set the MLflow tracking URI](https://mlflow.org/docs/latest/tracking.html#where-runs-are-recorded) to the following scheme:
```
adbazureml://${azuremlRegion}.experiments.azureml.net/history/v1.0/subscriptions/${azuremlSubscriptionId}/resourceGroups/${azuremlResourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/${azuremlWorkspaceName}
```
1. You can automatically configure this on your clusters for all subsequent notebook sessions using this helper script instead of manually setting the tracking URI in the notebook:
* [AzureML Tracking Cluster Init Script](./linking/README.md)
3. If configured correctly, you'll now be able to see your MLflow tracking data in both Azure ML (via the REST API and all clients) and Azure Databricks (in the MLflow UI and using the MLflow client)
## Known Preview Limitations
While we roll this experience out to customers for feedback, there are some known limitations we'd love comments on in addition to any other issues seen in your workflow.
### 1-to-1 Workspace linking
Currently, an Azure ML Workspace can only be linked to one Azure Databricks Workspace at a time.
### Data synchronization
At the moment, data is only generated in the Azure Machine Learning workspace for tracking. Editing tags via the Azure Databricks MLflow UI won't be reflected in the Azure ML UI.
### Java and R support
The experience currently is only available from the Python MLflow client.
For more on SDK concepts, please refer to [notebooks](https://github.com/Azure/MachineLearningNotebooks).
**Please let us know your feedback.**
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/README.png)

View File

@@ -1,380 +1,373 @@
{ {
"metadata": { "cells": [
"name": "build-model-run-history-03", {
"kernelspec": { "cell_type": "markdown",
"display_name": "Python 3.6", "metadata": {},
"name": "python36", "source": [
"language": "python" "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
}, "\n",
"authors": [ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
{ "\n",
"name": "pasha" "Licensed under the MIT License."
} ]
], },
"language_info": { {
"mimetype": "text/x-python", "cell_type": "markdown",
"codemirror_mode": { "metadata": {},
"name": "ipython", "source": [
"version": 3 "#Model Building"
}, ]
"pygments_lexer": "ipython3", },
"name": "python", {
"file_extension": ".py", "cell_type": "code",
"nbconvert_exporter": "python", "execution_count": null,
"version": "3.6.6" "metadata": {},
}, "outputs": [],
"notebookId": 3836944406456339 "source": [
}, "import os\n",
"nbformat": 4, "import pprint\n",
"cells": [ "import numpy as np\n",
{ "\n",
"metadata": {}, "from pyspark.ml import Pipeline, PipelineModel\n",
"source": [ "from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler\n",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "from pyspark.ml.classification import LogisticRegression\n",
"\n", "from pyspark.ml.evaluation import BinaryClassificationEvaluator\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "from pyspark.ml.tuning import CrossValidator, ParamGridBuilder"
"\n", ]
"Licensed under the MIT License." },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/build-model-run-history-03.png)" "import azureml.core\n",
], "\n",
"cell_type": "markdown" "# Check core SDK version number\n",
}, "print(\"SDK version:\", azureml.core.VERSION)"
{ ]
"metadata": {}, },
"source": [ {
"#Model Building" "cell_type": "code",
], "execution_count": null,
"cell_type": "markdown" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "# Set auth to be used by workspace related APIs.\n",
"outputs": [], "# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
"execution_count": null, "# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
"source": [ "auth = None"
"import os\n", ]
"import pprint\n", },
"import numpy as np\n", {
"\n", "cell_type": "code",
"from pyspark.ml import Pipeline, PipelineModel\n", "execution_count": null,
"from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler\n", "metadata": {},
"from pyspark.ml.classification import LogisticRegression\n", "outputs": [],
"from pyspark.ml.evaluation import BinaryClassificationEvaluator\n", "source": [
"from pyspark.ml.tuning import CrossValidator, ParamGridBuilder" "# import the Workspace class and check the azureml SDK version\n",
], "from azureml.core import Workspace\n",
"cell_type": "code" "\n",
}, "ws = Workspace.from_config(auth = auth)\n",
{ "print('Workspace name: ' + ws.name, \n",
"metadata": {}, " 'Azure region: ' + ws.location, \n",
"outputs": [], " 'Subscription id: ' + ws.subscription_id, \n",
"execution_count": null, " 'Resource group: ' + ws.resource_group, sep = '\\n')"
"source": [ ]
"import azureml.core\n", },
"\n", {
"# Check core SDK version number\n", "cell_type": "code",
"print(\"SDK version:\", azureml.core.VERSION)" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "#get the train and test datasets\n",
"metadata": {}, "train_data_path = \"AdultCensusIncomeTrain\"\n",
"outputs": [], "test_data_path = \"AdultCensusIncomeTest\"\n",
"execution_count": null, "\n",
"source": [ "train = spark.read.parquet(train_data_path)\n",
"# Set auth to be used by workspace related APIs.\n", "test = spark.read.parquet(test_data_path)\n",
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n", "\n",
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n", "print(\"train: ({}, {})\".format(train.count(), len(train.columns)))\n",
"auth = None" "print(\"test: ({}, {})\".format(test.count(), len(test.columns)))\n",
], "\n",
"cell_type": "code" "train.printSchema()"
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "markdown",
"execution_count": null, "metadata": {},
"source": [ "source": [
"# import the Workspace class and check the azureml SDK version\n", "#Define Model"
"from azureml.core import Workspace\n", ]
"\n", },
"ws = Workspace.from_config(auth = auth)\n", {
"print('Workspace name: ' + ws.name, \n", "cell_type": "code",
" 'Azure region: ' + ws.location, \n", "execution_count": null,
" 'Subscription id: ' + ws.subscription_id, \n", "metadata": {},
" 'Resource group: ' + ws.resource_group, sep = '\\n')" "outputs": [],
], "source": [
"cell_type": "code" "label = \"income\"\n",
}, "dtypes = dict(train.dtypes)\n",
{ "dtypes.pop(label)\n",
"metadata": {}, "\n",
"outputs": [], "si_xvars = []\n",
"execution_count": null, "ohe_xvars = []\n",
"source": [ "featureCols = []\n",
"#get the train and test datasets\n", "for idx,key in enumerate(dtypes):\n",
"train_data_path = \"AdultCensusIncomeTrain\"\n", " if dtypes[key] == \"string\":\n",
"test_data_path = \"AdultCensusIncomeTest\"\n", " featureCol = \"-\".join([key, \"encoded\"])\n",
"\n", " featureCols.append(featureCol)\n",
"train = spark.read.parquet(train_data_path)\n", " \n",
"test = spark.read.parquet(test_data_path)\n", " tmpCol = \"-\".join([key, \"tmp\"])\n",
"\n", " # string-index and one-hot encode the string column\n",
"print(\"train: ({}, {})\".format(train.count(), len(train.columns)))\n", " #https://spark.apache.org/docs/2.3.0/api/java/org/apache/spark/ml/feature/StringIndexer.html\n",
"print(\"test: ({}, {})\".format(test.count(), len(test.columns)))\n", " #handleInvalid: Param for how to handle invalid data (unseen labels or NULL values). \n",
"\n", " #Options are 'skip' (filter out rows with invalid data), 'error' (throw an error), \n",
"train.printSchema()" " #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",
"cell_type": "code" " ohe_xvars.append(OneHotEncoder(inputCol=tmpCol, outputCol=featureCol))\n",
}, " else:\n",
{ " featureCols.append(key)\n",
"metadata": {}, "\n",
"source": [ "# string-index the label column into a column named \"label\"\n",
"#Define Model" "si_label = StringIndexer(inputCol=label, outputCol='label')\n",
], "\n",
"cell_type": "markdown" "# assemble the encoded feature columns in to a column named \"features\"\n",
}, "assembler = VectorAssembler(inputCols=featureCols, outputCol=\"features\")"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "code",
"source": [ "execution_count": null,
"label = \"income\"\n", "metadata": {},
"dtypes = dict(train.dtypes)\n", "outputs": [],
"dtypes.pop(label)\n", "source": [
"\n", "from azureml.core.run import Run\n",
"si_xvars = []\n", "from azureml.core.experiment import Experiment\n",
"ohe_xvars = []\n", "import numpy as np\n",
"featureCols = []\n", "import os\n",
"for idx,key in enumerate(dtypes):\n", "import shutil\n",
" if dtypes[key] == \"string\":\n", "\n",
" featureCol = \"-\".join([key, \"encoded\"])\n", "model_name = \"AdultCensus_runHistory.mml\"\n",
" featureCols.append(featureCol)\n", "model_dbfs = os.path.join(\"/dbfs\", model_name)\n",
" \n", "run_history_name = 'spark-ml-notebook'\n",
" tmpCol = \"-\".join([key, \"tmp\"])\n", "\n",
" # string-index and one-hot encode the string column\n", "# start a training run by defining an experiment\n",
" #https://spark.apache.org/docs/2.3.0/api/java/org/apache/spark/ml/feature/StringIndexer.html\n", "myexperiment = Experiment(ws, \"Ignite_AI_Talk\")\n",
" #handleInvalid: Param for how to handle invalid data (unseen labels or NULL values). \n", "root_run = myexperiment.start_logging()\n",
" #Options are 'skip' (filter out rows with invalid data), 'error' (throw an error), \n", "\n",
" #or 'keep' (put invalid data in a special additional bucket, at index numLabels). Default: \"error\"\n", "# Regularization Rates - \n",
" si_xvars.append(StringIndexer(inputCol=key, outputCol=tmpCol, handleInvalid=\"skip\"))\n", "regs = [0.0001, 0.001, 0.01, 0.1]\n",
" ohe_xvars.append(OneHotEncoder(inputCol=tmpCol, outputCol=featureCol))\n", " \n",
" else:\n", "# try a bunch of regularization rate in a Logistic Regression model\n",
" featureCols.append(key)\n", "for reg in regs:\n",
"\n", " print(\"Regularization rate: {}\".format(reg))\n",
"# string-index the label column into a column named \"label\"\n", " # create a bunch of child runs\n",
"si_label = StringIndexer(inputCol=label, outputCol='label')\n", " with root_run.child_run(\"reg-\" + str(reg)) as run:\n",
"\n", " # create a new Logistic Regression model.\n",
"# assemble the encoded feature columns in to a column named \"features\"\n", " lr = LogisticRegression(regParam=reg)\n",
"assembler = VectorAssembler(inputCols=featureCols, outputCol=\"features\")" " \n",
], " # put together the pipeline\n",
"cell_type": "code" " pipe = Pipeline(stages=[*si_xvars, *ohe_xvars, si_label, assembler, lr])\n",
}, "\n",
{ " # train the model\n",
"metadata": {}, " model_p = pipe.fit(train)\n",
"outputs": [], " \n",
"execution_count": null, " # make prediction\n",
"source": [ " pred = model_p.transform(test)\n",
"from azureml.core.run import Run\n", " \n",
"from azureml.core.experiment import Experiment\n", " # evaluate. note only 2 metrics are supported out of the box by Spark ML.\n",
"import numpy as np\n", " bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n",
"import os\n", " au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n",
"import shutil\n", " au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
"\n", "\n",
"model_name = \"AdultCensus_runHistory.mml\"\n", " print(\"Area under ROC: {}\".format(au_roc))\n",
"model_dbfs = os.path.join(\"/dbfs\", model_name)\n", " print(\"Area Under PR: {}\".format(au_prc))\n",
"run_history_name = 'spark-ml-notebook'\n", " \n",
"\n", " # log reg, au_roc, au_prc and feature names in run history\n",
"# start a training run by defining an experiment\n", " run.log(\"reg\", reg)\n",
"myexperiment = Experiment(ws, \"Ignite_AI_Talk\")\n", " run.log(\"au_roc\", au_roc)\n",
"root_run = myexperiment.start_logging()\n", " run.log(\"au_prc\", au_prc)\n",
"\n", " run.log_list(\"columns\", train.columns)\n",
"# Regularization Rates - \n", "\n",
"regs = [0.0001, 0.001, 0.01, 0.1]\n", " # save model\n",
" \n", " model_p.write().overwrite().save(model_name)\n",
"# try a bunch of regularization rate in a Logistic Regression model\n", " \n",
"for reg in regs:\n", " # upload the serialized model into run history record\n",
" print(\"Regularization rate: {}\".format(reg))\n", " mdl, ext = model_name.split(\".\")\n",
" # create a bunch of child runs\n", " model_zip = mdl + \".zip\"\n",
" with root_run.child_run(\"reg-\" + str(reg)) as run:\n", " shutil.make_archive(mdl, 'zip', model_dbfs)\n",
" # create a new Logistic Regression model.\n", " run.upload_file(\"outputs/\" + model_name, model_zip) \n",
" lr = LogisticRegression(regParam=reg)\n", " #run.upload_file(\"outputs/\" + model_name, path_or_stream = model_dbfs) #cannot deal with folders\n",
" \n", "\n",
" # put together the pipeline\n", " # now delete the serialized model from local folder since it is already uploaded to run history \n",
" pipe = Pipeline(stages=[*si_xvars, *ohe_xvars, si_label, assembler, lr])\n", " shutil.rmtree(model_dbfs)\n",
"\n", " os.remove(model_zip)\n",
" # train the model\n", " \n",
" model_p = pipe.fit(train)\n", "# Declare run completed\n",
" \n", "root_run.complete()\n",
" # make prediction\n", "root_run_id = root_run.id\n",
" pred = model_p.transform(test)\n", "print (\"run id:\", root_run.id)"
" \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", "cell_type": "code",
" au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n", "execution_count": null,
"\n", "metadata": {},
" print(\"Area under ROC: {}\".format(au_roc))\n", "outputs": [],
" print(\"Area Under PR: {}\".format(au_prc))\n", "source": [
" \n", "metrics = root_run.get_metrics(recursive=True)\n",
" # log reg, au_roc, au_prc and feature names in run history\n", "best_run_id = max(metrics, key = lambda k: metrics[k]['au_roc'])\n",
" run.log(\"reg\", reg)\n", "print(best_run_id, metrics[best_run_id]['au_roc'], metrics[best_run_id]['reg'])"
" run.log(\"au_roc\", au_roc)\n", ]
" run.log(\"au_prc\", au_prc)\n", },
" run.log_list(\"columns\", train.columns)\n", {
"\n", "cell_type": "code",
" # save model\n", "execution_count": null,
" model_p.write().overwrite().save(model_name)\n", "metadata": {},
" \n", "outputs": [],
" # upload the serialized model into run history record\n", "source": [
" mdl, ext = model_name.split(\".\")\n", "#Get the best run\n",
" model_zip = mdl + \".zip\"\n", "child_runs = {}\n",
" shutil.make_archive(mdl, 'zip', model_dbfs)\n", "\n",
" run.upload_file(\"outputs/\" + model_name, model_zip) \n", "for r in root_run.get_children():\n",
" #run.upload_file(\"outputs/\" + model_name, path_or_stream = model_dbfs) #cannot deal with folders\n", " child_runs[r.id] = r\n",
"\n", " \n",
" # now delete the serialized model from local folder since it is already uploaded to run history \n", "best_run = child_runs[best_run_id]"
" shutil.rmtree(model_dbfs)\n", ]
" os.remove(model_zip)\n", },
" \n", {
"# Declare run completed\n", "cell_type": "code",
"root_run.complete()\n", "execution_count": null,
"root_run_id = root_run.id\n", "metadata": {},
"print (\"run id:\", root_run.id)" "outputs": [],
], "source": [
"cell_type": "code" "#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)"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "markdown",
"metrics = root_run.get_metrics(recursive=True)\n", "metadata": {},
"best_run_id = max(metrics, key = lambda k: metrics[k]['au_roc'])\n", "source": [
"print(best_run_id, metrics[best_run_id]['au_roc'], metrics[best_run_id]['reg'])" "#Model Evaluation"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"#Get the best run\n", "##unzip the model to dbfs (as load() seems to require that) and load it.\n",
"child_runs = {}\n", "if os.path.isfile(model_dbfs) or os.path.isdir(model_dbfs):\n",
"\n", " shutil.rmtree(model_dbfs)\n",
"for r in root_run.get_children():\n", "shutil.unpack_archive(best_model_file_name, model_dbfs)\n",
" child_runs[r.id] = r\n", "\n",
" \n", "model_p_best = PipelineModel.load(model_name)"
"best_run = child_runs[best_run_id]" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "# make prediction\n",
"#Download the model from the best run to a local folder\n", "pred = model_p_best.transform(test)\n",
"best_model_file_name = \"best_model.zip\"\n", "output = pred[['hours_per_week','age','workclass','marital_status','income','prediction']]\n",
"best_run.download_file(name = 'outputs/' + model_name, output_file_path = best_model_file_name)" "display(output.limit(5))"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"#Model Evaluation" "outputs": [],
], "source": [
"cell_type": "markdown" "# 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",
"metadata": {}, "au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
"outputs": [], "\n",
"execution_count": null, "print(\"Area under ROC: {}\".format(au_roc))\n",
"source": [ "print(\"Area Under PR: {}\".format(au_prc))"
"##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", "cell_type": "markdown",
"\n", "metadata": {},
"model_p_best = PipelineModel.load(model_name)" "source": [
], "#Model Persistence"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"# make prediction\n", "source": [
"pred = model_p_best.transform(test)\n", "##NOTE: by default the model is saved to and loaded from /dbfs/ instead of cwd!\n",
"output = pred[['hours_per_week','age','workclass','marital_status','income','prediction']]\n", "model_p_best.write().overwrite().save(model_name)\n",
"display(output.limit(5))" "print(\"saved model to {}\".format(model_dbfs))"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"# evaluate. note only 2 metrics are supported out of the box by Spark ML.\n", "%sh\n",
"bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n", "\n",
"au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n", "ls -la /dbfs/AdultCensus_runHistory.mml/*"
"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": "code",
], "execution_count": null,
"cell_type": "code" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "dbutils.notebook.exit(\"success\")"
"source": [ ]
"#Model Persistence" },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/build-model-run-history-03.png)"
"outputs": [], ]
"execution_count": null, }
"source": [ ],
"##NOTE: by default the model is saved to and loaded from /dbfs/ instead of cwd!\n", "metadata": {
"model_p_best.write().overwrite().save(model_name)\n", "authors": [
"print(\"saved model to {}\".format(model_dbfs))" {
], "name": "pasha"
"cell_type": "code" }
}, ],
{ "kernelspec": {
"metadata": {}, "display_name": "Python 3.6",
"outputs": [], "language": "python",
"execution_count": null, "name": "python36"
"source": [ },
"%sh\n", "language_info": {
"\n", "codemirror_mode": {
"ls -la /dbfs/AdultCensus_runHistory.mml/*" "name": "ipython",
], "version": 3
"cell_type": "code" },
}, "file_extension": ".py",
{ "mimetype": "text/x-python",
"metadata": {}, "name": "python",
"outputs": [], "nbconvert_exporter": "python",
"execution_count": null, "pygments_lexer": "ipython3",
"source": [ "version": "3.6.6"
"dbutils.notebook.exit(\"success\")" },
], "name": "build-model-run-history-03",
"cell_type": "code" "notebookId": 3836944406456339
}, },
{ "nbformat": 4,
"metadata": {}, "nbformat_minor": 1
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/build-model-run-history-03.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

View File

@@ -1,324 +1,293 @@
{ {
"metadata": { "cells": [
"name": "deploy-to-aci-04", {
"kernelspec": { "cell_type": "markdown",
"display_name": "Python 3.6", "metadata": {},
"name": "python36", "source": [
"language": "python" "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
}, "\n",
"authors": [ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
{ "\n",
"name": "pasha" "Licensed under the MIT License."
} ]
], },
"language_info": { {
"mimetype": "text/x-python", "cell_type": "markdown",
"codemirror_mode": { "metadata": {},
"name": "ipython", "source": [
"version": 3 "Please ensure you have run all previous notebooks in sequence before running this.\n",
}, "\n",
"pygments_lexer": "ipython3", "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."
"name": "python", ]
"file_extension": ".py", },
"nbconvert_exporter": "python", {
"version": "3.6.6" "cell_type": "code",
}, "execution_count": null,
"notebookId": 3836944406456376 "metadata": {},
}, "outputs": [],
"nbformat": 4, "source": [
"cells": [ "import azureml.core\n",
{ "\n",
"metadata": {}, "# Check core SDK version number\n",
"source": [ "print(\"SDK version:\", azureml.core.VERSION)"
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", ]
"\n", },
"Copyright (c) Microsoft Corporation. All rights reserved.\n", {
"\n", "cell_type": "code",
"Licensed under the MIT License." "execution_count": null,
], "metadata": {},
"cell_type": "markdown" "outputs": [],
}, "source": [
{ "# Set auth to be used by workspace related APIs.\n",
"metadata": {}, "# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
"source": [ "# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/deploy-to-aci-04.png)" "auth = None"
], ]
"cell_type": "markdown" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"Please ensure you have run all previous notebooks in sequence before running this.\n", "outputs": [],
"\n", "source": [
"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." "from azureml.core import Workspace\n",
], "\n",
"cell_type": "markdown" "ws = Workspace.from_config(auth = auth)\n",
}, "print('Workspace name: ' + ws.name, \n",
{ " 'Azure region: ' + ws.location, \n",
"metadata": {}, " 'Subscription id: ' + ws.subscription_id, \n",
"outputs": [], " 'Resource group: ' + ws.resource_group, sep = '\\n')"
"execution_count": null, ]
"source": [ },
"import azureml.core\n", {
"\n", "cell_type": "code",
"# Check core SDK version number\n", "execution_count": null,
"print(\"SDK version:\", azureml.core.VERSION)" "metadata": {},
], "outputs": [],
"cell_type": "code" "source": [
}, "##NOTE: service deployment always gets the model from the current working dir.\n",
{ "import os\n",
"metadata": {}, "\n",
"outputs": [], "model_name = \"AdultCensus_runHistory.mml\" # \n",
"execution_count": null, "model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n",
"source": [ "\n",
"# Set auth to be used by workspace related APIs.\n", "print(\"copy model from dbfs to local\")\n",
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n", "model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n",
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n", "dbutils.fs.cp(model_name, model_local, True)"
"auth = None" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "#Register the model\n",
"from azureml.core import Workspace\n", "from azureml.core.model import Model\n",
"\n", "mymodel = Model.register(model_path = model_name, # this points to a local file\n",
"ws = Workspace.from_config(auth = auth)\n", " model_name = model_name, # this is the name the model is registered as, am using same name for both path and name. \n",
"print('Workspace name: ' + ws.name, \n", " description = \"ADB trained model by Parashar\",\n",
" 'Azure region: ' + ws.location, \n", " workspace = ws)\n",
" 'Subscription id: ' + ws.subscription_id, \n", "\n",
" 'Resource group: ' + ws.resource_group, sep = '\\n')" "print(mymodel.name, mymodel.description, mymodel.version)"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"outputs": [], "metadata": {},
"execution_count": null, "outputs": [],
"source": [ "source": [
"##NOTE: service deployment always gets the model from the current working dir.\n", "#%%writefile score_sparkml.py\n",
"import os\n", "score_sparkml = \"\"\"\n",
"\n", " \n",
"model_name = \"AdultCensus_runHistory.mml\" # \n", "import json\n",
"model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n", " \n",
"\n", "def init():\n",
"print(\"copy model from dbfs to local\")\n", " # One-time initialization of PySpark and predictive model\n",
"model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n", " import pyspark\n",
"dbutils.fs.cp(model_name, model_local, True)" " from azureml.core.model import Model\n",
], " from pyspark.ml import PipelineModel\n",
"cell_type": "code" " \n",
}, " global trainedModel\n",
{ " global spark\n",
"metadata": {}, " \n",
"outputs": [], " spark = pyspark.sql.SparkSession.builder.appName(\"ADB and AML notebook by Parashar\").getOrCreate()\n",
"execution_count": null, " model_name = \"{model_name}\" #interpolated\n",
"source": [ " model_path = Model.get_model_path(model_name)\n",
"#Register the model\n", " trainedModel = PipelineModel.load(model_path)\n",
"from azureml.core.model import Model\n", " \n",
"mymodel = Model.register(model_path = model_name, # this points to a local file\n", "def run(input_json):\n",
" model_name = model_name, # this is the name the model is registered as, am using same name for both path and name. \n", " if isinstance(trainedModel, Exception):\n",
" description = \"ADB trained model by Parashar\",\n", " return json.dumps({{\"trainedModel\":str(trainedModel)}})\n",
" workspace = ws)\n", " \n",
"\n", " try:\n",
"print(mymodel.name, mymodel.description, mymodel.version)" " sc = spark.sparkContext\n",
], " input_list = json.loads(input_json)\n",
"cell_type": "code" " input_rdd = sc.parallelize(input_list)\n",
}, " input_df = spark.read.json(input_rdd)\n",
{ " \n",
"metadata": {}, " # Compute prediction\n",
"outputs": [], " prediction = trainedModel.transform(input_df)\n",
"execution_count": null, " #result = prediction.first().prediction\n",
"source": [ " predictions = prediction.collect()\n",
"#%%writefile score_sparkml.py\n", " \n",
"score_sparkml = \"\"\"\n", " #Get each scored result\n",
" \n", " preds = [str(x['prediction']) for x in predictions]\n",
"import json\n", " result = \",\".join(preds)\n",
" \n", " # you can return any data type as long as it is JSON-serializable\n",
"def init():\n", " return result.tolist()\n",
" # One-time initialization of PySpark and predictive model\n", " except Exception as e:\n",
" import pyspark\n", " result = str(e)\n",
" from azureml.core.model import Model\n", " return result\n",
" from pyspark.ml import PipelineModel\n", " \n",
" \n", "\"\"\".format(model_name=model_name)\n",
" global trainedModel\n", " \n",
" global spark\n", "exec(score_sparkml)\n",
" \n", " \n",
" spark = pyspark.sql.SparkSession.builder.appName(\"ADB and AML notebook by Parashar\").getOrCreate()\n", "with open(\"score_sparkml.py\", \"w\") as file:\n",
" model_name = \"{model_name}\" #interpolated\n", " file.write(score_sparkml)"
" model_path = Model.get_model_path(model_name)\n", ]
" trainedModel = PipelineModel.load(model_path)\n", },
" \n", {
"def run(input_json):\n", "cell_type": "code",
" if isinstance(trainedModel, Exception):\n", "execution_count": null,
" return json.dumps({{\"trainedModel\":str(trainedModel)}})\n", "metadata": {},
" \n", "outputs": [],
" try:\n", "source": [
" sc = spark.sparkContext\n", "from azureml.core.conda_dependencies import CondaDependencies \n",
" input_list = json.loads(input_json)\n", "\n",
" input_rdd = sc.parallelize(input_list)\n", "myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) #showing how to add libs as an eg. - not needed for this model.\n",
" input_df = spark.read.json(input_rdd)\n", "\n",
" \n", "with open(\"mydeployenv.yml\",\"w\") as f:\n",
" # Compute prediction\n", " f.write(myacienv.serialize_to_string())"
" prediction = trainedModel.transform(input_df)\n", ]
" #result = prediction.first().prediction\n", },
" predictions = prediction.collect()\n", {
" \n", "cell_type": "code",
" #Get each scored result\n", "execution_count": null,
" preds = [str(x['prediction']) for x in predictions]\n", "metadata": {},
" result = \",\".join(preds)\n", "outputs": [],
" # you can return any data type as long as it is JSON-serializable\n", "source": [
" return result.tolist()\n", "#deploy to ACI\n",
" except Exception as e:\n", "from azureml.core.webservice import AciWebservice, Webservice\n",
" result = str(e)\n", "from azureml.core.model import InferenceConfig\n",
" return result\n", "\n",
" \n", "myaci_config = AciWebservice.deploy_configuration(cpu_cores = 2, \n",
"\"\"\".format(model_name=model_name)\n", " memory_gb = 2, \n",
" \n", " tags = {'name':'Databricks Azure ML ACI'}, \n",
"exec(score_sparkml)\n", " description = 'This is for ADB and AML example.')\n",
" \n", "\n",
"with open(\"score_sparkml.py\", \"w\") as file:\n", "inference_config = InferenceConfig(runtime= 'spark-py', \n",
" file.write(score_sparkml)" " entry_script='score_sparkml.py',\n",
], " conda_file='mydeployenv.yml')\n",
"cell_type": "code" "\n",
}, "myservice = Model.deploy(ws, 'aciws', [mymodel], inference_config, myaci_config)\n",
{ "myservice.wait_for_deployment(show_output=True)"
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "code",
"from azureml.core.conda_dependencies import CondaDependencies \n", "execution_count": null,
"\n", "metadata": {},
"myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) #showing how to add libs as an eg. - not needed for this model.\n", "outputs": [],
"\n", "source": [
"with open(\"mydeployenv.yml\",\"w\") as f:\n", "help(Webservice)"
" f.write(myacienv.serialize_to_string())" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "# List images by ws\n",
"#deploy to ACI\n", "\n",
"from azureml.core.webservice import AciWebservice, Webservice\n", "for i in ContainerImage.list(workspace = ws):\n",
"\n", " print('{}(v.{} [{}]) stored at {} with build log {}'.format(i.name, i.version, i.creation_state, i.image_location, i.image_build_log_uri))"
"myaci_config = AciWebservice.deploy_configuration(\n", ]
" cpu_cores = 2, \n", },
" memory_gb = 2, \n", {
" tags = {'name':'Databricks Azure ML ACI'}, \n", "cell_type": "code",
" description = 'This is for ADB and AML example. Azure Databricks & Azure ML SDK demo with ACI by Parashar.')" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "#for using the Web HTTP API \n",
"metadata": {}, "print(myservice.scoring_uri)"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"# this will take 10-15 minutes to finish\n", "cell_type": "code",
"\n", "execution_count": null,
"service_name = \"aciws\"\n", "metadata": {},
"runtime = \"spark-py\" \n", "outputs": [],
"driver_file = \"score_sparkml.py\"\n", "source": [
"my_conda_file = \"mydeployenv.yml\"\n", "import json\n",
"\n", "\n",
"# image creation\n", "#get the some sample data\n",
"from azureml.core.image import ContainerImage\n", "test_data_path = \"AdultCensusIncomeTest\"\n",
"myimage_config = ContainerImage.image_configuration(execution_script = driver_file, \n", "test = spark.read.parquet(test_data_path).limit(5)\n",
" runtime = runtime, \n", "\n",
" conda_file = my_conda_file)\n", "test_json = json.dumps(test.toJSON().collect())\n",
"\n", "\n",
"# Webservice creation\n", "print(test_json)"
"myservice = Webservice.deploy_from_model(\n", ]
" workspace=ws, \n", },
" name=service_name,\n", {
" deployment_config = myaci_config,\n", "cell_type": "code",
" models = [mymodel],\n", "execution_count": null,
" image_config = myimage_config\n", "metadata": {},
" )\n", "outputs": [],
"\n", "source": [
"myservice.wait_for_deployment(show_output=True)" "#using data defined above predict if income is >50K (1) or <=50K (0)\n",
], "myservice.run(input_data=test_json)"
"cell_type": "code" ]
}, },
{ {
"metadata": {}, "cell_type": "code",
"outputs": [], "execution_count": null,
"execution_count": null, "metadata": {},
"source": [ "outputs": [],
"help(Webservice)" "source": [
], "#comment to not delete the web service\n",
"cell_type": "code" "myservice.delete()"
}, ]
{ },
"metadata": {}, {
"outputs": [], "cell_type": "markdown",
"execution_count": null, "metadata": {},
"source": [ "source": [
"# List images by ws\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aci-04.png)"
"\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))" ],
], "metadata": {
"cell_type": "code" "authors": [
}, {
{ "name": "pasha"
"metadata": {}, }
"outputs": [], ],
"execution_count": null, "kernelspec": {
"source": [ "display_name": "Python 3.6",
"#for using the Web HTTP API \n", "language": "python",
"print(myservice.scoring_uri)" "name": "python36"
], },
"cell_type": "code" "language_info": {
}, "codemirror_mode": {
{ "name": "ipython",
"metadata": {}, "version": 3
"outputs": [], },
"execution_count": null, "file_extension": ".py",
"source": [ "mimetype": "text/x-python",
"import json\n", "name": "python",
"\n", "nbconvert_exporter": "python",
"#get the some sample data\n", "pygments_lexer": "ipython3",
"test_data_path = \"AdultCensusIncomeTest\"\n", "version": "3.6.6"
"test = spark.read.parquet(test_data_path).limit(5)\n", },
"\n", "name": "deploy-to-aci-04",
"test_json = json.dumps(test.toJSON().collect())\n", "notebookId": 3836944406456376
"\n", },
"print(test_json)" "nbformat": 4,
], "nbformat_minor": 1
"cell_type": "code"
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"source": [
"#using data defined above predict if income is >50K (1) or <=50K (0)\n",
"myservice.run(input_data=test_json)"
],
"cell_type": "code"
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"source": [
"#comment to not delete the web service\n",
"myservice.delete()"
],
"cell_type": "code"
},
{
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aci-04.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

View File

@@ -1,250 +1,298 @@
{ {
"metadata": { "cells": [
"name": "deploy-to-aks-existingimage-05", {
"kernelspec": { "cell_type": "markdown",
"display_name": "Python 3.6", "metadata": {},
"name": "python36", "source": [
"language": "python" "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
}, "\n",
"authors": [ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
{ "\n",
"name": "pasha" "Licensed under the MIT License."
} ]
], },
"language_info": { {
"mimetype": "text/x-python", "cell_type": "markdown",
"codemirror_mode": { "metadata": {},
"name": "ipython", "source": [
"version": 3 "This notebook uses image from ACI notebook for deploying to AKS."
}, ]
"pygments_lexer": "ipython3", },
"name": "python", {
"file_extension": ".py", "cell_type": "code",
"nbconvert_exporter": "python", "execution_count": null,
"version": "3.6.6" "metadata": {},
}, "outputs": [],
"notebookId": 1030695628045968 "source": [
}, "import azureml.core\n",
"nbformat": 4, "\n",
"cells": [ "# Check core SDK version number\n",
{ "print(\"SDK version:\", azureml.core.VERSION)"
"metadata": {}, ]
"source": [ },
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", {
"\n", "cell_type": "code",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "execution_count": null,
"\n", "metadata": {},
"Licensed under the MIT License." "outputs": [],
], "source": [
"cell_type": "markdown" "# 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",
"metadata": {}, "auth = None"
"source": [ ]
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/deploy-to-aks-existingimage-05.png)" },
], {
"cell_type": "markdown" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "source": [
"This notebook uses image from ACI notebook for deploying to AKS." "from azureml.core import Workspace\n",
], "\n",
"cell_type": "markdown" "ws = Workspace.from_config(auth = auth)\n",
}, "print('Workspace name: ' + ws.name, \n",
{ " 'Azure region: ' + ws.location, \n",
"metadata": {}, " 'Subscription id: ' + ws.subscription_id, \n",
"outputs": [], " 'Resource group: ' + ws.resource_group, sep = '\\n')"
"execution_count": null, ]
"source": [ },
"import azureml.core\n", {
"\n", "cell_type": "code",
"# Check core SDK version number\n", "execution_count": null,
"print(\"SDK version:\", azureml.core.VERSION)" "metadata": {},
], "outputs": [],
"cell_type": "code" "source": [
}, "#Register the model\n",
{ "import os\n",
"metadata": {}, "from azureml.core.model import Model\n",
"outputs": [], "\n",
"execution_count": null, "model_name = \"AdultCensus_runHistory_aks.mml\" # \n",
"source": [ "model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n",
"# Set auth to be used by workspace related APIs.\n", "\n",
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n", "print(\"copy model from dbfs to local\")\n",
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n", "model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n",
"auth = None" "dbutils.fs.cp(model_name, model_local, True)\n",
], "\n",
"cell_type": "code" "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",
"metadata": {}, " workspace = ws)\n",
"outputs": [], "\n",
"execution_count": null, "print(mymodel.name, mymodel.description, mymodel.version)"
"source": [ ]
"from azureml.core import Workspace\n", },
"\n", {
"ws = Workspace.from_config(auth = auth)\n", "cell_type": "code",
"print('Workspace name: ' + ws.name, \n", "execution_count": null,
" 'Azure region: ' + ws.location, \n", "metadata": {},
" 'Subscription id: ' + ws.subscription_id, \n", "outputs": [],
" 'Resource group: ' + ws.resource_group, sep = '\\n')" "source": [
], "#%%writefile score_sparkml.py\n",
"cell_type": "code" "score_sparkml = \"\"\"\n",
}, " \n",
{ "import json\n",
"metadata": {}, " \n",
"outputs": [], "def init():\n",
"execution_count": null, " # One-time initialization of PySpark and predictive model\n",
"source": [ " import pyspark\n",
"# List images by ws\n", " from azureml.core.model import Model\n",
"\n", " from pyspark.ml import PipelineModel\n",
"from azureml.core.image import ContainerImage\n", " \n",
"for i in ContainerImage.list(workspace = ws):\n", " global trainedModel\n",
" print('{}(v.{} [{}]) stored at {} with build log {}'.format(i.name, i.version, i.creation_state, i.image_location, i.image_build_log_uri))" " global spark\n",
], " \n",
"cell_type": "code" " 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",
"metadata": {}, " trainedModel = PipelineModel.load(model_path)\n",
"outputs": [], " \n",
"execution_count": null, "def run(input_json):\n",
"source": [ " if isinstance(trainedModel, Exception):\n",
"from azureml.core.image import Image\n", " return json.dumps({{\"trainedModel\":str(trainedModel)}})\n",
"myimage = Image(workspace=ws, name=\"aciws\")" " \n",
], " try:\n",
"cell_type": "code" " sc = spark.sparkContext\n",
}, " input_list = json.loads(input_json)\n",
{ " input_rdd = sc.parallelize(input_list)\n",
"metadata": {}, " input_df = spark.read.json(input_rdd)\n",
"outputs": [], " \n",
"execution_count": null, " # Compute prediction\n",
"source": [ " prediction = trainedModel.transform(input_df)\n",
"#create AKS compute\n", " #result = prediction.first().prediction\n",
"#it may take 20-25 minutes to create a new cluster\n", " predictions = prediction.collect()\n",
"\n", " \n",
"from azureml.core.compute import AksCompute, ComputeTarget\n", " #Get each scored result\n",
"\n", " preds = [str(x['prediction']) for x in predictions]\n",
"# Use the default configuration (can also provide parameters to customize)\n", " result = \",\".join(preds)\n",
"prov_config = AksCompute.provisioning_configuration()\n", " # you can return any data type as long as it is JSON-serializable\n",
"\n", " return result.tolist()\n",
"aks_name = 'ps-aks-demo2' \n", " except Exception as e:\n",
"\n", " result = str(e)\n",
"# Create the cluster\n", " return result\n",
"aks_target = ComputeTarget.create(workspace = ws, \n", " \n",
" name = aks_name, \n", "\"\"\".format(model_name=model_name)\n",
" provisioning_configuration = prov_config)\n", " \n",
"\n", "exec(score_sparkml)\n",
"aks_target.wait_for_completion(show_output = True)\n", " \n",
"\n", "with open(\"score_sparkml.py\", \"w\") as file:\n",
"print(aks_target.provisioning_state)\n", " file.write(score_sparkml)"
"print(aks_target.provisioning_errors)" ]
], },
"cell_type": "code" {
}, "cell_type": "code",
{ "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"execution_count": null, "source": [
"source": [ "from azureml.core.conda_dependencies import CondaDependencies \n",
"from azureml.core.webservice import Webservice\n", "\n",
"help( Webservice.deploy_from_image)" "myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) #showing how to add libs as an eg. - not needed for this model.\n",
], "\n",
"cell_type": "code" "with open(\"mydeployenv.yml\",\"w\") as f:\n",
}, " f.write(myacienv.serialize_to_string())"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "code",
"source": [ "execution_count": null,
"from azureml.core.webservice import Webservice, AksWebservice\n", "metadata": {},
"from azureml.core.image import ContainerImage\n", "outputs": [],
"\n", "source": [
"#Set the web service configuration (using default here with app insights)\n", "#create AKS compute\n",
"aks_config = AksWebservice.deploy_configuration(enable_app_insights=True)\n", "#it may take 20-25 minutes to create a new cluster\n",
"\n", "\n",
"#unique service name\n", "from azureml.core.compute import AksCompute, ComputeTarget\n",
"service_name ='ps-aks-service'\n", "\n",
"\n", "# Use the default configuration (can also provide parameters to customize)\n",
"# Webservice creation using single command, there is a variant to use image directly as well.\n", "prov_config = AksCompute.provisioning_configuration()\n",
"aks_service = Webservice.deploy_from_image(\n", "\n",
" workspace=ws, \n", "aks_name = 'ps-aks-demo2' \n",
" name=service_name,\n", "\n",
" deployment_config = aks_config,\n", "# Create the cluster\n",
" image = myimage,\n", "aks_target = ComputeTarget.create(workspace = ws, \n",
" deployment_target = aks_target\n", " name = aks_name, \n",
" )\n", " provisioning_configuration = prov_config)\n",
"\n", "\n",
"aks_service.wait_for_deployment(show_output=True)" "aks_target.wait_for_completion(show_output = True)\n",
], "\n",
"cell_type": "code" "print(aks_target.provisioning_state)\n",
}, "print(aks_target.provisioning_errors)"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "code",
"source": [ "execution_count": null,
"aks_service.deployment_status" "metadata": {},
], "outputs": [],
"cell_type": "code" "source": [
}, "#deploy to AKS\n",
{ "from azureml.core.webservice import AksWebservice, Webservice\n",
"metadata": {}, "from azureml.core.model import InferenceConfig\n",
"outputs": [], "\n",
"execution_count": null, "aks_config = AksWebservice.deploy_configuration(enable_app_insights=True)\n",
"source": [ "\n",
"#for using the Web HTTP API \n", "inference_config = InferenceConfig(runtime = 'spark-py', \n",
"print(aks_service.scoring_uri)\n", " entry_script ='score_sparkml.py',\n",
"print(aks_service.get_keys())" " conda_file ='mydeployenv.yml')\n",
], "\n",
"cell_type": "code" "aks_service = Model.deploy(ws, 'ps-aks-service', [mymodel], inference_config, aks_config, aks_target)\n",
}, "aks_service.wait_for_deployment(show_output=True)"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "code",
"source": [ "execution_count": null,
"import json\n", "metadata": {},
"\n", "outputs": [],
"#get the some sample data\n", "source": [
"test_data_path = \"AdultCensusIncomeTest\"\n", "aks_service.deployment_status"
"test = spark.read.parquet(test_data_path).limit(5)\n", ]
"\n", },
"test_json = json.dumps(test.toJSON().collect())\n", {
"\n", "cell_type": "code",
"print(test_json)" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "#for using the Web HTTP API \n",
"metadata": {}, "print(aks_service.scoring_uri)\n",
"outputs": [], "print(aks_service.get_keys())"
"execution_count": null, ]
"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,
"cell_type": "code" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "import json\n",
"outputs": [], "\n",
"execution_count": null, "#get the some sample data\n",
"source": [ "test_data_path = \"AdultCensusIncomeTest\"\n",
"#comment to not delete the web service\n", "test = spark.read.parquet(test_data_path).limit(5)\n",
"aks_service.delete()\n", "\n",
"#image.delete()\n", "test_json = json.dumps(test.toJSON().collect())\n",
"#model.delete()\n", "\n",
"aks_target.delete() " "print(test_json)"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "code",
"metadata": {}, "execution_count": null,
"source": [ "metadata": {},
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aks-existingimage-05.png)" "outputs": [],
], "source": [
"cell_type": "markdown" "#using data defined above predict if income is >50K (1) or <=50K (0)\n",
} "aks_service.run(input_data=test_json)"
], ]
"nbformat_minor": 1 },
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#comment to not delete the web service\n",
"aks_service.delete()\n",
"#model.delete()\n",
"aks_target.delete() "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aks-existingimage-05.png)"
]
}
],
"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
} }

View File

@@ -1,186 +1,179 @@
{ {
"metadata": { "cells": [
"name": "ingest-data-02", {
"kernelspec": { "cell_type": "markdown",
"display_name": "Python 3.6", "metadata": {},
"name": "python36", "source": [
"language": "python" "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
}, "\n",
"authors": [ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
{ "\n",
"name": "pasha" "Licensed under the MIT License."
} ]
], },
"language_info": { {
"mimetype": "text/x-python", "cell_type": "markdown",
"codemirror_mode": { "metadata": {},
"name": "ipython", "source": [
"version": 3 "#Data Ingestion"
}, ]
"pygments_lexer": "ipython3", },
"name": "python", {
"file_extension": ".py", "cell_type": "code",
"nbconvert_exporter": "python", "execution_count": null,
"version": "3.6.6" "metadata": {},
}, "outputs": [],
"notebookId": 3836944406456362 "source": [
}, "import os\n",
"nbformat": 4, "import urllib"
"cells": [ ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "execution_count": null,
"\n", "metadata": {},
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "outputs": [],
"\n", "source": [
"Licensed under the MIT License." "# Download AdultCensusIncome.csv from Azure CDN. This file has 32,561 rows.\n",
], "dataurl = \"https://amldockerdatasets.azureedge.net/AdultCensusIncome.csv\"\n",
"cell_type": "markdown" "datafile = \"AdultCensusIncome.csv\"\n",
}, "datafile_dbfs = os.path.join(\"/dbfs\", datafile)\n",
{ "\n",
"metadata": {}, "if os.path.isfile(datafile_dbfs):\n",
"source": [ " print(\"found {} at {}\".format(datafile, datafile_dbfs))\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/ingest-data-02.png)" "else:\n",
], " print(\"downloading {} to {}\".format(datafile, datafile_dbfs))\n",
"cell_type": "markdown" " urllib.request.urlretrieve(dataurl, datafile_dbfs)"
}, ]
{ },
"metadata": {}, {
"source": [ "cell_type": "code",
"#Data Ingestion" "execution_count": null,
], "metadata": {},
"cell_type": "markdown" "outputs": [],
}, "source": [
{ "# Create a Spark dataframe out of the csv file.\n",
"metadata": {}, "data_all = sqlContext.read.format('csv').options(header='true', inferSchema='true', ignoreLeadingWhiteSpace='true', ignoreTrailingWhiteSpace='true').load(datafile)\n",
"outputs": [], "print(\"({}, {})\".format(data_all.count(), len(data_all.columns)))\n",
"execution_count": null, "data_all.printSchema()"
"source": [ ]
"import os\n", },
"import urllib" {
], "cell_type": "code",
"cell_type": "code" "execution_count": null,
}, "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"outputs": [], "#renaming columns\n",
"execution_count": null, "columns_new = [col.replace(\"-\", \"_\") for col in data_all.columns]\n",
"source": [ "data_all = data_all.toDF(*columns_new)\n",
"# Download AdultCensusIncome.csv from Azure CDN. This file has 32,561 rows.\n", "data_all.printSchema()"
"dataurl = \"https://amldockerdatasets.azureedge.net/AdultCensusIncome.csv\"\n", ]
"datafile = \"AdultCensusIncome.csv\"\n", },
"datafile_dbfs = os.path.join(\"/dbfs\", datafile)\n", {
"\n", "cell_type": "code",
"if os.path.isfile(datafile_dbfs):\n", "execution_count": null,
" print(\"found {} at {}\".format(datafile, datafile_dbfs))\n", "metadata": {},
"else:\n", "outputs": [],
" print(\"downloading {} to {}\".format(datafile, datafile_dbfs))\n", "source": [
" urllib.request.urlretrieve(dataurl, datafile_dbfs)" "display(data_all.limit(5))"
], ]
"cell_type": "code" },
}, {
{ "cell_type": "markdown",
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"execution_count": null, "#Data Preparation"
"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", "cell_type": "code",
"data_all.printSchema()" "execution_count": null,
], "metadata": {},
"cell_type": "code" "outputs": [],
}, "source": [
{ "# Choose feature columns and the label column.\n",
"metadata": {}, "label = \"income\"\n",
"outputs": [], "xvars = set(data_all.columns) - {label}\n",
"execution_count": null, "\n",
"source": [ "print(\"label = {}\".format(label))\n",
"#renaming columns\n", "print(\"features = {}\".format(xvars))\n",
"columns_new = [col.replace(\"-\", \"_\") for col in data_all.columns]\n", "\n",
"data_all = data_all.toDF(*columns_new)\n", "data = data_all.select([*xvars, label])\n",
"data_all.printSchema()" "\n",
], "# Split data into train and test.\n",
"cell_type": "code" "train, test = data.randomSplit([0.75, 0.25], seed=123)\n",
}, "\n",
{ "print(\"train ({}, {})\".format(train.count(), len(train.columns)))\n",
"metadata": {}, "print(\"test ({}, {})\".format(test.count(), len(test.columns)))"
"outputs": [], ]
"execution_count": null, },
"source": [ {
"display(data_all.limit(5))" "cell_type": "markdown",
], "metadata": {},
"cell_type": "code" "source": [
}, "#Data Persistence"
{ ]
"metadata": {}, },
"source": [ {
"#Data Preparation" "cell_type": "code",
], "execution_count": null,
"cell_type": "markdown" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "# Write the train and test data sets to intermediate storage\n",
"outputs": [], "train_data_path = \"AdultCensusIncomeTrain\"\n",
"execution_count": null, "test_data_path = \"AdultCensusIncomeTest\"\n",
"source": [ "\n",
"# Choose feature columns and the label column.\n", "train_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTrain\")\n",
"label = \"income\"\n", "test_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTest\")\n",
"xvars = set(data_all.columns) - {label}\n", "\n",
"\n", "train.write.mode('overwrite').parquet(train_data_path)\n",
"print(\"label = {}\".format(label))\n", "test.write.mode('overwrite').parquet(test_data_path)\n",
"print(\"features = {}\".format(xvars))\n", "print(\"train and test datasets saved to {} and {}\".format(train_data_path_dbfs, test_data_path_dbfs))"
"\n", ]
"data = data_all.select([*xvars, label])\n", },
"\n", {
"# Split data into train and test.\n", "cell_type": "code",
"train, test = data.randomSplit([0.75, 0.25], seed=123)\n", "execution_count": null,
"\n", "metadata": {},
"print(\"train ({}, {})\".format(train.count(), len(train.columns)))\n", "outputs": [],
"print(\"test ({}, {})\".format(test.count(), len(test.columns)))" "source": []
], },
"cell_type": "code" {
}, "cell_type": "markdown",
{ "metadata": {},
"metadata": {}, "source": [
"source": [ "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/ingest-data-02.png)"
"#Data Persistence" ]
], }
"cell_type": "markdown" ],
}, "metadata": {
{ "authors": [
"metadata": {}, {
"outputs": [], "name": "pasha"
"execution_count": null, }
"source": [ ],
"# Write the train and test data sets to intermediate storage\n", "kernelspec": {
"train_data_path = \"AdultCensusIncomeTrain\"\n", "display_name": "Python 3.6",
"test_data_path = \"AdultCensusIncomeTest\"\n", "language": "python",
"\n", "name": "python36"
"train_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTrain\")\n", },
"test_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTest\")\n", "language_info": {
"\n", "codemirror_mode": {
"train.write.mode('overwrite').parquet(train_data_path)\n", "name": "ipython",
"test.write.mode('overwrite').parquet(test_data_path)\n", "version": 3
"print(\"train and test datasets saved to {} and {}\".format(train_data_path_dbfs, test_data_path_dbfs))" },
], "file_extension": ".py",
"cell_type": "code" "mimetype": "text/x-python",
}, "name": "python",
{ "nbconvert_exporter": "python",
"metadata": {}, "pygments_lexer": "ipython3",
"outputs": [], "version": "3.6.6"
"execution_count": null, },
"source": [], "name": "ingest-data-02",
"cell_type": "code" "notebookId": 3836944406456362
}, },
{ "nbformat": 4,
"metadata": {}, "nbformat_minor": 1
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/ingest-data-02.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

View File

@@ -1,190 +1,183 @@
{ {
"metadata": { "cells": [
"name": "installation-and-configuration-01", {
"kernelspec": { "cell_type": "markdown",
"display_name": "Python 3.6", "metadata": {},
"name": "python36", "source": [
"language": "python" "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
}, "\n",
"authors": [ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
{ "\n",
"name": "pasha" "Licensed under the MIT License."
} ]
], },
"language_info": { {
"mimetype": "text/x-python", "cell_type": "markdown",
"codemirror_mode": { "metadata": {},
"name": "ipython", "source": [
"version": 3 "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",
"pygments_lexer": "ipython3", "**install azureml-sdk**\n",
"name": "python", "* Source: Upload Python Egg or PyPi\n",
"file_extension": ".py", "* PyPi Name: `azureml-sdk[databricks]`\n",
"nbconvert_exporter": "python", "* Select Install Library"
"version": "3.6.6" ]
}, },
"notebookId": 3688394266452835 {
}, "cell_type": "code",
"nbformat": 4, "execution_count": null,
"cells": [ "metadata": {},
{ "outputs": [],
"metadata": {}, "source": [
"source": [ "import azureml.core\n",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "\n",
"\n", "# Check core SDK version number - based on build number of preview/master.\n",
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "print(\"SDK version:\", azureml.core.VERSION)"
"\n", ]
"Licensed under the MIT License." },
], {
"cell_type": "markdown" "cell_type": "markdown",
}, "metadata": {},
{ "source": [
"metadata": {}, "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",
"source": [ "\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/installation-and-configuration-01.png)" "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",
"cell_type": "markdown" "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."
"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", "cell_type": "code",
"**install azureml-sdk**\n", "execution_count": null,
"* Source: Upload Python Egg or PyPi\n", "metadata": {},
"* PyPi Name: `azureml-sdk[databricks]`\n", "outputs": [],
"* Select Install Library" "source": [
], "# subscription_id = \"<your-subscription-id>\"\n",
"cell_type": "markdown" "# 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>\""
"metadata": {}, ]
"outputs": [], },
"execution_count": null, {
"source": [ "cell_type": "code",
"import azureml.core\n", "execution_count": null,
"\n", "metadata": {},
"# Check core SDK version number - based on build number of preview/master.\n", "outputs": [],
"print(\"SDK version:\", azureml.core.VERSION)" "source": [
], "# Set auth to be used by workspace related APIs.\n",
"cell_type": "code" "# 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"
"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", "cell_type": "code",
"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", "execution_count": null,
"\n", "metadata": {},
"For the resource_group, use the name of the resource group that contains your Azure Databricks Workspace.\n", "outputs": [],
"\n", "source": [
"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." "# import the Workspace class and check the azureml SDK version\n",
], "# exist_ok checks if workspace exists or not.\n",
"cell_type": "markdown" "\n",
}, "from azureml.core import Workspace\n",
{ "\n",
"metadata": {}, "ws = Workspace.create(name = workspace_name,\n",
"outputs": [], " subscription_id = subscription_id,\n",
"execution_count": null, " resource_group = resource_group, \n",
"source": [ " location = workspace_region,\n",
"# subscription_id = \"<your-subscription-id>\"\n", " auth = auth,\n",
"# resource_group = \"<your-existing-resource-group>\"\n", " exist_ok=True)"
"# workspace_name = \"<a-new-or-existing-workspace; it is unrelated to Databricks workspace>\"\n", ]
"# workspace_region = \"<your-resource group-region>\"" },
], {
"cell_type": "code" "cell_type": "code",
}, "execution_count": null,
{ "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "source": [
"execution_count": null, "#get workspace details\n",
"source": [ "ws.get_details()"
"# 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,
"cell_type": "code" "metadata": {},
}, "outputs": [],
{ "source": [
"metadata": {}, "ws = Workspace(workspace_name = workspace_name,\n",
"outputs": [], " subscription_id = subscription_id,\n",
"execution_count": null, " resource_group = resource_group,\n",
"source": [ " auth = auth)\n",
"# import the Workspace class and check the azureml SDK version\n", "\n",
"# exist_ok checks if workspace exists or not.\n", "# persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n",
"\n", "ws.write_config()\n",
"from azureml.core import Workspace\n", "#if you need to give a different path/filename please use this\n",
"\n", "#write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)"
"ws = Workspace.create(name = workspace_name,\n", ]
" subscription_id = subscription_id,\n", },
" resource_group = resource_group, \n", {
" location = workspace_region,\n", "cell_type": "code",
" auth = auth,\n", "execution_count": null,
" exist_ok=True)" "metadata": {},
], "outputs": [],
"cell_type": "code" "source": [
}, "help(Workspace)"
{ ]
"metadata": {}, },
"outputs": [], {
"execution_count": null, "cell_type": "code",
"source": [ "execution_count": null,
"#get workspace details\n", "metadata": {},
"ws.get_details()" "outputs": [],
], "source": [
"cell_type": "code" "# import the Workspace class and check the azureml SDK version\n",
}, "from azureml.core import Workspace\n",
{ "\n",
"metadata": {}, "ws = Workspace.from_config(auth = auth)\n",
"outputs": [], "#ws = Workspace.from_config(<full path>)\n",
"execution_count": null, "print('Workspace name: ' + ws.name, \n",
"source": [ " 'Azure region: ' + ws.location, \n",
"ws = Workspace(workspace_name = workspace_name,\n", " 'Subscription id: ' + ws.subscription_id, \n",
" subscription_id = subscription_id,\n", " 'Resource group: ' + ws.resource_group, sep = '\\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", "cell_type": "markdown",
"ws.write_config()\n", "metadata": {},
"#if you need to give a different path/filename please use this\n", "source": [
"#write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)" "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/installation-and-configuration-01.png)"
], ]
"cell_type": "code" }
}, ],
{ "metadata": {
"metadata": {}, "authors": [
"outputs": [], {
"execution_count": null, "name": "pasha"
"source": [ }
"help(Workspace)" ],
], "kernelspec": {
"cell_type": "code" "display_name": "Python 3.6",
}, "language": "python",
{ "name": "python36"
"metadata": {}, },
"outputs": [], "language_info": {
"execution_count": null, "codemirror_mode": {
"source": [ "name": "ipython",
"# import the Workspace class and check the azureml SDK version\n", "version": 3
"from azureml.core import Workspace\n", },
"\n", "file_extension": ".py",
"ws = Workspace.from_config(auth = auth)\n", "mimetype": "text/x-python",
"#ws = Workspace.from_config(<full path>)\n", "name": "python",
"print('Workspace name: ' + ws.name, \n", "nbconvert_exporter": "python",
" 'Azure region: ' + ws.location, \n", "pygments_lexer": "ipython3",
" 'Subscription id: ' + ws.subscription_id, \n", "version": "3.6.6"
" 'Resource group: ' + ws.resource_group, sep = '\\n')" },
], "name": "installation-and-configuration-01",
"cell_type": "code" "notebookId": 3688394266452835
}, },
{ "nbformat": 4,
"metadata": {}, "nbformat_minor": 1
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/installation-and-configuration-01.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

View File

@@ -0,0 +1,56 @@
# Adding an init script to an Azure Databricks cluster
The [azureml-cluster-init.sh](./azureml-cluster-init.sh) script configures the environment to
1. Use the configured AzureML Workspace with Workspace.from_config()
2. Set the default MLflow Tracking Server to be the AzureML managed one
Modify azureml-cluster-init.sh by providing the values for region, subscriptionId, resourceGroupName, and workspaceName of your target Azure ML workspace in the highlighted section at the top of the script.
To create the Azure Databricks cluster-scoped init script
1. Create the base directory you want to store the init script in if it does not exist.
```
dbutils.fs.mkdirs("dbfs:/databricks/<directory>/")
```
2. Create the script by copying the contents of azureml-cluster-init.sh
```
dbutils.fs.put("/databricks/<directory>/azureml-cluster-init.sh","""
<configured_contents_of_azureml-cluster-init.sh>
""", True)
3. Check that the script exists.
```
display(dbutils.fs.ls("dbfs:/databricks/<directory>/azureml-cluster-init.sh"))
```
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/<directory>/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/<directory>/azureml-cluster-init.sh"
}
} ]
}' https://<databricks-instance>/api/2.0/clusters/edit
```

View File

@@ -0,0 +1,24 @@
#!/bin/bash
# This script configures the environment to
# 1. Use the configured AzureML Workspace with azureml.core.Workspace.from_config()
# 2. Set the default MLflow Tracking Server to be the AzureML managed one
############## START CONFIGURATION #################
# Provide the required *AzureML* workspace information
region="" # example: westus2
subscriptionId="" # example: bcb65f42-f234-4bff-91cf-9ef816cd9936
resourceGroupName="" # example: dev-rg
workspaceName="" # example: myazuremlws
# Optional config directory
configLocation="/databricks/config.json"
############### END CONFIGURATION #################
# Drop the workspace configuration on the cluster
sudo touch $configLocation
sudo echo {\\"subscription_id\\": \\"${subscriptionId}\\", \\"resource_group\\": \\"${resourceGroupName}\\", \\"workspace_name\\": \\"${workspaceName}\\"} > $configLocation
# Set the MLflow Tracking URI
trackingUri="adbazureml://${region}.experiments.azureml.net/history/v1.0/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/${workspaceName}"
sudo echo export MLFLOW_TRACKING_URI=${trackingUri} >> /databricks/spark/conf/spark-env.sh

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

View File

@@ -0,0 +1,217 @@
NOTICES AND INFORMATION
Do Not Translate or Localize
This Azure Machine Learning service example notebooks repository includes material from the projects listed below.
1. SSD-Tensorflow (https://github.com/balancap/ssd-tensorflow)
%% SSD-Tensorflow NOTICES AND INFORMATION BEGIN HERE
=========================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================
END OF SSD-Tensorflow NOTICES AND INFORMATION

View File

@@ -0,0 +1,102 @@
# Notebooks for Microsoft Azure Machine Learning Hardware Accelerated Models SDK
Easily create and train a model using various deep neural networks (DNNs) as a featurizer for deployment to Azure or a Data Box Edge device for ultra-low latency inferencing using FPGA's. These models are currently available:
* ResNet 50
* ResNet 152
* DenseNet-121
* VGG-16
* SSD-VGG
To learn more about the azureml-accel-model classes, see the section [Model Classes](#model-classes) below or the [Azure ML Accel Models SDK documentation](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel?view=azure-ml-py).
### Step 1: Create an Azure ML workspace
Follow [these instructions](https://docs.microsoft.com/en-us/azure/machine-learning/service/setup-create-workspace) to install the Azure ML SDK on your local machine, create an Azure ML workspace, and set up your notebook environment, which is required for the next step.
### Step 2: Check your FPGA quota
Use the Azure CLI to check whether you have quota.
```shell
az vm list-usage --location "eastus" -o table
```
The other locations are ``southeastasia``, ``westeurope``, and ``westus2``.
Under the "Name" column, look for "Standard PBS Family vCPUs" and ensure you have at least 6 vCPUs under "CurrentValue."
If you do not have quota, then submit a request form [here](https://aka.ms/accelerateAI).
### Step 3: Install the Azure ML Accelerated Models SDK
Once you have set up your environment, install the Azure ML Accel Models SDK. This package requires tensorflow >= 1.6,<2.0 to be installed.
If you already have tensorflow >= 1.6,<2.0 installed in your development environment, you can install the SDK package using:
```
pip install azureml-accel-models
```
If you do not have tensorflow >= 1.6,<2.0 and are using a CPU-only development environment, our SDK with tensorflow can be installed using:
```
pip install azureml-accel-models[cpu]
```
If your machine supports GPU (for example, on an [Azure DSVM](https://docs.microsoft.com/en-us/azure/machine-learning/data-science-virtual-machine/overview)), then you can leverage the tensorflow-gpu functionality using:
```
pip install azureml-accel-models[gpu]
```
### Step 4: Follow our notebooks
The notebooks in this repo walk through the following scenarios:
* [Quickstart](accelerated-models-quickstart.ipynb), deploy and inference a ResNet50 model trained on ImageNet
* [Object Detection](accelerated-models-object-detection.ipynb), deploy and inference an SSD-VGG model that can do object detection
* [Training models](accelerated-models-training.ipynb), train one of our accelerated models on the Kaggle Cats and Dogs dataset to see how to improve accuracy on custom datasets
<a name="model-classes"></a>
## Model Classes
As stated above, we support 5 Accelerated Models. Here's more information on their input and output tensors.
**Available models and output tensors**
The available models and the corresponding default classifier output tensors are below. This is the value that you would use during inferencing if you used the default classifier.
* Resnet50, QuantizedResnet50
``
output_tensors = "classifier_1/resnet_v1_50/predictions/Softmax:0"
``
* Resnet152, QuantizedResnet152
``
output_tensors = "classifier/resnet_v1_152/predictions/Softmax:0"
``
* Densenet121, QuantizedDensenet121
``
output_tensors = "classifier/densenet121/predictions/Softmax:0"
``
* Vgg16, QuantizedVgg16
``
output_tensors = "classifier/vgg_16/fc8/squeezed:0"
``
* SsdVgg, QuantizedSsdVgg
``
output_tensors = ['ssd_300_vgg/block4_box/Reshape_1:0', 'ssd_300_vgg/block7_box/Reshape_1:0', 'ssd_300_vgg/block8_box/Reshape_1:0', 'ssd_300_vgg/block9_box/Reshape_1:0', 'ssd_300_vgg/block10_box/Reshape_1:0', 'ssd_300_vgg/block11_box/Reshape_1:0', 'ssd_300_vgg/block4_box/Reshape:0', 'ssd_300_vgg/block7_box/Reshape:0', 'ssd_300_vgg/block8_box/Reshape:0', 'ssd_300_vgg/block9_box/Reshape:0', 'ssd_300_vgg/block10_box/Reshape:0', 'ssd_300_vgg/block11_box/Reshape:0']
``
For more information, please reference the azureml.accel.models package in the [Azure ML Python SDK documentation](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel.models?view=azure-ml-py).
**Input tensors**
The input_tensors value defaults to "Placeholder:0" and is created in the [Image Preprocessing](#construct-model) step in the line:
``
in_images = tf.placeholder(tf.string)
``
You can change the input_tensors name by doing this:
``
in_images = tf.placeholder(tf.string, name="images")
``
## Resources
* [Read more about FPGAs](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-accelerate-with-fpgas)

View File

@@ -0,0 +1,497 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/deployment/accelerated-models/accelerated-models-object-detection.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Azure ML Hardware Accelerated Object Detection"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This tutorial will show you how to deploy an object detection service based on the SSD-VGG model in just a few minutes using the Azure Machine Learning Accelerated AI service.\n",
"\n",
"We will use the SSD-VGG model accelerated on an FPGA. Our Accelerated Models Service handles translating deep neural networks (DNN) into an FPGA program.\n",
"\n",
"The steps in this notebook are: \n",
"1. [Setup Environment](#set-up-environment)\n",
"* [Construct Model](#construct-model)\n",
" * Image Preprocessing\n",
" * Featurizer\n",
" * Save Model\n",
" * Save input and output tensor names\n",
"* [Create Image](#create-image)\n",
"* [Deploy Image](#deploy-image)\n",
"* [Test the Service](#test-service)\n",
" * Create Client\n",
" * Serve the model\n",
"* [Cleanup](#cleanup)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"set-up-environment\"></a>\n",
"## 1. Set up Environment\n",
"### 1.a. Imports"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import tensorflow as tf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.b. Retrieve Workspace\n",
"If you haven't created a Workspace, please follow [this notebook](\"../../../configuration.ipynb\") to do so. If you have, run the codeblock below to retrieve it. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"construct-model\"></a>\n",
"## 2. Construct model\n",
"### 2.a. Image preprocessing\n",
"We'd like our service to accept JPEG images as input. However the input to SSD-VGG is a float tensor of shape \\[1, 300, 300, 3\\]. The first dimension is batch, then height, width, and channels (i.e. NHWC). To bridge this gap, we need code that decodes JPEG images and resizes them appropriately for input to SSD-VGG. The Accelerated AI service can execute TensorFlow graphs as part of the service and we'll use that ability to do the image preprocessing. This code defines a TensorFlow graph that preprocesses an array of JPEG images (as TensorFlow strings) and produces a tensor that is ready to be featurized by SSD-VGG.\n",
"\n",
"**Note:** Expect to see TF deprecation warnings until we port our SDK over to use Tensorflow 2.0."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Input images as a two-dimensional tensor containing an arbitrary number of images represented a strings\n",
"import azureml.accel.models.utils as utils\n",
"tf.reset_default_graph()\n",
"\n",
"in_images = tf.placeholder(tf.string)\n",
"image_tensors = utils.preprocess_array(in_images, output_width=300, output_height=300, preserve_aspect_ratio=False)\n",
"print(image_tensors.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.b. Featurizer\n",
"The SSD-VGG model is different from our other models in that it generates 12 tensor outputs. These corresponds to x,y displacements of the anchor boxes and the detection confidence (for 21 classes). Because these outputs are not convenient to work with, we will later use a pre-defined post-processing utility to transform the outputs into a simplified list of bounding boxes with their respective class and confidence.\n",
"\n",
"For more information about the output tensors, take this example: the output tensor 'ssd_300_vgg/block4_box/Reshape_1:0' has a shape of [None, 37, 37, 4, 21]. This gives the pre-softmax confidence for 4 anchor boxes situated at each site of a 37 x 37 grid imposed on the image, one confidence score for each of the 21 classes. The first dimension is the batch dimension. Likewise, 'ssd_300_vgg/block4_box/Reshape:0' has shape [None, 37, 37, 4, 4] and encodes the (cx, cy) center shift and rescaling (sw, sh) relative to each anchor box. Refer to the [SSD-VGG paper](https://arxiv.org/abs/1512.02325) to understand how these are computed. The other 10 tensors are defined similarly."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.accel.models import SsdVgg\n",
"\n",
"saved_model_dir = os.path.join(os.path.expanduser('~'), 'models')\n",
"model_graph = SsdVgg(saved_model_dir, is_frozen = True)\n",
"\n",
"print('SSD-VGG Input Tensors:')\n",
"for idx, input_name in enumerate(model_graph.input_tensor_list):\n",
" print('{}, {}'.format(input_name, model_graph.get_input_dims(idx)))\n",
" \n",
"print('SSD-VGG Output Tensors:')\n",
"for idx, output_name in enumerate(model_graph.output_tensor_list):\n",
" print('{}, {}'.format(output_name, model_graph.get_output_dims(idx)))\n",
"\n",
"ssd_outputs = model_graph.import_graph_def(image_tensors, is_training=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.c. Save Model\n",
"Now that we loaded both parts of the tensorflow graph (preprocessor and SSD-VGG featurizer), we can save the graph and associated variables to a directory which we can register as an Azure ML Model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_name = \"ssdvgg\"\n",
"model_save_path = os.path.join(saved_model_dir, model_name, \"saved_model\")\n",
"print(\"Saving model in {}\".format(model_save_path))\n",
"\n",
"output_map = {}\n",
"for i, output in enumerate(ssd_outputs):\n",
" output_map['out_{}'.format(i)] = output\n",
"\n",
"with tf.Session() as sess:\n",
" model_graph.restore_weights(sess)\n",
" tf.saved_model.simple_save(sess, \n",
" model_save_path, \n",
" inputs={'images': in_images}, \n",
" outputs=output_map)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.d. Important! Save names of input and output tensors\n",
"\n",
"These input and output tensors that were created during the preprocessing and classifier steps are also going to be used when **converting the model** to an Accelerated Model that can run on FPGA's and for **making an inferencing request**. It is very important to save this information!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"register model from file"
]
},
"outputs": [],
"source": [
"input_tensors = in_images.name\n",
"# We will use the list of output tensors during inferencing\n",
"output_tensors = [output.name for output in ssd_outputs]\n",
"# However, for multiple output tensors, our AccelOnnxConverter will \n",
"# accept comma-delimited strings (lists will cause error)\n",
"output_tensors_str = \",\".join(output_tensors)\n",
"\n",
"print(input_tensors)\n",
"print(output_tensors)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"create-image\"></a>\n",
"## 3. Create AccelContainerImage\n",
"Below we will execute all the same steps as in the [Quickstart](./accelerated-models-quickstart.ipynb#create-image) to package the model we have saved locally into an accelerated Docker image saved in our workspace. To complete all the steps, it may take a few minutes. For more details on each step, check out the [Quickstart section on model registration](./accelerated-models-quickstart.ipynb#register-model)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"from azureml.core.model import Model\n",
"from azureml.core.image import Image\n",
"from azureml.accel import AccelOnnxConverter\n",
"from azureml.accel import AccelContainerImage\n",
"\n",
"# Retrieve workspace\n",
"ws = Workspace.from_config()\n",
"print(\"Successfully retrieved workspace:\", ws.name, ws.resource_group, ws.location, ws.subscription_id, '\\n')\n",
"\n",
"# Register model\n",
"registered_model = Model.register(workspace = ws,\n",
" model_path = model_save_path,\n",
" model_name = model_name)\n",
"print(\"Successfully registered: \", registered_model.name, registered_model.description, registered_model.version, '\\n', sep = '\\t')\n",
"\n",
"# Convert model\n",
"convert_request = AccelOnnxConverter.convert_tf_model(ws, registered_model, input_tensors, output_tensors_str)\n",
"if convert_request.wait_for_completion(show_output = False):\n",
" # If the above call succeeded, get the converted model\n",
" converted_model = convert_request.result\n",
" print(\"\\nSuccessfully converted: \", converted_model.name, converted_model.url, converted_model.version, \n",
" converted_model.id, converted_model.created_time, '\\n')\n",
"else:\n",
" print(\"Model conversion failed. Showing output.\")\n",
" convert_request.wait_for_completion(show_output = True)\n",
"\n",
"# Package into AccelContainerImage\n",
"image_config = AccelContainerImage.image_configuration()\n",
"# Image name must be lowercase\n",
"image_name = \"{}-image\".format(model_name)\n",
"image = Image.create(name = image_name,\n",
" models = [converted_model],\n",
" image_config = image_config, \n",
" workspace = ws)\n",
"image.wait_for_creation()\n",
"print(\"Created AccelContainerImage: {} {} {}\\n\".format(image.name, image.creation_state, image.image_location))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"deploy-image\"></a>\n",
"## 4. Deploy image\n",
"Once you have an Azure ML Accelerated Image in your Workspace, you can deploy it to two destinations, to a Databox Edge machine or to an AKS cluster. \n",
"\n",
"### 4.a. Deploy to Databox Edge Machine using IoT Hub\n",
"See the sample [here](https://github.com/Azure-Samples/aml-real-time-ai/) for using the Azure IoT CLI extension for deploying your Docker image to your Databox Edge Machine.\n",
"\n",
"### 4.b. Deploy to AKS Cluster\n",
"Same as in the [Quickstart section on image deployment](./accelerated-models-quickstart.ipynb#deploy-image), we are going to create an AKS cluster with FPGA-enabled machines, then deploy our service to it.\n",
"#### Create AKS ComputeTarget"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import AksCompute, ComputeTarget\n",
"\n",
"# Uses the specific FPGA enabled VM (sku: Standard_PB6s)\n",
"# Standard_PB6s are available in: eastus, westus2, westeurope, southeastasia\n",
"prov_config = AksCompute.provisioning_configuration(vm_size = \"Standard_PB6s\",\n",
" agent_count = 1, \n",
" location = \"eastus\")\n",
"\n",
"aks_name = 'aks-pb6-obj'\n",
"# Create the cluster\n",
"aks_target = ComputeTarget.create(workspace = ws, \n",
" name = aks_name, \n",
" provisioning_configuration = prov_config)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Provisioning an AKS cluster might take awhile (15 or so minutes), and we want to wait until it's successfully provisioned before we can deploy a service to it. If you interrupt this cell, provisioning of the cluster will continue. You can re-run it or check the status in your Workspace under Compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"aks_target.wait_for_completion(show_output = True)\n",
"print(aks_target.provisioning_state)\n",
"print(aks_target.provisioning_errors)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Deploy AccelContainerImage to AKS ComputeTarget"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"from azureml.core.webservice import Webservice, AksWebservice\n",
"\n",
"# Set the web service configuration (for creating a test service, we don't want autoscale enabled)\n",
"# Authentication is enabled by default, but for testing we specify False\n",
"aks_config = AksWebservice.deploy_configuration(autoscale_enabled=False,\n",
" num_replicas=1,\n",
" auth_enabled = False)\n",
"\n",
"aks_service_name ='my-aks-service-3'\n",
"\n",
"aks_service = Webservice.deploy_from_image(workspace = ws,\n",
" name = aks_service_name,\n",
" image = image,\n",
" deployment_config = aks_config,\n",
" deployment_target = aks_target)\n",
"aks_service.wait_for_deployment(show_output = True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"test-service\"></a>\n",
"## 5. Test the service\n",
"<a id=\"create-client\"></a>\n",
"### 5.a. Create Client\n",
"The image supports gRPC and the TensorFlow Serving \"predict\" API. We will create a PredictionClient from the Webservice object that can call into the docker image to get predictions. If you do not have the Webservice object, you can also create [PredictionClient](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel.predictionclient?view=azure-ml-py) directly.\n",
"\n",
"**Note:** If you chose to use auth_enabled=True when creating your AksWebservice.deploy_configuration(), see documentation [here](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.webservice(class)?view=azure-ml-py#get-keys--) on how to retrieve your keys and use either key as an argument to PredictionClient(...,access_token=key).\n",
"**WARNING:** If you are running on Azure Notebooks free compute, you will not be able to make outgoing calls to your service. Try locating your client on a different machine to consume it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Using the grpc client in AzureML Accelerated Models SDK\n",
"from azureml.accel import client_from_service\n",
"\n",
"# Initialize AzureML Accelerated Models client\n",
"client = client_from_service(aks_service)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can adapt the client [code](https://github.com/Azure/aml-real-time-ai/blob/master/pythonlib/amlrealtimeai/client.py) to meet your needs. There is also an example C# [client](https://github.com/Azure/aml-real-time-ai/blob/master/sample-clients/csharp).\n",
"\n",
"The service provides an API that is compatible with TensorFlow Serving. There are instructions to download a sample client [here](https://www.tensorflow.org/serving/setup)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"serve-model\"></a>\n",
"### 5.b. Serve the model\n",
"The SSD-VGG model returns the confidence and bounding boxes for all possible anchor boxes. As mentioned earlier, we will use a post-processing routine to transform this into a list of bounding boxes (y1, x1, y2, x2) where x, y are fractional coordinates measured from left and top respectively. A respective list of classes and scores is also returned to tag each bounding box. Below we make use of this information to draw the bounding boxes on top the original image. Note that in the post-processing routine we select a confidence threshold of 0.5."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import cv2\n",
"from matplotlib import pyplot as plt\n",
"\n",
"colors_tableau = [(255, 255, 255), (31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),\n",
" (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),\n",
" (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),\n",
" (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),\n",
" (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]\n",
"\n",
"\n",
"def draw_boxes_on_img(img, classes, scores, bboxes, thickness=2):\n",
" shape = img.shape\n",
" for i in range(bboxes.shape[0]):\n",
" bbox = bboxes[i]\n",
" color = colors_tableau[classes[i]]\n",
" # Draw bounding box...\n",
" p1 = (int(bbox[0] * shape[0]), int(bbox[1] * shape[1]))\n",
" p2 = (int(bbox[2] * shape[0]), int(bbox[3] * shape[1]))\n",
" cv2.rectangle(img, p1[::-1], p2[::-1], color, thickness)\n",
" # Draw text...\n",
" s = '%s/%.3f' % (classes[i], scores[i])\n",
" p1 = (p1[0]-5, p1[1])\n",
" cv2.putText(img, s, p1[::-1], cv2.FONT_HERSHEY_DUPLEX, 0.4, color, 1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import azureml.accel._external.ssdvgg_utils as ssdvgg_utils\n",
"\n",
"result = client.score_file(path=\"meeting.jpg\", input_name=input_tensors, outputs=output_tensors)\n",
"classes, scores, bboxes = ssdvgg_utils.postprocess(result, select_threshold=0.5)\n",
"\n",
"img = cv2.imread('meeting.jpg', 1)\n",
"img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
"draw_boxes_on_img(img, classes, scores, bboxes)\n",
"plt.imshow(img)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"cleanup\"></a>\n",
"## 6. Cleanup\n",
"It's important to clean up your resources, so that you won't incur unnecessary costs. In the [next notebook](./accelerated-models-training.ipynb) you will learn how to train a classfier on a new dataset using transfer learning."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"aks_service.delete()\n",
"aks_target.delete()\n",
"image.delete()\n",
"registered_model.delete()\n",
"converted_model.delete()"
]
}
],
"metadata": {
"authors": [
{
"name": "coverste"
},
{
"name": "paledger"
},
{
"name": "sukha"
}
],
"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.5.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,7 @@
name: accelerated-models-object-detection
dependencies:
- pip:
- azureml-sdk
- azureml-accel-models[cpu]
- opencv-python
- matplotlib

View File

@@ -0,0 +1,551 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/deployment/accelerated-models/accelerated-models-quickstart.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Azure ML Hardware Accelerated Models Quickstart"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This tutorial will show you how to deploy an image recognition service based on the ResNet 50 classifier using the Azure Machine Learning Accelerated Models service. Get more information about our service from our [documentation](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-accelerate-with-fpgas), [API reference](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel?view=azure-ml-py), or [forum](https://aka.ms/aml-forum).\n",
"\n",
"We will use an accelerated ResNet50 featurizer running on an FPGA. Our Accelerated Models Service handles translating deep neural networks (DNN) into an FPGA program.\n",
"\n",
"For more information about using other models besides Resnet50, see the [README](./README.md).\n",
"\n",
"The steps covered in this notebook are: \n",
"1. [Set up environment](#set-up-environment)\n",
"* [Construct model](#construct-model)\n",
" * Image Preprocessing\n",
" * Featurizer (Resnet50)\n",
" * Classifier\n",
" * Save Model\n",
"* [Register Model](#register-model)\n",
"* [Convert into Accelerated Model](#convert-model)\n",
"* [Create Image](#create-image)\n",
"* [Deploy](#deploy-image)\n",
"* [Test service](#test-service)\n",
"* [Clean-up](#clean-up)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"set-up-environment\"></a>\n",
"## 1. Set up environment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import tensorflow as tf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Retrieve Workspace\n",
"If you haven't created a Workspace, please follow [this notebook](https://github.com/Azure/MachineLearningNotebooks/blob/master/configuration.ipynb) to do so. If you have, run the codeblock below to retrieve it. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"construct-model\"></a>\n",
"## 2. Construct model\n",
"\n",
"There are three parts to the model we are deploying: pre-processing, featurizer with ResNet50, and classifier with ImageNet dataset. Then we will save this complete Tensorflow model graph locally before registering it to your Azure ML Workspace.\n",
"\n",
"### 2.a. Image preprocessing\n",
"We'd like our service to accept JPEG images as input. However the input to ResNet50 is a tensor. So we need code that decodes JPEG images and does the preprocessing required by ResNet50. The Accelerated AI service can execute TensorFlow graphs as part of the service and we'll use that ability to do the image preprocessing. This code defines a TensorFlow graph that preprocesses an array of JPEG images (as strings) and produces a tensor that is ready to be featurized by ResNet50.\n",
"\n",
"**Note:** Expect to see TF deprecation warnings until we port our SDK over to use Tensorflow 2.0."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Input images as a two-dimensional tensor containing an arbitrary number of images represented a strings\n",
"import azureml.accel.models.utils as utils\n",
"tf.reset_default_graph()\n",
"\n",
"in_images = tf.placeholder(tf.string)\n",
"image_tensors = utils.preprocess_array(in_images)\n",
"print(image_tensors.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.b. Featurizer\n",
"We use ResNet50 as a featurizer. In this step we initialize the model. This downloads a TensorFlow checkpoint of the quantized ResNet50."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.accel.models import QuantizedResnet50\n",
"save_path = os.path.expanduser('~/models')\n",
"model_graph = QuantizedResnet50(save_path, is_frozen = True)\n",
"feature_tensor = model_graph.import_graph_def(image_tensors)\n",
"print(model_graph.version)\n",
"print(feature_tensor.name)\n",
"print(feature_tensor.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.c. Classifier\n",
"The model we downloaded includes a classifier which takes the output of the ResNet50 and identifies an image. This classifier is trained on the ImageNet dataset. We are going to use this classifier for our service. The next [notebook](./accelerated-models-training.ipynb) shows how to train a classifier for a different data set. The input to the classifier is a tensor matching the output of our ResNet50 featurizer."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"classifier_output = model_graph.get_default_classifier(feature_tensor)\n",
"print(classifier_output)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.d. Save Model\n",
"Now that we loaded all three parts of the tensorflow graph (preprocessor, resnet50 featurizer, and the classifier), we can save the graph and associated variables to a directory which we can register as an Azure ML Model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# model_name must be lowercase\n",
"model_name = \"resnet50\"\n",
"model_save_path = os.path.join(save_path, model_name)\n",
"print(\"Saving model in {}\".format(model_save_path))\n",
"\n",
"with tf.Session() as sess:\n",
" model_graph.restore_weights(sess)\n",
" tf.saved_model.simple_save(sess, model_save_path,\n",
" inputs={'images': in_images},\n",
" outputs={'output_alias': classifier_output})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.e. Important! Save names of input and output tensors\n",
"\n",
"These input and output tensors that were created during the preprocessing and classifier steps are also going to be used when **converting the model** to an Accelerated Model that can run on FPGA's and for **making an inferencing request**. It is very important to save this information! You can see our defaults for all the models in the [README](./README.md).\n",
"\n",
"By default for Resnet50, these are the values you should see when running the cell below: \n",
"* input_tensors = \"Placeholder:0\"\n",
"* output_tensors = \"classifier/resnet_v1_50/predictions/Softmax:0\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"register model from file"
]
},
"outputs": [],
"source": [
"input_tensors = in_images.name\n",
"output_tensors = classifier_output.name\n",
"\n",
"print(input_tensors)\n",
"print(output_tensors)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"register-model\"></a>\n",
"## 3. Register Model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can add tags and descriptions to your models. Using tags, you can track useful information such as the name and version of the machine learning library used to train the model. Note that tags must be alphanumeric."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"register model from file"
]
},
"outputs": [],
"source": [
"from azureml.core.model import Model\n",
"\n",
"registered_model = Model.register(workspace = ws,\n",
" model_path = model_save_path,\n",
" model_name = model_name)\n",
"\n",
"print(\"Successfully registered: \", registered_model.name, registered_model.description, registered_model.version, sep = '\\t')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"convert-model\"></a>\n",
"## 4. Convert Model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For conversion you need to provide names of input and output tensors. This information can be found from the model_graph you saved in step 2.e. above.\n",
"\n",
"**Note**: Conversion may take a while and on average for FPGA model it is about 1-3 minutes and it depends on model type."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"register model from file"
]
},
"outputs": [],
"source": [
"from azureml.accel import AccelOnnxConverter\n",
"\n",
"convert_request = AccelOnnxConverter.convert_tf_model(ws, registered_model, input_tensors, output_tensors)\n",
"\n",
"if convert_request.wait_for_completion(show_output = False):\n",
" # If the above call succeeded, get the converted model\n",
" converted_model = convert_request.result\n",
" print(\"\\nSuccessfully converted: \", converted_model.name, converted_model.url, converted_model.version, \n",
" converted_model.id, converted_model.created_time, '\\n')\n",
"else:\n",
" print(\"Model conversion failed. Showing output.\")\n",
" convert_request.wait_for_completion(show_output = True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"create-image\"></a>\n",
"## 5. Package the model into an Image"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can add tags and descriptions to image. Also, for FPGA model an image can only contain **single** model.\n",
"\n",
"**Note**: The following command can take few minutes. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.image import Image\n",
"from azureml.accel import AccelContainerImage\n",
"\n",
"image_config = AccelContainerImage.image_configuration()\n",
"# Image name must be lowercase\n",
"image_name = \"{}-image\".format(model_name)\n",
"\n",
"image = Image.create(name = image_name,\n",
" models = [converted_model],\n",
" image_config = image_config, \n",
" workspace = ws)\n",
"image.wait_for_creation(show_output = False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"deploy-image\"></a>\n",
"## 6. Deploy\n",
"Once you have an Azure ML Accelerated Image in your Workspace, you can deploy it to two destinations, to a Databox Edge machine or to an AKS cluster. \n",
"\n",
"### 6.a. Databox Edge Machine using IoT Hub\n",
"See the sample [here](https://github.com/Azure-Samples/aml-real-time-ai/) for using the Azure IoT CLI extension for deploying your Docker image to your Databox Edge Machine.\n",
"\n",
"### 6.b. Azure Kubernetes Service (AKS) using Azure ML Service\n",
"We are going to create an AKS cluster with FPGA-enabled machines, then deploy our service to it. For more information, see [AKS official docs](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-deploy-and-where#aks).\n",
"\n",
"#### Create AKS ComputeTarget"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import AksCompute, ComputeTarget\n",
"\n",
"# Uses the specific FPGA enabled VM (sku: Standard_PB6s)\n",
"# Standard_PB6s are available in: eastus, westus2, westeurope, southeastasia\n",
"prov_config = AksCompute.provisioning_configuration(vm_size = \"Standard_PB6s\",\n",
" agent_count = 1, \n",
" location = \"eastus\")\n",
"\n",
"aks_name = 'my-aks-pb6'\n",
"# Create the cluster\n",
"aks_target = ComputeTarget.create(workspace = ws, \n",
" name = aks_name, \n",
" provisioning_configuration = prov_config)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Provisioning an AKS cluster might take awhile (15 or so minutes), and we want to wait until it's successfully provisioned before we can deploy a service to it. If you interrupt this cell, provisioning of the cluster will continue. You can also check the status in your Workspace under Compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"aks_target.wait_for_completion(show_output = True)\n",
"print(aks_target.provisioning_state)\n",
"print(aks_target.provisioning_errors)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Deploy AccelContainerImage to AKS ComputeTarget"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"from azureml.core.webservice import Webservice, AksWebservice\n",
"\n",
"# Set the web service configuration (for creating a test service, we don't want autoscale enabled)\n",
"# Authentication is enabled by default, but for testing we specify False\n",
"aks_config = AksWebservice.deploy_configuration(autoscale_enabled=False,\n",
" num_replicas=1,\n",
" auth_enabled = False)\n",
"\n",
"aks_service_name ='my-aks-service-1'\n",
"\n",
"aks_service = Webservice.deploy_from_image(workspace = ws,\n",
" name = aks_service_name,\n",
" image = image,\n",
" deployment_config = aks_config,\n",
" deployment_target = aks_target)\n",
"aks_service.wait_for_deployment(show_output = True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"test-service\"></a>\n",
"## 7. Test the service"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 7.a. Create Client\n",
"The image supports gRPC and the TensorFlow Serving \"predict\" API. We will create a PredictionClient from the Webservice object that can call into the docker image to get predictions. If you do not have the Webservice object, you can also create [PredictionClient](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel.predictionclient?view=azure-ml-py) directly.\n",
"\n",
"**Note:** If you chose to use auth_enabled=True when creating your AksWebservice, see documentation [here](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.webservice(class)?view=azure-ml-py#get-keys--) on how to retrieve your keys and use either key as an argument to PredictionClient(...,access_token=key).\n",
"**WARNING:** If you are running on Azure Notebooks free compute, you will not be able to make outgoing calls to your service. Try locating your client on a different machine to consume it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Using the grpc client in AzureML Accelerated Models SDK\n",
"from azureml.accel import client_from_service\n",
"\n",
"# Initialize AzureML Accelerated Models client\n",
"client = client_from_service(aks_service)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can adapt the client [code](https://github.com/Azure/aml-real-time-ai/blob/master/pythonlib/amlrealtimeai/client.py) to meet your needs. There is also an example C# [client](https://github.com/Azure/aml-real-time-ai/blob/master/sample-clients/csharp).\n",
"\n",
"The service provides an API that is compatible with TensorFlow Serving. There are instructions to download a sample client [here](https://www.tensorflow.org/serving/setup)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 7.b. Serve the model\n",
"To understand the results we need a mapping to the human readable imagenet classes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"classes_entries = requests.get(\"https://raw.githubusercontent.com/Lasagne/Recipes/master/examples/resnet50/imagenet_classes.txt\").text.splitlines()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Score image with input and output tensor names\n",
"results = client.score_file(path=\"./snowleopardgaze.jpg\", \n",
" input_name=input_tensors, \n",
" outputs=output_tensors)\n",
"\n",
"# map results [class_id] => [confidence]\n",
"results = enumerate(results)\n",
"# sort results by confidence\n",
"sorted_results = sorted(results, key=lambda x: x[1], reverse=True)\n",
"# print top 5 results\n",
"for top in sorted_results[:5]:\n",
" print(classes_entries[top[0]], 'confidence:', top[1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"clean-up\"></a>\n",
"## 8. Clean-up\n",
"Run the cell below to delete your webservice, image, and model (must be done in that order). In the [next notebook](./accelerated-models-training.ipynb) you will learn how to train a classfier on a new dataset using transfer learning and finetune the weights."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"aks_service.delete()\n",
"aks_target.delete()\n",
"image.delete()\n",
"registered_model.delete()\n",
"converted_model.delete()"
]
}
],
"metadata": {
"authors": [
{
"name": "coverste"
},
{
"name": "paledger"
},
{
"name": "aibhalla"
}
],
"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.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,5 @@
name: accelerated-models-quickstart
dependencies:
- pip:
- azureml-sdk
- azureml-accel-models[cpu]

View File

@@ -0,0 +1,866 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/deployment/accelerated-models/accelerated-models-training.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Training with the Azure Machine Learning Accelerated Models Service"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook will introduce how to apply common machine learning techniques, like transfer learning, custom weights, and unquantized vs. quantized models, when working with our Azure Machine Learning Accelerated Models Service (Azure ML Accel Models).\n",
"\n",
"We will use Tensorflow for the preprocessing steps, ResNet50 for the featurizer, and the Keras API (built on Tensorflow backend) to build the classifier layers instead of the default ImageNet classifier used in Quickstart. Then we will train the model, evaluate it, and deploy it to run on an FPGA.\n",
"\n",
"#### Transfer Learning and Custom weights\n",
"We will walk you through two ways to build and train a ResNet50 model on the Kaggle Cats and Dogs dataset: transfer learning only and then transfer learning with custom weights.\n",
"\n",
"In using transfer learning, our goal is to re-purpose the ResNet50 model already trained on the [ImageNet image dataset](http://www.image-net.org/) as a basis for our training of the Kaggle Cats and Dogs dataset. The ResNet50 featurizer will be imported as frozen, so only the Keras classifier will be trained.\n",
"\n",
"With the addition of custom weights, we will build the model so that the ResNet50 featurizer weights as not frozen. This will let us retrain starting with custom weights trained with ImageNet on ResNet50 and then use the Kaggle Cats and Dogs dataset to retrain and fine-tune the quantized version of the model.\n",
"\n",
"#### Unquantized vs. Quantized models\n",
"The unquantized version of our models (ie. Resnet50, Resnet152, Densenet121, Vgg16, SsdVgg) uses native float precision (32-bit floats), which will be faster at training. We will use this for our first run through, then fine-tune the weights with the quantized version. The quantized version of our models (i.e. QuantizedResnet50, QuantizedResnet152, QuantizedDensenet121, QuantizedVgg16, QuantizedSsdVgg) will have the same node names as the unquantized version, but use quantized operations and will match the performance of the model when running on an FPGA.\n",
"\n",
"#### Contents\n",
"1. [Setup Environment](#setup)\n",
"* [Prepare Data](#prepare-data)\n",
"* [Construct Model](#construct-model)\n",
" * Preprocessor\n",
" * Classifier\n",
" * Model construction\n",
"* [Train Model](#train-model)\n",
"* [Test Model](#test-model)\n",
"* [Execution](#execution)\n",
" * [Transfer Learning](#transfer-learning)\n",
" * [Transfer Learning with Custom Weights](#custom-weights)\n",
"* [Create Image](#create-image)\n",
"* [Deploy Image](#deploy-image)\n",
"* [Test the service](#test-service)\n",
"* [Clean-up](#cleanup)\n",
"* [Appendix](#appendix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"setup\"></a>\n",
"## 1. Setup Environment\n",
"#### 1.a. Please set up your environment as described in the [Quickstart](./accelerated-models-quickstart.ipynb), meaning:\n",
"* Make sure your Workspace config.json exists and has the correct info\n",
"* Install Tensorflow\n",
"\n",
"#### 1.b. Download dataset into ~/catsanddogs \n",
"The dataset we will be using for training can be downloaded [here](https://www.microsoft.com/en-us/download/details.aspx?id=54765). Download the zip and extract to a directory named 'catsanddogs' under your user directory (\"~/catsanddogs\"). \n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.c. Import packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"import tensorflow as tf\n",
"import numpy as np\n",
"from keras import backend as K\n",
"import sklearn\n",
"import tqdm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.d. Create directories for later use\n",
"After you train your model in float32, you'll write the weights to a place on disk. We also need a location to store the models that get downloaded."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"custom_weights_dir = os.path.expanduser(\"~/custom-weights\")\n",
"saved_model_dir = os.path.expanduser(\"~/models\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"prepare-data\"></a>\n",
"## 2. Prepare Data\n",
"Load the files we are going to use for training and testing. By default this notebook uses only a very small subset of the Cats and Dogs dataset. That makes it run relatively quickly."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import glob\n",
"import imghdr\n",
"datadir = os.path.expanduser(\"~/catsanddogs\")\n",
"\n",
"cat_files = glob.glob(os.path.join(datadir, 'PetImages', 'Cat', '*.jpg'))\n",
"dog_files = glob.glob(os.path.join(datadir, 'PetImages', 'Dog', '*.jpg'))\n",
"\n",
"# Limit the data set to make the notebook execute quickly.\n",
"cat_files = cat_files[:64]\n",
"dog_files = dog_files[:64]\n",
"\n",
"# The data set has a few images that are not jpeg. Remove them.\n",
"cat_files = [f for f in cat_files if imghdr.what(f) == 'jpeg']\n",
"dog_files = [f for f in dog_files if imghdr.what(f) == 'jpeg']\n",
"\n",
"if(not len(cat_files) or not len(dog_files)):\n",
" print(\"Please download the Kaggle Cats and Dogs dataset form https://www.microsoft.com/en-us/download/details.aspx?id=54765 and extract the zip to \" + datadir) \n",
" raise ValueError(\"Data not found\")\n",
"else:\n",
" print(cat_files[0])\n",
" print(dog_files[0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Construct a numpy array as labels\n",
"image_paths = cat_files + dog_files\n",
"total_files = len(cat_files) + len(dog_files)\n",
"labels = np.zeros(total_files)\n",
"labels[len(cat_files):] = 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Split images data as training data and test data\n",
"from sklearn.model_selection import train_test_split\n",
"onehot_labels = np.array([[0,1] if i else [1,0] for i in labels])\n",
"img_train, img_test, label_train, label_test = train_test_split(image_paths, onehot_labels, random_state=42, shuffle=True)\n",
"\n",
"print(len(img_train), len(img_test), label_train.shape, label_test.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"construct-model\"></a>\n",
"## 3. Construct Model\n",
"We will define the functions to handle creating the preprocessor and the classifier first, and then run them together to actually construct the model with the Resnet50 featurizer in a single Tensorflow session in a separate cell.\n",
"\n",
"We use ResNet50 for the featurizer and build our own classifier using Keras layers. We train the featurizer and the classifier as one model. We will provide parameters to determine whether we are using the quantized version and whether we are using custom weights in training or not."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.a. Define image preprocessing step\n",
"Same as in the Quickstart, before passing image dataset to the ResNet50 featurizer, we need to preprocess the input file to get it into the form expected by ResNet50. ResNet50 expects float tensors representing the images in BGR, channel last order. We've provided a default implementation of the preprocessing that you can use.\n",
"\n",
"**Note:** Expect to see TF deprecation warnings until we port our SDK over to use Tensorflow 2.0."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import azureml.accel.models.utils as utils\n",
"\n",
"def preprocess_images(scaling_factor=1.0):\n",
" # Convert images to 3D tensors [width,height,channel] - channels are in BGR order.\n",
" in_images = tf.placeholder(tf.string)\n",
" image_tensors = utils.preprocess_array(in_images, 'RGB', scaling_factor)\n",
" return in_images, image_tensors"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.b. Define classifier\n",
"We use Keras layer APIs to construct the classifier. Because we're using the tensorflow backend, we can train this classifier in one session with our Resnet50 model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def construct_classifier(in_tensor, seed=None):\n",
" from keras.layers import Dropout, Dense, Flatten\n",
" from keras.initializers import glorot_uniform\n",
" K.set_session(tf.get_default_session())\n",
"\n",
" FC_SIZE = 1024\n",
" NUM_CLASSES = 2\n",
"\n",
" x = Dropout(0.2, input_shape=(1, 1, int(in_tensor.shape[3]),), seed=seed)(in_tensor)\n",
" x = Dense(FC_SIZE, activation='relu', input_dim=(1, 1, int(in_tensor.shape[3]),),\n",
" kernel_initializer=glorot_uniform(seed=seed), bias_initializer='zeros')(x)\n",
" x = Flatten()(x)\n",
" preds = Dense(NUM_CLASSES, activation='softmax', input_dim=FC_SIZE, name='classifier_output',\n",
" kernel_initializer=glorot_uniform(seed=seed), bias_initializer='zeros')(x)\n",
" return preds"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.c. Define model construction\n",
"Now that the preprocessor and classifier for the model are defined, we can define how we want to construct the model. \n",
"\n",
"Constructing the model has these steps: \n",
"1. Get preprocessing steps\n",
"* Get featurizer using the Azure ML Accel Models SDK:\n",
" * import the graph definition\n",
" * restore the weights of the model into a Tensorflow session\n",
"* Get classifier\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def construct_model(quantized, starting_weights_directory = None):\n",
" from azureml.accel.models import Resnet50, QuantizedResnet50\n",
" \n",
" # Convert images to 3D tensors [width,height,channel]\n",
" in_images, image_tensors = preprocess_images(1.0)\n",
"\n",
" # Construct featurizer using quantized or unquantized ResNet50 model\n",
" if not quantized:\n",
" featurizer = Resnet50(saved_model_dir)\n",
" else:\n",
" featurizer = QuantizedResnet50(saved_model_dir, custom_weights_directory = starting_weights_directory)\n",
"\n",
" features = featurizer.import_graph_def(input_tensor=image_tensors)\n",
" \n",
" # Construct classifier\n",
" preds = construct_classifier(features)\n",
" \n",
" # Initialize weights\n",
" sess = tf.get_default_session()\n",
" tf.global_variables_initializer().run()\n",
"\n",
" featurizer.restore_weights(sess)\n",
"\n",
" return in_images, image_tensors, features, preds, featurizer"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"train-model\"></a>\n",
"## 4. Train Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def read_files(files):\n",
" \"\"\" Read files to array\"\"\"\n",
" contents = []\n",
" for path in files:\n",
" with open(path, 'rb') as f:\n",
" contents.append(f.read())\n",
" return contents"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def train_model(preds, in_images, img_train, label_train, is_retrain = False, train_epoch = 10, learning_rate=None):\n",
" \"\"\" training model \"\"\"\n",
" from keras.objectives import binary_crossentropy\n",
" from tqdm import tqdm\n",
" \n",
" learning_rate = learning_rate if learning_rate else 0.001 if is_retrain else 0.01\n",
" \n",
" # Specify the loss function\n",
" in_labels = tf.placeholder(tf.float32, shape=(None, 2)) \n",
" cross_entropy = tf.reduce_mean(binary_crossentropy(in_labels, preds))\n",
" optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n",
"\n",
" def chunks(a, b, n):\n",
" \"\"\"Yield successive n-sized chunks from a and b.\"\"\"\n",
" if (len(a) != len(b)):\n",
" print(\"a and b are not equal in chunks(a,b,n)\")\n",
" raise ValueError(\"Parameter error\")\n",
"\n",
" for i in range(0, len(a), n):\n",
" yield a[i:i + n], b[i:i + n]\n",
"\n",
" chunk_size = 16\n",
" chunk_num = len(label_train) / chunk_size\n",
"\n",
" sess = tf.get_default_session()\n",
" for epoch in range(train_epoch):\n",
" avg_loss = 0\n",
" for img_chunk, label_chunk in tqdm(chunks(img_train, label_train, chunk_size)):\n",
" contents = read_files(img_chunk)\n",
" _, loss = sess.run([optimizer, cross_entropy],\n",
" feed_dict={in_images: contents,\n",
" in_labels: label_chunk,\n",
" K.learning_phase(): 1})\n",
" avg_loss += loss / chunk_num\n",
" print(\"Epoch:\", (epoch + 1), \"loss = \", \"{:.3f}\".format(avg_loss))\n",
" \n",
" # Reach desired performance\n",
" if (avg_loss < 0.001):\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"test-model\"></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"test-model\"></a>\n",
"## 5. Test Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def test_model(preds, in_images, img_test, label_test):\n",
" \"\"\"Test the model\"\"\"\n",
" from keras.metrics import categorical_accuracy\n",
"\n",
" in_labels = tf.placeholder(tf.float32, shape=(None, 2))\n",
" accuracy = tf.reduce_mean(categorical_accuracy(in_labels, preds))\n",
" contents = read_files(img_test)\n",
"\n",
" accuracy = accuracy.eval(feed_dict={in_images: contents,\n",
" in_labels: label_test,\n",
" K.learning_phase(): 0})\n",
" return accuracy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"execution\"></a>\n",
"## 6. Execute steps\n",
"You can run through the Transfer Learning section, then skip to Create AccelContainerImage. By default, because the custom weights section takes much longer for training twice, it is not saved as executable cells. You can copy the code or change cell type to 'Code'.\n",
"\n",
"<a id=\"transfer-learning\"></a>\n",
"### 6.a. Training using Transfer Learning"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"# Launch the training\n",
"tf.reset_default_graph()\n",
"sess = tf.Session(graph=tf.get_default_graph())\n",
"\n",
"with sess.as_default():\n",
" in_images, image_tensors, features, preds, featurizer = construct_model(quantized=True)\n",
" train_model(preds, in_images, img_train, label_train, is_retrain=False, train_epoch=10, learning_rate=0.01) \n",
" accuracy = test_model(preds, in_images, img_test, label_test) \n",
" print(\"Accuracy:\", accuracy)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Save Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_name = 'resnet50-catsanddogs-tl'\n",
"model_save_path = os.path.join(saved_model_dir, model_name)\n",
"\n",
"tf.saved_model.simple_save(sess, model_save_path,\n",
" inputs={'images': in_images},\n",
" outputs={'output_alias': preds})\n",
"\n",
"input_tensors = in_images.name\n",
"output_tensors = preds.name\n",
"\n",
"print(input_tensors)\n",
"print(output_tensors)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"custom-weights\"></a>\n",
"### 6.b. Traning using Custom Weights\n",
"\n",
"Because the quantized graph defintion and the float32 graph defintion share the same node names in the graph definitions, we can initally train the weights in float32, and then reload them with the quantized operations (which take longer) to fine-tune the model.\n",
"\n",
"First we train the model with custom weights but without quantization. Training is done with native float precision (32-bit floats). We load the training data set and batch the training with 10 epochs. When the performance reaches desired level or starts decredation, we stop the training iteration and save the weights as tensorflow checkpoint files. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Launch the training\n",
"```\n",
"tf.reset_default_graph()\n",
"sess = tf.Session(graph=tf.get_default_graph())\n",
"\n",
"with sess.as_default():\n",
" in_images, image_tensors, features, preds, featurizer = construct_model(quantized=False)\n",
" train_model(preds, in_images, img_train, label_train, is_retrain=False, train_epoch=10) \n",
" accuracy = test_model(preds, in_images, img_test, label_test) \n",
" print(\"Accuracy:\", accuracy)\n",
" featurizer.save_weights(custom_weights_dir + \"/rn50\", tf.get_default_session())\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Test Model\n",
"After training, we evaluate the trained model's accuracy on test dataset with quantization. So that we know the model's performance if it is deployed on the FPGA."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"tf.reset_default_graph()\n",
"sess = tf.Session(graph=tf.get_default_graph())\n",
"\n",
"with sess.as_default():\n",
" print(\"Testing trained model with quantization\")\n",
" in_images, image_tensors, features, preds, quantized_featurizer = construct_model(quantized=True, starting_weights_directory=custom_weights_dir)\n",
" accuracy = test_model(preds, in_images, img_test, label_test) \n",
" print(\"Accuracy:\", accuracy)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Fine-Tune Model\n",
"Sometimes, the model's accuracy can drop significantly after quantization. In those cases, we need to retrain the model enabled with quantization to get better model accuracy."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"if (accuracy < 0.93):\n",
" with sess.as_default():\n",
" print(\"Fine-tuning model with quantization\")\n",
" train_model(preds, in_images, img_train, label_train, is_retrain=True, train_epoch=10)\n",
" accuracy = test_model(preds, in_images, img_test, label_test) \n",
" print(\"Accuracy:\", accuracy)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Save Model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"model_name = 'resnet50-catsanddogs-cw'\n",
"model_save_path = os.path.join(saved_model_dir, model_name)\n",
"\n",
"tf.saved_model.simple_save(sess, model_save_path,\n",
" inputs={'images': in_images},\n",
" outputs={'output_alias': preds})\n",
"\n",
"input_tensors = in_images.name\n",
"output_tensors = preds.name\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"create-image\"></a>\n",
"## 7. Create AccelContainerImage\n",
"\n",
"Below we will execute all the same steps as in the [Quickstart](./accelerated-models-quickstart.ipynb#create-image) to package the model we have saved locally into an accelerated Docker image saved in our workspace. To complete all the steps, it may take a few minutes. For more details on each step, check out the [Quickstart section on model registration](./accelerated-models-quickstart.ipynb#register-model)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"from azureml.core.model import Model\n",
"from azureml.core.image import Image\n",
"from azureml.accel import AccelOnnxConverter\n",
"from azureml.accel import AccelContainerImage\n",
"\n",
"# Retrieve workspace\n",
"ws = Workspace.from_config()\n",
"print(\"Successfully retrieved workspace:\", ws.name, ws.resource_group, ws.location, ws.subscription_id, '\\n')\n",
"\n",
"# Register model\n",
"registered_model = Model.register(workspace = ws,\n",
" model_path = model_save_path,\n",
" model_name = model_name)\n",
"print(\"Successfully registered: \", registered_model.name, registered_model.description, registered_model.version, '\\n', sep = '\\t')\n",
"\n",
"# Convert model\n",
"convert_request = AccelOnnxConverter.convert_tf_model(ws, registered_model, input_tensors, output_tensors)\n",
"if convert_request.wait_for_completion(show_output = False):\n",
" # If the above call succeeded, get the converted model\n",
" converted_model = convert_request.result\n",
" print(\"\\nSuccessfully converted: \", converted_model.name, converted_model.url, converted_model.version, \n",
" converted_model.id, converted_model.created_time, '\\n')\n",
"else:\n",
" print(\"Model conversion failed. Showing output.\")\n",
" convert_request.wait_for_completion(show_output = True)\n",
"\n",
"# Package into AccelContainerImage\n",
"image_config = AccelContainerImage.image_configuration()\n",
"# Image name must be lowercase\n",
"image_name = \"{}-image\".format(model_name)\n",
"image = Image.create(name = image_name,\n",
" models = [converted_model],\n",
" image_config = image_config, \n",
" workspace = ws)\n",
"image.wait_for_creation()\n",
"print(\"Created AccelContainerImage: {} {} {}\\n\".format(image.name, image.creation_state, image.image_location))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"deploy-image\"></a>\n",
"## 8. Deploy image\n",
"Once you have an Azure ML Accelerated Image in your Workspace, you can deploy it to two destinations, to a Databox Edge machine or to an AKS cluster. \n",
"\n",
"### 8.a. Deploy to Databox Edge Machine using IoT Hub\n",
"See the sample [here](https://github.com/Azure-Samples/aml-real-time-ai/) for using the Azure IoT CLI extension for deploying your Docker image to your Databox Edge Machine.\n",
"\n",
"### 8.b. Deploy to AKS Cluster"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create AKS ComputeTarget"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import AksCompute, ComputeTarget\n",
"\n",
"# Uses the specific FPGA enabled VM (sku: Standard_PB6s)\n",
"# Standard_PB6s are available in: eastus, westus2, westeurope, southeastasia\n",
"prov_config = AksCompute.provisioning_configuration(vm_size = \"Standard_PB6s\",\n",
" agent_count = 1,\n",
" location = \"eastus\")\n",
"\n",
"aks_name = 'aks-pb6-tl'\n",
"# Create the cluster\n",
"aks_target = ComputeTarget.create(workspace = ws, \n",
" name = aks_name, \n",
" provisioning_configuration = prov_config)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Provisioning an AKS cluster might take awhile (15 or so minutes), and we want to wait until it's successfully provisioned before we can deploy a service to it. If you interrupt this cell, provisioning of the cluster will continue. You can re-run it or check the status in your Workspace under Compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"aks_target.wait_for_completion(show_output = True)\n",
"print(aks_target.provisioning_state)\n",
"print(aks_target.provisioning_errors)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Deploy AccelContainerImage to AKS ComputeTarget"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"from azureml.core.webservice import Webservice, AksWebservice\n",
"\n",
"# Set the web service configuration (for creating a test service, we don't want autoscale enabled)\n",
"# Authentication is enabled by default, but for testing we specify False\n",
"aks_config = AksWebservice.deploy_configuration(autoscale_enabled=False,\n",
" num_replicas=1,\n",
" auth_enabled = False)\n",
"\n",
"aks_service_name ='my-aks-service-2'\n",
"\n",
"aks_service = Webservice.deploy_from_image(workspace = ws,\n",
" name = aks_service_name,\n",
" image = image,\n",
" deployment_config = aks_config,\n",
" deployment_target = aks_target)\n",
"aks_service.wait_for_deployment(show_output = True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"test-service\"></a>\n",
"## 9. Test the service\n",
"\n",
"<a id=\"create-client\"></a>\n",
"### 9.a. Create Client\n",
"The image supports gRPC and the TensorFlow Serving \"predict\" API. We will create a PredictionClient from the Webservice object that can call into the docker image to get predictions. If you do not have the Webservice object, you can also create [PredictionClient](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel.predictionclient?view=azure-ml-py) directly.\n",
"\n",
"**Note:** If you chose to use auth_enabled=True when creating your AksWebservice.deploy_configuration(), see documentation [here](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.webservice(class)?view=azure-ml-py#get-keys--) on how to retrieve your keys and use either key as an argument to PredictionClient(...,access_token=key).\n",
"**WARNING:** If you are running on Azure Notebooks free compute, you will not be able to make outgoing calls to your service. Try locating your client on a different machine to consume it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Using the grpc client in AzureML Accelerated Models SDK\n",
"from azureml.accel import client_from_service\n",
"\n",
"# Initialize AzureML Accelerated Models client\n",
"client = client_from_service(aks_service)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"serve-model\"></a>\n",
"### 9.b. Serve the model\n",
"Let's see how our service does on a few images. It may get a few wrong."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Specify an image to classify\n",
"print('CATS')\n",
"for image_file in cat_files[:8]:\n",
" results = client.score_file(path=image_file, \n",
" input_name=input_tensors, \n",
" outputs=output_tensors)\n",
" result = 'CORRECT ' if results[0] > results[1] else 'WRONG '\n",
" print(result + str(results))\n",
"print('DOGS')\n",
"for image_file in dog_files[:8]:\n",
" results = client.score_file(path=image_file, \n",
" input_name=input_tensors, \n",
" outputs=output_tensors)\n",
" result = 'CORRECT ' if results[1] > results[0] else 'WRONG '\n",
" print(result + str(results))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"cleanup\"></a>\n",
"## 10. Cleanup\n",
"It's important to clean up your resources, so that you won't incur unnecessary costs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"aks_service.delete()\n",
"aks_target.delete()\n",
"image.delete()\n",
"registered_model.delete()\n",
"converted_model.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"appendix\"></a>\n",
"## 11. Appendix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"License for plot_confusion_matrix:\n",
"\n",
"New BSD License\n",
"\n",
"Copyright (c) 2007-2018 The scikit-learn developers.\n",
"All rights reserved.\n",
"\n",
"\n",
"Redistribution and use in source and binary forms, with or without\n",
"modification, are permitted provided that the following conditions are met:\n",
"\n",
" a. Redistributions of source code must retain the above copyright notice,\n",
" this list of conditions and the following disclaimer.\n",
" b. Redistributions in binary form must reproduce the above copyright\n",
" notice, this list of conditions and the following disclaimer in the\n",
" documentation and/or other materials provided with the distribution.\n",
" c. Neither the name of the Scikit-learn Developers nor the names of\n",
" its contributors may be used to endorse or promote products\n",
" derived from this software without specific prior written\n",
" permission. \n",
"\n",
"\n",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n",
"ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR\n",
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n",
"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n",
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n",
"CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n",
"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n",
"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n",
"DAMAGE.\n"
]
}
],
"metadata": {
"authors": [
{
"name": "coverste"
},
{
"name": "paledger"
}
],
"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.5.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,8 @@
name: accelerated-models-training
dependencies:
- pip:
- azureml-sdk
- azureml-accel-models[cpu]
- keras
- tqdm
- sklearn

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Some files were not shown because too many files have changed in this diff Show More