Compare commits

...

13 Commits

Author SHA1 Message Date
amlrelsa-ms
5775f8a78f update samples from Release-70 as a part of SDK release 2020-10-13 05:19:49 +00:00
Cody
aae823ecd8 Merge pull request #1181 from samuel100/quickstart-notebook
quickstart nb added
2020-10-09 10:54:32 -07:00
Sam Kemp
f1126e07f9 quickstart nb added 2020-10-09 10:35:19 +01:00
Harneet Virk
0e4b27a233 Merge pull request #1171 from savitamittal1/patch-2
Update automl-databricks-local-01.ipynb
2020-10-02 09:41:14 -07:00
Harneet Virk
0a3d5f68a1 Merge pull request #1172 from savitamittal1/patch-3
Update automl-databricks-local-with-deployment.ipynb
2020-10-02 09:41:02 -07:00
savitamittal1
a6fe2affcb Update automl-databricks-local-with-deployment.ipynb
fixed link to readme
2020-10-01 19:38:11 -07:00
savitamittal1
ce469ddf6a Update automl-databricks-local-01.ipynb
fixed link for readme
2020-10-01 19:36:06 -07:00
mx-iao
9fe459be79 Merge pull request #1166 from Azure/minxia/patch
patch for resume training notebook
2020-09-29 17:30:24 -07:00
mx-iao
89c35c8ed6 Update train-tensorflow-resume-training.ipynb 2020-09-29 17:28:17 -07:00
mx-iao
33168c7f5d Update train-tensorflow-resume-training.ipynb 2020-09-29 17:27:23 -07:00
Cody
1d0766bd46 Merge pull request #1165 from samuel100/quickstart-add
quickstart added
2020-09-29 13:13:36 -07:00
Sam Kemp
9903e56882 quickstart added 2020-09-29 21:09:55 +01:00
Harneet Virk
a039166b90 Merge pull request #1162 from Azure/release_update/Release-69
update samples from Release-69 as a part of  SDK 1.15.0 release
2020-09-28 23:54:05 -07:00
70 changed files with 2404 additions and 138 deletions

View File

@@ -103,7 +103,7 @@
"source": [
"import azureml.core\n",
"\n",
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -82,8 +82,7 @@
"from sklearn import svm\n",
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
"from sklearn.linear_model import LogisticRegression\n",
"import pandas as pd\n",
"import shap"
"import pandas as pd"
]
},
{
@@ -99,8 +98,12 @@
"metadata": {},
"outputs": [],
"source": [
"X_raw, Y = shap.datasets.adult()\n",
"X_raw[\"Race\"].value_counts().to_dict()"
"from sklearn.datasets import fetch_openml\n",
"data = fetch_openml(data_id=1590, as_frame=True)\n",
"X_raw = data.data\n",
"Y = (data.target == '>50K') * 1\n",
"\n",
"X_raw[\"race\"].value_counts().to_dict()"
]
},
{
@@ -116,9 +119,13 @@
"metadata": {},
"outputs": [],
"source": [
"A = X_raw[['Sex','Race']]\n",
"X = X_raw.drop(labels=['Sex', 'Race'],axis = 1)\n",
"X = pd.get_dummies(X)\n",
"A = X_raw[['sex','race']]\n",
"X = X_raw.drop(labels=['sex', 'race'],axis = 1)\n",
"X_dummies = pd.get_dummies(X)\n",
"\n",
"sc = StandardScaler()\n",
"X_scaled = sc.fit_transform(X_dummies)\n",
"X_scaled = pd.DataFrame(X_scaled, columns=X_dummies.columns)\n",
"\n",
"\n",
"le = LabelEncoder()\n",
@@ -139,7 +146,7 @@
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"X_train, X_test, Y_train, Y_test, A_train, A_test = train_test_split(X_raw, \n",
"X_train, X_test, Y_train, Y_test, A_train, A_test = train_test_split(X_scaled, \n",
" Y, \n",
" A,\n",
" test_size = 0.2,\n",
@@ -150,18 +157,7 @@
"X_train = X_train.reset_index(drop=True)\n",
"A_train = A_train.reset_index(drop=True)\n",
"X_test = X_test.reset_index(drop=True)\n",
"A_test = A_test.reset_index(drop=True)\n",
"\n",
"# Improve labels\n",
"A_test.Sex.loc[(A_test['Sex'] == 0)] = 'female'\n",
"A_test.Sex.loc[(A_test['Sex'] == 1)] = 'male'\n",
"\n",
"\n",
"A_test.Race.loc[(A_test['Race'] == 0)] = 'Amer-Indian-Eskimo'\n",
"A_test.Race.loc[(A_test['Race'] == 1)] = 'Asian-Pac-Islander'\n",
"A_test.Race.loc[(A_test['Race'] == 2)] = 'Black'\n",
"A_test.Race.loc[(A_test['Race'] == 3)] = 'Other'\n",
"A_test.Race.loc[(A_test['Race'] == 4)] = 'White'"
"A_test = A_test.reset_index(drop=True)"
]
},
{
@@ -251,7 +247,7 @@
"outputs": [],
"source": [
"sweep.fit(X_train, Y_train,\n",
" sensitive_features=A_train.Sex)\n",
" sensitive_features=A_train.sex)\n",
"\n",
"predictors = sweep._predictors"
]
@@ -274,9 +270,9 @@
" classifier = lambda X: m.predict(X)\n",
" \n",
" error = ErrorRate()\n",
" error.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.Sex)\n",
" error.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.sex)\n",
" disparity = DemographicParity()\n",
" disparity.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.Sex)\n",
" disparity.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.sex)\n",
" \n",
" errors.append(error.gamma(classifier)[0])\n",
" disparities.append(disparity.gamma(classifier).max())\n",
@@ -440,7 +436,7 @@
"metadata": {},
"outputs": [],
"source": [
"sf = { 'sex': A_test.Sex, 'race': A_test.Race }\n",
"sf = { 'sex': A_test.sex, 'race': A_test.race }\n",
"\n",
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
"\n",

View File

@@ -5,4 +5,3 @@ dependencies:
- azureml-contrib-fairness
- fairlearn==0.4.6
- joblib
- shap

View File

@@ -82,8 +82,7 @@
"from sklearn import svm\n",
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
"from sklearn.linear_model import LogisticRegression\n",
"import pandas as pd\n",
"import shap"
"import pandas as pd"
]
},
{
@@ -99,7 +98,10 @@
"metadata": {},
"outputs": [],
"source": [
"X_raw, Y = shap.datasets.adult()"
"from sklearn.datasets import fetch_openml\n",
"data = fetch_openml(data_id=1590, as_frame=True)\n",
"X_raw = data.data\n",
"Y = (data.target == '>50K') * 1"
]
},
{
@@ -115,7 +117,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(X_raw[\"Race\"].value_counts().to_dict())"
"print(X_raw[\"race\"].value_counts().to_dict())"
]
},
{
@@ -134,9 +136,9 @@
"metadata": {},
"outputs": [],
"source": [
"A = X_raw[['Sex','Race']]\n",
"X = X_raw.drop(labels=['Sex', 'Race'],axis = 1)\n",
"X = pd.get_dummies(X)"
"A = X_raw[['sex','race']]\n",
"X = X_raw.drop(labels=['sex', 'race'],axis = 1)\n",
"X_dummies = pd.get_dummies(X)"
]
},
{
@@ -153,8 +155,8 @@
"outputs": [],
"source": [
"sc = StandardScaler()\n",
"X_scaled = sc.fit_transform(X)\n",
"X_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n",
"X_scaled = sc.fit_transform(X_dummies)\n",
"X_scaled = pd.DataFrame(X_scaled, columns=X_dummies.columns)\n",
"\n",
"le = LabelEncoder()\n",
"Y = le.fit_transform(Y)"
@@ -185,18 +187,7 @@
"X_train = X_train.reset_index(drop=True)\n",
"A_train = A_train.reset_index(drop=True)\n",
"X_test = X_test.reset_index(drop=True)\n",
"A_test = A_test.reset_index(drop=True)\n",
"\n",
"# Improve labels\n",
"A_test.Sex.loc[(A_test['Sex'] == 0)] = 'female'\n",
"A_test.Sex.loc[(A_test['Sex'] == 1)] = 'male'\n",
"\n",
"\n",
"A_test.Race.loc[(A_test['Race'] == 0)] = 'Amer-Indian-Eskimo'\n",
"A_test.Race.loc[(A_test['Race'] == 1)] = 'Asian-Pac-Islander'\n",
"A_test.Race.loc[(A_test['Race'] == 2)] = 'Black'\n",
"A_test.Race.loc[(A_test['Race'] == 3)] = 'Other'\n",
"A_test.Race.loc[(A_test['Race'] == 4)] = 'White'"
"A_test = A_test.reset_index(drop=True)"
]
},
{
@@ -380,7 +371,7 @@
"metadata": {},
"outputs": [],
"source": [
"sf = { 'Race': A_test.Race, 'Sex': A_test.Sex }\n",
"sf = { 'Race': A_test.race, 'Sex': A_test.sex }\n",
"\n",
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
"\n",
@@ -499,7 +490,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
"version": "3.6.10"
}
},
"nbformat": 4,

View File

@@ -5,4 +5,3 @@ dependencies:
- azureml-contrib-fairness
- fairlearn==0.4.6
- joblib
- shap

View File

@@ -173,7 +173,7 @@ The main code of the file must be indented so that it is under this condition.
## automl_setup fails
1. On Windows, make sure that you are running automl_setup from an Anconda Prompt window rather than a regular cmd window. You can launch the "Anaconda Prompt" window by hitting the Start button and typing "Anaconda Prompt". If you don't see the application "Anaconda Prompt", you might not have conda or mini conda installed. In that case, you can install it [here](https://conda.io/miniconda.html)
2. Check that you have conda 64-bit installed rather than 32-bit. You can check this with the command `conda info`. The `platform` should be `win-64` for Windows or `osx-64` for Mac.
3. Check that you have conda 4.4.10 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`.
3. Check that you have conda 4.7.8 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`.
4. On Linux, if the error is `gcc: error trying to exec 'cc1plus': execvp: No such file or directory`, install build essentials using the command `sudo apt-get install build-essential`.
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>`.

View File

@@ -6,7 +6,7 @@ dependencies:
- python>=3.5.2,<3.6.8
- nb_conda
- matplotlib==2.1.0
- numpy~=1.18.0
- numpy==1.18.5
- cython
- urllib3<1.24
- scipy==1.4.1
@@ -24,5 +24,5 @@ dependencies:
- pytorch-transformers==1.0.0
- spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.15.0/validated_win32_requirements.txt [--no-deps]
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.16.0/validated_win32_requirements.txt [--no-deps]

View File

@@ -6,7 +6,7 @@ dependencies:
- python>=3.5.2,<3.6.8
- nb_conda
- matplotlib==2.1.0
- numpy~=1.18.0
- numpy==1.18.5
- cython
- urllib3<1.24
- scipy==1.4.1
@@ -24,5 +24,5 @@ dependencies:
- pytorch-transformers==1.0.0
- spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.15.0/validated_linux_requirements.txt [--no-deps]
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.16.0/validated_linux_requirements.txt [--no-deps]

View File

@@ -7,7 +7,7 @@ dependencies:
- python>=3.5.2,<3.6.8
- nb_conda
- matplotlib==2.1.0
- numpy~=1.18.0
- numpy==1.18.5
- cython
- urllib3<1.24
- scipy==1.4.1
@@ -25,4 +25,4 @@ dependencies:
- pytorch-transformers==1.0.0
- spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.15.0/validated_darwin_requirements.txt [--no-deps]
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.16.0/validated_darwin_requirements.txt [--no-deps]

View File

@@ -6,11 +6,22 @@ set PIP_NO_WARN_SCRIPT_LOCATION=0
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl"
IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml"
SET check_conda_version_script="check_conda_version.py"
IF NOT EXIST %automl_env_file% GOTO YmlMissing
IF "%CONDA_EXE%"=="" GOTO CondaMissing
IF NOT EXIST %check_conda_version_script% GOTO VersionCheckMissing
python "%check_conda_version_script%"
IF errorlevel 1 GOTO ErrorExit:
SET replace_version_script="replace_latest_version.ps1"
IF EXIST %replace_version_script% (
powershell -file %replace_version_script% %automl_env_file%
)
call conda activate %conda_env_name% 2>nul:
if not errorlevel 1 (
@@ -54,6 +65,10 @@ echo If you are running an older version of Miniconda or Anaconda,
echo you can upgrade using the command: conda update conda
goto End
:VersionCheckMissing
echo File %check_conda_version_script% not found.
goto End
:YmlMissing
echo File %automl_env_file% not found.

View File

@@ -4,6 +4,7 @@ CONDA_ENV_NAME=$1
AUTOML_ENV_FILE=$2
OPTIONS=$3
PIP_NO_WARN_SCRIPT_LOCATION=0
CHECK_CONDA_VERSION_SCRIPT="check_conda_version.py"
if [ "$CONDA_ENV_NAME" == "" ]
then
@@ -20,6 +21,18 @@ if [ ! -f $AUTOML_ENV_FILE ]; then
exit 1
fi
if [ ! -f $CHECK_CONDA_VERSION_SCRIPT ]; then
echo "File $CHECK_CONDA_VERSION_SCRIPT not found"
exit 1
fi
python "$CHECK_CONDA_VERSION_SCRIPT"
if [ $? -ne 0 ]; then
exit 1
fi
sed -i 's/AZUREML-SDK-VERSION/latest/' $AUTOML_ENV_FILE
if source activate $CONDA_ENV_NAME 2> /dev/null
then
echo "Upgrading existing conda environment" $CONDA_ENV_NAME

View File

@@ -4,6 +4,7 @@ CONDA_ENV_NAME=$1
AUTOML_ENV_FILE=$2
OPTIONS=$3
PIP_NO_WARN_SCRIPT_LOCATION=0
CHECK_CONDA_VERSION_SCRIPT="check_conda_version.py"
if [ "$CONDA_ENV_NAME" == "" ]
then
@@ -20,6 +21,18 @@ if [ ! -f $AUTOML_ENV_FILE ]; then
exit 1
fi
if [ ! -f $CHECK_CONDA_VERSION_SCRIPT ]; then
echo "File $CHECK_CONDA_VERSION_SCRIPT not found"
exit 1
fi
python "$CHECK_CONDA_VERSION_SCRIPT"
if [ $? -ne 0 ]; then
exit 1
fi
sed -i '' 's/AZUREML-SDK-VERSION/latest/' $AUTOML_ENV_FILE
if source activate $CONDA_ENV_NAME 2> /dev/null
then
echo "Upgrading existing conda environment" $CONDA_ENV_NAME

View File

@@ -0,0 +1,26 @@
from distutils.version import LooseVersion
import platform
try:
import conda
except:
print('Failed to import conda.')
print('This setup is usually run from the base conda environment.')
print('You can activate the base environment using the command "conda activate base"')
exit(1)
architecture = platform.architecture()[0]
if architecture != "64bit":
print('This setup requires 64bit Anaconda or Miniconda. Found: ' + architecture)
exit(1)
minimumVersion = "4.7.8"
versionInvalid = (LooseVersion(conda.__version__) < LooseVersion(minimumVersion))
if versionInvalid:
print('Setup requires conda version ' + minimumVersion + ' or higher.')
print('You can use the command "conda update conda" to upgrade conda.')
exit(versionInvalid)

View File

@@ -105,7 +105,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -93,7 +93,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -424,15 +424,26 @@
"source": [
"This Credit Card fraud Detection dataset is made available under the Open Database License: http://opendatacommons.org/licenses/odbl/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: http://opendatacommons.org/licenses/dbcl/1.0/ and is available at: https://www.kaggle.com/mlg-ulb/creditcardfraud\n",
"\n",
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u00a9 Libre de Bruxelles) on big data mining and fraud detection.\n",
"More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
"\n",
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u0192\u00c2\u00a9 Libre de Bruxelles) on big data mining and fraud detection. More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
"Please cite the following works:\n",
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tAndrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
"o\tDal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing"
"\n",
"Andrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
"\n",
"Dal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
"\n",
"Dal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
"\n",
"Dal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
"\n",
"Carcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
"\n",
"Carcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing\n",
"\n",
"Bertrand Lebichot, Yann-A\u00c3\u00abl Le Borgne, Liyun He, Frederic Obl\u00c3\u00a9, Gianluca Bontempi Deep-Learning Domain Adaptation Techniques for Credit Cards Fraud Detection, INNSBDDL 2019: Recent Advances in Big Data and Deep Learning, pp 78-88, 2019\n",
"\n",
"Fabrizio Carcillo, Yann-A\u00c3\u00abl Le Borgne, Olivier Caelen, Frederic Obl\u00c3\u00a9, Gianluca Bontempi Combining Unsupervised and Supervised Learning in Credit Card Fraud Detection Information Sciences, 2019"
]
}
],

View File

@@ -88,7 +88,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -550,7 +550,7 @@
"metadata": {
"authors": [
{
"name": "vivijay"
"name": "anshirga"
}
],
"kernelspec": {

View File

@@ -92,7 +92,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -114,7 +114,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -87,7 +87,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -97,7 +97,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -94,7 +94,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -82,7 +82,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -96,7 +96,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -98,7 +98,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -92,7 +92,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -295,8 +295,7 @@
"# environment, otherwise if a model is trained or deployed in a different environment this can\n",
"# cause errors. Please take extra care when specifying your dependencies in a production environment.\n",
"azureml_pip_packages.extend(['sklearn-pandas', 'pyyaml', sklearn_dep, pandas_dep])\n",
"run_config.environment.python.conda_dependencies = CondaDependencies.create(pip_packages=azureml_pip_packages,\n",
" pin_sdk_version=False)\n",
"run_config.environment.python.conda_dependencies = CondaDependencies.create(pip_packages=azureml_pip_packages)\n",
"# Now submit a run on AmlCompute\n",
"from azureml.core.script_run_config import ScriptRunConfig\n",
"\n",
@@ -460,8 +459,7 @@
"# environment, otherwise if a model is trained or deployed in a different environment this can\n",
"# cause errors. Please take extra care when specifying your dependencies in a production environment.\n",
"azureml_pip_packages.extend(['sklearn-pandas', 'pyyaml', sklearn_dep, pandas_dep])\n",
"myenv = CondaDependencies.create(pip_packages=azureml_pip_packages,\n",
" pin_sdk_version=False)\n",
"myenv = CondaDependencies.create(pip_packages=azureml_pip_packages)\n",
"\n",
"with open(\"myenv.yml\",\"w\") as f:\n",
" f.write(myenv.serialize_to_string())\n",

View File

@@ -0,0 +1,274 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-use-databricks-as-compute-target.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Azure Machine Learning Pipeline with KustoStep\n",
"To use Kusto as a compute target from [Azure Machine Learning Pipeline](https://aka.ms/pl-concept), a KustoStep is used. A KustoStep enables the functionality of running Kusto queries on a target Kusto cluster in Azure ML Pipelines. Each KustoStep can target one Kusto cluster and perform multiple queries on them. This notebook demonstrates the use of KustoStep in Azure Machine Learning (AML) Pipeline.\n",
"\n",
"## Before you begin:\n",
"\n",
"1. **Have an Azure Machine Learning workspace**: You will need details of this workspace later on to define KustoStep.\n",
"2. **Have a Service Principal**: You will need a service principal and use its credentials to access your cluster. See [this](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal) for more information.\n",
"3. **Have a Blob storage**: You will need a Azure Blob storage for uploading the output of your Kusto query."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Azure Machine Learning and Pipeline SDK-specific imports"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import azureml.core\n",
"from azureml.core.runconfig import JarLibrary\n",
"from azureml.core.compute import ComputeTarget, KustoCompute\n",
"from azureml.exceptions import ComputeTargetException\n",
"from azureml.core import Workspace, Experiment\n",
"from azureml.pipeline.core import Pipeline, PipelineData\n",
"from azureml.pipeline.steps import KustoStep\n",
"from azureml.core.datastore import Datastore\n",
"from azureml.data.data_reference import DataReference\n",
"\n",
"# Check core SDK version number\n",
"print(\"SDK version:\", azureml.core.VERSION)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize Workspace\n",
"\n",
"Initialize a workspace object from persisted configuration. If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the [configuration Notebook](https://aka.ms/pl-config) first if you haven't."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ws = Workspace.from_config()\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Attach Kusto compute target\n",
"Next, you need to create a Kusto compute target and give it a name. You will use this name to refer to your Kusto compute target inside Azure Machine Learning. Your workspace will be associated to this Kusto compute target. You will also need to provide some credentials that will be used to enable access to your target Kusto cluster and database.\n",
"\n",
"- **Resource Group** - The resource group name of your Azure Machine Learning workspace\n",
"- **Workspace Name** - The workspace name of your Azure Machine Learning workspace\n",
"- **Resource ID** - The resource ID of your Kusto cluster\n",
"- **Tenant ID** - The tenant ID associated to your Kusto cluster\n",
"- **Application ID** - The Application ID associated to your Kusto cluster\n",
"- **Application Key** - The Application key associated to your Kusto cluster\n",
"- **Kusto Connection String** - The connection string of your Kusto cluster\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"sample-databrickscompute-attach"
]
},
"outputs": [],
"source": [
"compute_name = \"<compute_name>\" # Name to associate with new compute in workspace\n",
"\n",
"# Account details associated to the target Kusto cluster\n",
"resource_id = \"<resource_id>\" # Resource ID of the Kusto cluster\n",
"kusto_connection_string = \"<kusto_connection_string>\" # Connection string of the Kusto cluster\n",
"application_id = \"<application_id>\" # Application ID associated to the Kusto cluster\n",
"application_key = \"<application_key>\" # Application Key associated to the Kusto cluster\n",
"tenant_id = \"<tenant_id>\" # Tenant ID associated to the Kusto cluster\n",
"\n",
"try:\n",
" kusto_compute = KustoCompute(workspace=ws, name=compute_name)\n",
" print('Compute target {} already exists'.format(compute_name))\n",
"except ComputeTargetException:\n",
" print('Compute not found, will use provided parameters to attach new one')\n",
" config = KustoCompute.attach_configuration(resource_group=ws.resource_group, workspace_name=ws.name, \n",
" resource_id=resource_id, tenant_id=tenant_id, \n",
" kusto_connection_string=kusto_connection_string, \n",
" application_id=application_id, application_key=application_key)\n",
" kusto_compute=ComputeTarget.attach(ws, compute_name, config)\n",
" kusto_compute.wait_for_completion(True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup output\n",
"To use Kusto as a compute target for Azure Machine Learning Pipeline, a KustoStep is used. Currently KustoStep only supports uploading results to Azure Blob store. Let's define an output datastore via PipelineData to be used in KustoStep."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.pipeline.core import PipelineParameter\n",
"\n",
"# Use the default blob storage\n",
"def_blob_store = Datastore.get(ws, \"workspaceblobstore\")\n",
"print('Datastore {} will be used'.format(def_blob_store.name))\n",
"\n",
"step_1_output = PipelineData(\"output\", datastore=def_blob_store)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Add a KustoStep to Pipeline\n",
"Adds a Kusto query as a step in a Pipeline.\n",
"- **name:** Name of the Module\n",
"- **compute_target:** Name of Kusto compute target\n",
"- **database_name:** Name of the database to perform Kusto query on\n",
"- **query_directory:** Path to folder that contains only a text file with Kusto queries (see [here](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/) for more details on Kusto queries). \n",
" - If the query is parameterized, then the text file must also include any declaration of query parameters (see [here](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/queryparametersstatement?pivots=azuredataexplorer) for more details on query parameters declaration statements). \n",
" - An example of the query text file could just contain the query \"StormEvents | count | as HowManyRecords;\", where StormEvents is the table name. \n",
" - Note. the text file should just contain the declarations and queries without quotation marks around them.\n",
"- **outputs:** Output binding to an Azure Blob Store.\n",
"- **parameter_dict (optional):** Dictionary that contains the values of parameters declared in the query text file in the **query_directory** mentioned above.\n",
" - Dictionary key is the parameter name, and dictionary value is the parameter value.\n",
" - For example, parameter_dict = {\"paramName1\": \"paramValue1\", \"paramName2\": \"paramValue2\"}\n",
"- **allow_reuse (optional):** Whether the step should reuse previous results when run with the same settings/inputs (default to False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"database_name = \"<database_name>\" # Name of the database to perform Kusto queries on\n",
"query_directory = \"<query_directory>\" # Path to folder that contains a text file with Kusto queries\n",
"\n",
"kustoStep = KustoStep(\n",
" name='KustoNotebook',\n",
" compute_target=compute_name,\n",
" database_name=database_name,\n",
" query_directory=query_directory,\n",
" output=step_1_output,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Build and submit the Experiment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"steps = [kustoStep]\n",
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
"pipeline_run = Experiment(ws, 'Notebook_demo').submit(pipeline)\n",
"pipeline_run.wait_for_completion()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# View Run Details"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.widgets import RunDetails\n",
"RunDetails(pipeline_run).show()"
]
}
],
"metadata": {
"authors": [
{
"name": "t-kachia"
}
],
"category": "tutorial",
"compute": [
"Kusto"
],
"datasets": [
"Custom"
],
"deployment": [
"None"
],
"exclude_from_index": false,
"framework": [
"Azure ML, Kusto"
],
"friendly_name": "How to use KustoStep with AML Pipelines",
"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.6"
},
"order_index": 5,
"star_tag": [
"featured"
],
"tags": [
"None"
],
"task": "Demonstrates the use of KustoStep"
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -477,7 +477,7 @@
"metadata": {
"authors": [
{
"name": "sanpil"
"name": "anshirga"
}
],
"category": "tutorial",

View File

@@ -774,7 +774,7 @@
"outputs": [],
"source": [
"# Before we proceed we need to wait for the run to complete.\n",
"pipeline_run.wait_for_completion()\n",
"pipeline_run.wait_for_completion(show_output=False)\n",
"\n",
"# functions to download output to local and fetch as dataframe\n",
"def get_download_path(download_path, output_name):\n",

View File

@@ -6,5 +6,6 @@ These sample notebooks show you how to train and deploy models with popular mach
3. [TensorFlow](tensorflow): Train, hyperparameter tune and deploy TensorFlow models. Distributed training with TensorFlow.
4. [Keras](keras): Train, hyperparameter tune and deploy Keras models.
5. [Chainer](chainer): Train, hyperparameter tune and deploy Chainer models. Distributed training with Chainer.
6. [Fastai](fastai): Train, hyperparameter tune and deploy Fastai models.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/ml-frameworks/README.png)

View File

@@ -0,0 +1,371 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/ml-frameworks/fastai/train-with-custom-docker/fastai-with-custom-docker.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": [
"# Train a model using a custom Docker image"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this tutorial, learn how to use a custom Docker image when training models with Azure Machine Learning.\n",
"\n",
"The example scripts in this article are used to classify pet images by creating a convolutional neural network. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set up the experiment\n",
"This section sets up the training experiment by initializing a workspace, creating an experiment, and uploading the training data and training scripts."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Initialize a workspace\n",
"The Azure Machine Learning workspace is the top-level resource for the service. It provides you with a centralized place to work with all the artifacts you create. In the Python SDK, you can access the workspace artifacts by creating a `workspace` object.\n",
"\n",
"Create a workspace object from the config.json file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Prepare scripts\n",
"Create a directory titled `fastai-example`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.makedirs('fastai-example', exist_ok=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then run the cell below to create the training script train.py in the directory."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"%%writefile fastai-example/train.py\n",
"\n",
"from fastai.vision.all import *\n",
"\n",
"path = untar_data(URLs.PETS)\n",
"path.ls()\n",
"\n",
"files = get_image_files(path/\"images\")\n",
"len(files)\n",
"\n",
"#(Path('/home/ashwin/.fastai/data/oxford-iiit-pet/images/yorkshire_terrier_102.jpg'),Path('/home/ashwin/.fastai/data/oxford-iiit-pet/images/great_pyrenees_102.jpg'))\n",
"\n",
"def label_func(f): return f[0].isupper()\n",
"\n",
"#To get our data ready for a model, we need to put it in a DataLoaders object. Here we have a function that labels using the file names, so we will use ImageDataLoaders.from_name_func. There are other factory methods of ImageDataLoaders that could be more suitable for your problem, so make sure to check them all in vision.data.\n",
"\n",
"dls = ImageDataLoaders.from_name_func(path, files, label_func, item_tfms=Resize(224))\n",
"\n",
"#We have passed to this function the directory we're working in, the files we grabbed, our label_func and one last piece as item_tfms: this is a Transform applied on all items of our dataset that will resize each imge to 224 by 224, by using a random crop on the largest dimension to make it a square, then resizing to 224 by 224. If we didn't pass this, we would get an error later as it would be impossible to batch the items together.\n",
"\n",
"dls.show_batch()\n",
"\n",
"learn = cnn_learner(dls, resnet34, metrics=error_rate)\n",
"learn.fine_tune(1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Define your environment\n",
"Create an environment object and enable Docker."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Environment\n",
"\n",
"fastai_env = Environment(\"fastai\")\n",
"fastai_env.docker.enabled = True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This specified base image supports the fast.ai library which allows for distributed deep learning capabilities. For more information, see the [fast.ai DockerHub](https://hub.docker.com/u/fastdotai). \n",
"\n",
"When you are using your custom Docker image, you might already have your Python environment properly set up. In that case, set the `user_managed_dependencies` flag to True in order to leverage your custom image's built-in python environment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fastai_env.docker.base_image = \"fastdotai/fastai:latest\"\n",
"fastai_env.python.user_managed_dependencies = True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To use an image from a private container registry that is not in your workspace, you must use `docker.base_image_registry` to specify the address of the repository as well as a username and password."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```python\n",
"fastai_env.docker.base_image_registry.address = \"myregistry.azurecr.io\"\n",
"fastai_env.docker.base_image_registry.username = \"username\"\n",
"fastai_env.docker.base_image_registry.password = \"password\"\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is also possible to use a custom Dockerfile. Use this approach if you need to install non-Python packages as dependencies and remember to set the base image to None. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Specify docker steps as a string:\n",
"```python \n",
"dockerfile = r\"\"\" \\\n",
"FROM mcr.microsoft.com/azureml/base:intelmpi2018.3-ubuntu16.04\n",
"RUN echo \"Hello from custom container!\" \\\n",
"\"\"\"\n",
"```\n",
"Set base image to None, because the image is defined by dockerfile:\n",
"```python\n",
"fastai_env.docker.base_image = None \\\n",
"fastai_env.docker.base_dockerfile = dockerfile\n",
"```\n",
"Alternatively, load the string from a file:\n",
"```python\n",
"fastai_env.docker.base_image = None \\\n",
"fastai_env.docker.base_dockerfile = \"./Dockerfile\"\n",
"```"
]
},
{
"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 training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
"\n",
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
"\n",
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
"from azureml.core.compute_target import ComputeTargetException\n",
"\n",
"# choose a name for your cluster\n",
"cluster_name = \"gpu-cluster\"\n",
"\n",
"try:\n",
" compute_target = ComputeTarget(workspace=ws, name=cluster_name)\n",
" print('Found existing compute target.')\n",
"except ComputeTargetException:\n",
" print('Creating a new compute target...')\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_NC6',\n",
" max_nodes=4)\n",
"\n",
" # create the cluster\n",
" compute_target = ComputeTarget.create(ws, cluster_name, compute_config)\n",
"\n",
" compute_target.wait_for_completion(show_output=True)\n",
"\n",
"# use get_status() to get a detailed status for the current AmlCompute\n",
"print(compute_target.get_status().serialize())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a ScriptRunConfig\n",
"This ScriptRunConfig will configure your job for execution on the desired compute target."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"from azureml.core import ScriptRunConfig\n",
"\n",
"fastai_config = ScriptRunConfig(source_directory='fastai-example',\n",
" script='train.py',\n",
" compute_target=compute_target,\n",
" environment=fastai_env)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Submit your run\n",
"When a training run is submitted using a ScriptRunConfig object, the submit method returns an object of type ScriptRun. The returned ScriptRun object gives you programmatic access to information about the training run. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"from azureml.core import Experiment\n",
"\n",
"run = Experiment(ws,'fastai-custom-image').submit(fastai_config)\n",
"run.wait_for_completion(show_output=True)"
]
}
],
"metadata": {
"authors": [
{
"name": "sagopal"
}
],
"category": "training",
"compute": [
"AML Compute"
],
"datasets": [
"Oxford IIIT Pet"
],
"deployment": [
"None"
],
"exclude_from_index": false,
"framework": [
"Pytorch"
],
"friendly_name": "Train a model with a custom Docker image",
"index_order": 1,
"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"
},
"nteract": {
"version": "nteract-front-end@1.0.0"
},
"tags": [
"None"
],
"task": "Train with custom Docker image"
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,5 @@
name: fastai-with-custom-docker
dependencies:
- pip:
- azureml-sdk
- fastai==1.0.61

View File

@@ -420,7 +420,9 @@
" script='tf_mnist_with_checkpoint.py',\n",
" arguments=args,\n",
" compute_target=compute_target,\n",
" environment=tf_env)"
" environment=tf_env)\n",
"\n",
"src.run_config.data_references = {checkpoint_data_ref.data_reference_name : checkpoint_data_ref.to_config()}"
]
},
{

View File

@@ -100,7 +100,7 @@
"\n",
"# Check core SDK version number\n",
"\n",
"print(\"This notebook was created using SDK version 1.15.0, you are currently running version\", azureml.core.VERSION)"
"print(\"This notebook was created using SDK version 1.16.0, you are currently running version\", azureml.core.VERSION)"
]
},
{
@@ -378,7 +378,13 @@
"metadata": {},
"outputs": [],
"source": [
"file_name = 'logging-api/myfile.txt'\n",
"import os\n",
"directory = 'logging-api'\n",
"\n",
"if not os.path.exists(directory):\n",
" os.mkdir(directory)\n",
"\n",
"file_name = os.path.join(directory, \"myfile.txt\")\n",
"\n",
"with open(file_name, \"w\") as f:\n",
" f.write('This is an output file that will be uploaded.\\n')\n",

View File

@@ -28,9 +28,9 @@ mounted_input_path = sys.argv[1]
mounted_output_path = sys.argv[2]
os.makedirs(mounted_output_path, exist_ok=True)
convert(os.path.join(mounted_input_path, 'train-images-idx3-ubyte'),
os.path.join(mounted_input_path, 'train-labels-idx1-ubyte'),
convert(os.path.join(mounted_input_path, 'mnist-fashion/train-images-idx3-ubyte'),
os.path.join(mounted_input_path, 'mnist-fashion/train-labels-idx1-ubyte'),
os.path.join(mounted_output_path, 'mnist_train.csv'), 60000)
convert(os.path.join(mounted_input_path, 't10k-images-idx3-ubyte'),
os.path.join(mounted_input_path, 't10k-labels-idx1-ubyte'),
convert(os.path.join(mounted_input_path, 'mnist-fashion/t10k-images-idx3-ubyte'),
os.path.join(mounted_input_path, 'mnist-fashion/t10k-labels-idx1-ubyte'),
os.path.join(mounted_output_path, 'mnist_test.csv'), 10000)

View File

@@ -65,8 +65,8 @@
"source": [
"import os\n",
"import azureml.core\n",
"from azureml.core import Workspace, Dataset, Datastore, ComputeTarget, Experiment\n",
"from azureml.pipeline.steps import PythonScriptStep, EstimatorStep\n",
"from azureml.core import Workspace, Dataset, Datastore, ComputeTarget, Experiment, ScriptRunConfig\n",
"from azureml.pipeline.steps import PythonScriptStep\n",
"from azureml.pipeline.core import Pipeline\n",
"# check core SDK version number\n",
"print(\"Azure ML SDK Version: \", azureml.core.VERSION)"
@@ -138,7 +138,7 @@
"from azureml.core.compute_target import ComputeTargetException\n",
"\n",
"# choose a name for your cluster\n",
"cluster_name = \"amlcomp\"\n",
"cluster_name = \"gpu-cluster\"\n",
"\n",
"try:\n",
" compute_target = ComputeTarget(workspace=workspace, name=cluster_name)\n",
@@ -165,9 +165,7 @@
"source": [
"## Create the Fashion MNIST dataset\n",
"\n",
"By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred.\n",
"\n",
"Every workspace comes with a default [datastore](https://docs.microsoft.com/azure/machine-learning/service/how-to-access-data) (and you can register more) which is backed by the Azure blob storage account associated with the workspace. We can use it to transfer data from local to the cloud, and create a dataset from it. We will now upload the [Fashion MNIST](./data) to the default datastore (blob) within your workspace."
"By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred."
]
},
{
@@ -176,28 +174,8 @@
"metadata": {},
"outputs": [],
"source": [
"datastore = workspace.get_default_datastore()\n",
"datastore.upload_files(files = ['data/t10k-images-idx3-ubyte', 'data/t10k-labels-idx1-ubyte',\n",
" 'data/train-images-idx3-ubyte','data/train-labels-idx1-ubyte'],\n",
" target_path = 'mnist-fashion',\n",
" overwrite = True,\n",
" show_progress = True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then we will create an unregistered FileDataset pointing to the path in the datastore. You can also create a dataset from multiple paths. [Learn More](https://aka.ms/azureml/howto/createdatasets) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fashion_ds = Dataset.File.from_files([(datastore, 'mnist-fashion')])\n",
"data_urls = ['https://data4mldemo6150520719.blob.core.windows.net/demo/mnist-fashion']\n",
"fashion_ds = Dataset.File.from_files(data_urls)\n",
"\n",
"# list the files referenced by fashion_ds\n",
"fashion_ds.to_path()"
@@ -246,6 +224,7 @@
"source": [
"# write output to datastore under folder `outputdataset` and register it as a dataset after the experiment completes\n",
"# make sure the service principal in your datastore has blob data contributor role in order to write data back\n",
"datastore=workspace.get_default_datastore()\n",
"prepared_fashion_ds = OutputFileDatasetConfig(destination=(datastore, 'outputdataset/{run-id}')).register_on_complete(name='prepared_fashion_ds')"
]
},
@@ -277,7 +256,7 @@
"source": [
"### Step 2: train CNN with Keras\n",
"\n",
"Next, we construct an `azureml.train.Estimator` estimator object. [EstimatorStep](https://docs.microsoft.com/python/api/azureml-pipeline-steps/azureml.pipeline.steps.estimator_step.estimatorstep?view=azure-ml-py) adds a step to run Tensorflow Estimator in a Pipeline. It takes a dataset as the input."
"Next, construct a ScriptRunConfig to configure the training run that trains a CNN model using Keras. It takes a dataset as the input."
]
},
{
@@ -286,18 +265,61 @@
"metadata": {},
"outputs": [],
"source": [
"from azureml.train.estimator import Estimator\n",
"# set up training step with Estimator\n",
"est = Estimator(entry_script='train.py',\n",
" source_directory=script_folder,\n",
" pip_packages=['keras','tensorflow','numpy','scikit-learn', 'matplotlib','pandas'],\n",
" compute_target=compute_target)\n",
"%%writefile conda_dependencies.yml\n",
"\n",
"est_step = EstimatorStep(name='train step',\n",
" estimator=est,\n",
" # parse prepared_fashion_ds into tabulardataset and use it as input\n",
" estimator_entry_script_arguments=[prepared_fashion_ds.read_delimited_files().as_input(name='prepared_fashion_ds')],\n",
" compute_target=compute_target)"
"dependencies:\n",
"- python=3.6.2\n",
"- pip:\n",
" - azureml-defaults\n",
" - keras\n",
" - tensorflow\n",
" - numpy\n",
" - scikit-learn\n",
" - pandas\n",
" - matplotlib"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Environment\n",
"\n",
"keras_env = Environment.from_conda_specification(name = 'keras-env', file_path = './conda_dependencies.yml')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_src = ScriptRunConfig(source_directory=script_folder,\n",
" script='train.py',\n",
" compute_target=compute_target,\n",
" environment=keras_env)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pass the run configuration details into the PythonScriptStep."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_step = PythonScriptStep(name='train step',\n",
" arguments=[prepared_fashion_ds.read_delimited_files().as_input(name='prepared_fashion_ds')],\n",
" source_directory=train_src.source_directory,\n",
" script_name=train_src.script,\n",
" runconfig=train_src.run_config)"
]
},
{
@@ -317,7 +339,7 @@
"outputs": [],
"source": [
"# build pipeline & run experiment\n",
"pipeline = Pipeline(workspace, steps=[prep_step, est_step])\n",
"pipeline = Pipeline(workspace, steps=[prep_step, train_step])\n",
"run = exp.submit(pipeline)"
]
},
@@ -360,7 +382,23 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Azure Machine Learning dataset makes it easy to trace how your data is used in ML. [Learn More](https://docs.microsoft.com/azure/machine-learning/service/how-to-version-track-datasets#track-datasets-in-experiments)<br>"
"Azure Machine Learning dataset makes it easy to trace how your data is used in ML. [Learn More](https://docs.microsoft.com/azure/machine-learning/service/how-to-version-track-datasets#track-datasets-in-experiments)<br>\n",
"For each Machine Learning experiment, you can easily trace the datasets used as the input through `Run` object."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# get input datasets\n",
"prep_step = run.find_step_run('prepare step')[0]\n",
"inputs = prep_step.get_details()['inputDatasets']\n",
"input_dataset = inputs[0]['dataset']\n",
"\n",
"# list the files referenced by input_dataset\n",
"input_dataset.to_path()"
]
},
{
@@ -376,10 +414,11 @@
"metadata": {},
"outputs": [],
"source": [
"fashion_ds = fashion_ds.register(workspace = workspace,\n",
"fashion_ds = input_dataset.register(workspace = workspace,\n",
" name = 'fashion_ds',\n",
" description = 'image and label files from fashion mnist',\n",
" create_new_version = True)"
" create_new_version = True)\n",
"fashion_ds"
]
},
{

View File

@@ -41,6 +41,7 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
| :star:[How to use Dataset as a PipelineParameter](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-showcasing-dataset-and-pipelineparameter.ipynb) | Demonstrates the use of Dataset as a PipelineParameter | Custom | AML Compute | None | Azure ML | None |
| [How to use AdlaStep with AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-use-adla-as-compute-target.ipynb) | Demonstrates the use of AdlaStep | Custom | Azure Data Lake Analytics | None | Azure ML | None |
| :star:[How to use DatabricksStep with AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-use-databricks-as-compute-target.ipynb) | Demonstrates the use of DatabricksStep | Custom | Azure Databricks | None | Azure ML, Azure Databricks | None |
| :star:[How to use KustoStep with AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-use-kusto-as-compute-target.ipynb) | Demonstrates the use of KustoStep | Custom | Kusto | None | Azure ML, Kusto | None |
| :star:[How to use AutoMLStep with AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb) | Demonstrates the use of AutoMLStep | Custom | AML Compute | None | Automated Machine Learning | None |
| :star:[Azure Machine Learning Pipelines with Data Dependency](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-data-dependency-steps.ipynb) | Demonstrates how to construct a Pipeline with data dependency between steps | Custom | AML Compute | None | Azure ML | None |
| [How to use run a notebook as a step in AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-notebook-runner-step.ipynb) | Demonstrates the use of NotebookRunnerStep | Custom | AML Compute | None | Azure ML | None |
@@ -56,6 +57,7 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
|:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|:------------:|
| [Distributed Training with Chainer](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/chainer/distributed-chainer/distributed-chainer.ipynb) | Use the Chainer estimator to perform distributed training | MNIST | AML Compute | None | Chainer | None |
| [Train a model with hyperparameter tuning](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/chainer/train-hyperparameter-tune-deploy-with-chainer/train-hyperparameter-tune-deploy-with-chainer.ipynb) | Train a Convolutional Neural Network (CNN) | MNIST | AML Compute | Azure Container Instance | Chainer | None |
| [Train a model with a custom Docker image](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/fastai/fastai-with-custom-docker/fastai-with-custom-docker.ipynb) | Train with custom Docker image | Oxford IIIT Pet | AML Compute | None | Pytorch | None |
| [Train a DNN using hyperparameter tuning and deploying with Keras](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/keras/train-hyperparameter-tune-deploy-with-keras/train-hyperparameter-tune-deploy-with-keras.ipynb) | Create a multi-class classifier | MNIST | AML Compute | Azure Container Instance | TensorFlow | None |
| [Distributed PyTorch](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/pytorch/distributed-pytorch-with-horovod/distributed-pytorch-with-horovod.ipynb) | Train a model using the distributed training via Horovod | MNIST | AML Compute | None | PyTorch | None |
| [Distributed training with PyTorch](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/pytorch/distributed-pytorch-with-nccl-gloo/distributed-pytorch-with-nccl-gloo.ipynb) | Train a model using distributed training via Nccl/Gloo | MNIST | AML Compute | None | PyTorch | None |
@@ -130,6 +132,10 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
| [Logging APIs](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/track-and-monitor-experiments/logging-api/logging-api.ipynb) | Logging APIs and analyzing results | None | None | None | None | None |
| [configuration](https://github.com/Azure/MachineLearningNotebooks/blob/master//setup-environment/configuration.ipynb) | | | | | | |
| [tutorial-1st-experiment-sdk-train](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/create-first-ml-experiment/tutorial-1st-experiment-sdk-train.ipynb) | | | | | | |
| [day1-part1-setup](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/get-started-day1/day1-part1-setup.ipynb) | | | | | | |
| [day1-part2-hello-world](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/get-started-day1/day1-part2-hello-world.ipynb) | | | | | | |
| [day1-part3-train-model](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/get-started-day1/day1-part3-train-model.ipynb) | | | | | | |
| [day1-part4-data](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/get-started-day1/day1-part4-data.ipynb) | | | | | | |
| [img-classification-part1-training](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb) | | | | | | |
| [img-classification-part2-deploy](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb) | | | | | | |
| [img-classification-part3-deploy-encrypted](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/image-classification-mnist-data/img-classification-part3-deploy-encrypted.ipynb) | | | | | | |

View File

@@ -102,7 +102,7 @@
"source": [
"import azureml.core\n",
"\n",
"print(\"This notebook was created using version 1.15.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.16.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -0,0 +1,12 @@
# 01-create-workspace.py
from azureml.core import Workspace
# Example locations: 'westeurope' or 'eastus2' or 'westus2' or 'southeastasia'.
ws = Workspace.create(name='<my_workspace_name>',
subscription_id='<azure-subscription-id>',
resource_group='<myresourcegroup>',
create_resource_group=True,
location='<NAME_OF_REGION>')
# write out the workspace details to a configuration file: .azureml/config.json
ws.write_config(path='.azureml')

View File

@@ -0,0 +1,23 @@
# 02-create-compute.py
from azureml.core import Workspace
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
ws = Workspace.from_config()
# Choose a name for your CPU cluster
cpu_cluster_name = "cpu-cluster"
# Verify that cluster does not exist already
try:
cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)
print('Found existing cluster, use it.')
except ComputeTargetException:
cfg = AmlCompute.provisioning_configuration(
vm_size='STANDARD_D2_V2',
max_nodes=4,
idle_seconds_before_scaledown=2400
)
cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, cfg)
cpu_cluster.wait_for_completion(show_output=True)

View File

@@ -0,0 +1,13 @@
# 03-run-hello.py
from azureml.core import Workspace, Experiment, ScriptRunConfig
ws = Workspace.from_config()
experiment = Experiment(workspace=ws, name='day1-experiment-hello')
config = ScriptRunConfig(source_directory='./src',
script='hello.py',
compute_target='cpu-cluster')
run = experiment.submit(config)
aml_url = run.get_portal_url()
print(aml_url)

View File

@@ -0,0 +1,24 @@
# 04-run-pytorch.py
from azureml.core import Workspace
from azureml.core import Experiment
from azureml.core import Environment
from azureml.core import ScriptRunConfig
if __name__ == "__main__":
ws = Workspace.from_config()
experiment = Experiment(workspace=ws, name='day1-experiment-train')
config = ScriptRunConfig(source_directory='./src',
script='train.py',
compute_target='cpu-cluster')
# set up pytorch environment
env = Environment.from_conda_specification(
name='pytorch-env',
file_path='./environments/pytorch-env.yml'
)
config.run_config.environment = env
run = experiment.submit(config)
aml_url = run.get_portal_url()
print(aml_url)

View File

@@ -0,0 +1,7 @@
# 05-upload-data.py
from azureml.core import Workspace
ws = Workspace.from_config()
datastore = ws.get_default_datastore()
datastore.upload(src_dir='./data',
target_path='datasets/cifar10',
overwrite=True)

View File

@@ -0,0 +1,35 @@
# 06-run-pytorch-data.py
from azureml.core import Workspace
from azureml.core import Experiment
from azureml.core import Environment
from azureml.core import ScriptRunConfig
from azureml.core import Dataset
if __name__ == "__main__":
ws = Workspace.from_config()
datastore = ws.get_default_datastore()
dataset = Dataset.File.from_files(path=(datastore, 'datasets/cifar10'))
experiment = Experiment(workspace=ws, name='day1-experiment-data')
config = ScriptRunConfig(
source_directory='./src',
script='train.py',
compute_target='cpu-cluster',
arguments=[
'--data_path', dataset.as_named_input('input').as_mount(),
'--learning_rate', 0.003,
'--momentum', 0.92],
)
# set up pytorch environment
env = Environment.from_conda_specification(
name='pytorch-env',
file_path='./environments/pytorch-env.yml'
)
config.run_config.environment = env
run = experiment.submit(config)
aml_url = run.get_portal_url()
print("Submitted to compute cluster. Click link below")
print("")
print(aml_url)

View File

@@ -0,0 +1,25 @@
# Get Started (day 1) with Azure Machine Learning: IDE Users
This folder has been setup for IDE user (for example, VS Code or Pycharm) following the [Get started (day 1) with Azure Machine Learning tutorial series](https://aka.ms/day1aml).
The directory is structured as follows:
```Text
IDE-users
└──environments
| └──pytorch-env.yml
└──src
| └──hello.py
| └──model.py
| └──train.py
└──01-create-workspace.py
└──02-create-compute.py
└──03-run-hello.py
└──04-run-pytorch.py
└──05-upload-data.py
└──06-run-pytorch-data.py
```
Please refer to [the documentation](https://aka.ms/day1aml) for more details on these files.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/tutorials/get-started-day1/IDE/README.png)

View File

@@ -0,0 +1,9 @@
name: pytorch-env
channels:
- defaults
- pytorch
dependencies:
- python=3.6.2
- pytorch
- torchvision

View File

@@ -0,0 +1,2 @@
print("hello world!")

View File

@@ -0,0 +1,22 @@
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

View File

@@ -0,0 +1,52 @@
import torch
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from model import Net
# download CIFAR 10 data
trainset = torchvision.datasets.CIFAR10(
root="./data",
train=True,
download=True,
transform=torchvision.transforms.ToTensor(),
)
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=4, shuffle=True, num_workers=2
)
if __name__ == "__main__":
# define convolutional network
net = Net()
# set up pytorch loss / optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# train the network
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# unpack the data
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999:
loss = running_loss / 2000
print(f"epoch={epoch + 1}, batch={i + 1:5}: loss {loss:.2f}")
running_loss = 0.0
print("Finished Training")

View File

@@ -0,0 +1,2 @@
print("hello world!")

View File

@@ -0,0 +1,22 @@
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

View File

@@ -0,0 +1,62 @@
import torch
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from model import Net
from azureml.core import Run
# ADDITIONAL CODE: get AML run from the current context
run = Run.get_context()
# download CIFAR 10 data
trainset = torchvision.datasets.CIFAR10(
root='./data',
train=True,
download=True,
transform=torchvision.transforms.ToTensor()
)
trainloader = torch.utils.data.DataLoader(
trainset,
batch_size=4,
shuffle=True,
num_workers=2
)
if __name__ == "__main__":
# define convolutional network
net = Net()
# set up pytorch loss / optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# train the network
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# unpack the data
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999:
loss = running_loss / 2000
# ADDITIONAL CODE: log loss metric to AML
run.log('loss', loss)
print(f'epoch={epoch + 1}, batch={i + 1:5}: loss {loss:.2f}')
running_loss = 0.0
print('Finished Training')

View File

@@ -0,0 +1,22 @@
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

View File

@@ -0,0 +1,52 @@
import torch
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from model import Net
# download CIFAR 10 data
trainset = torchvision.datasets.CIFAR10(
root="./data",
train=True,
download=True,
transform=torchvision.transforms.ToTensor(),
)
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=4, shuffle=True, num_workers=2
)
if __name__ == "__main__":
# define convolutional network
net = Net()
# set up pytorch loss / optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# train the network
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# unpack the data
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999:
loss = running_loss / 2000
print(f"epoch={epoch + 1}, batch={i + 1:5}: loss {loss:.2f}")
running_loss = 0.0
print("Finished Training")

View File

@@ -0,0 +1,22 @@
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

View File

@@ -0,0 +1,96 @@
import os
import argparse
import torch
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from model import Net
from azureml.core import Run
run = Run.get_context()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'--data_path',
type=str,
help='Path to the training data'
)
parser.add_argument(
'--learning_rate',
type=float,
default=0.001,
help='Learning rate for SGD'
)
parser.add_argument(
'--momentum',
type=float,
default=0.9,
help='Momentum for SGD'
)
args = parser.parse_args()
print("===== DATA =====")
print("DATA PATH: " + args.data_path)
print("LIST FILES IN DATA PATH...")
print(os.listdir(args.data_path))
print("================")
# prepare DataLoader for CIFAR10 data
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
trainset = torchvision.datasets.CIFAR10(
root=args.data_path,
train=True,
download=False,
transform=transform,
)
trainloader = torch.utils.data.DataLoader(
trainset,
batch_size=4,
shuffle=True,
num_workers=2
)
# define convolutional network
net = Net()
# set up pytorch loss / optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(
net.parameters(),
lr=args.learning_rate,
momentum=args.momentum,
)
# train the network
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# unpack the data
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999:
loss = running_loss / 2000
run.log('loss', loss) # log loss metric to AML
print(f'epoch={epoch + 1}, batch={i + 1:5}: loss {loss:.2f}')
running_loss = 0.0
print('Finished Training')

View File

@@ -0,0 +1,11 @@
name: pytorch-aml-env
channels:
- defaults
- pytorch
dependencies:
- python=3.6.2
- pytorch
- torchvision
- pip
- pip:
- azureml-sdk

View File

@@ -0,0 +1,9 @@
name: pytorch-env
channels:
- defaults
- pytorch
dependencies:
- python=3.6.2
- pytorch
- torchvision

View File

@@ -0,0 +1,166 @@
{
"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/tutorials/day1-part1-setup.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Tutorial: Get started (day 1) with Azure Machine Learning (Part 1 of 4)\n",
"\n",
"---\n",
"## Introduction <a id='intro'></a>\n",
"\n",
"In this **four-part tutorial series**, you will learn the fundamentals of Azure Machine Learning and complete jobs-based Python machine learning tasks in the Azure cloud, including:\n",
"\n",
"1. Set up a compute cluster\n",
"2. Run code in the cloud using Azure Machine Learning's Python SDK.\n",
"3. Manage the Python environment you use for model training.\n",
"4. Upload data to Azure and consume that data in training.\n",
"\n",
"In this first part of the tutorial series you learn how to create an Azure Machine Learning Compute Cluster that will be used in subsequent parts of the series to submit jobs to. This notebook follows the steps provided on the [Python (day 1) - set up local computer documentation page](https://aka.ms/day1aml).\n",
"\n",
"## Pre-requisites <a id='pre-reqs'></a>\n",
"\n",
"- An Azure Subscription. If you don't have an Azure subscription, create a free account before you begin. Try [Azure Machine Learning](https://aka.ms/AMLFree) today.\n",
"- Familiarity with Python and Machine Learning concepts. For example, environments, training, scoring, and so on.\n",
"- If you are using a compute instance in Azure Machine Learning to run this notebook series, you are all set. Otherwise, please follow the [Configure a development environment for Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/how-to-configure-environment)\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Ensure you have the latest Azure Machine Learning Python SDK\n",
"\n",
"This tutorial series depends on having the Azure Machine Learning SDK version 1.14.0 onwards installed. You can check your version using the code cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import VERSION\n",
"\n",
"print ('Version: ' + VERSION)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If your version is below 1.14.0, then upgrade the SDK using `pip` (**Note: You may need to restart your kernel for the changes to take effect. Re-run the cell above to ensure you have the right version**).\n",
"\n",
"```bash\n",
"!pip install -U azureml-sdk\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create an Azure Machine Learning compute cluster <a id='createcc'></a>\n",
"\n",
"As this tutorial focuses on jobs-based machine learning tasks, you will be submitting python code to run on an Azure Machine Learning **Compute cluster**, which is well suited for large jobs and production. Therefore, you create an Azure Machine Learning compute cluster that will auto-scale between zero and four nodes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"create mlc",
"batchai"
]
},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
"from azureml.core.compute_target import ComputeTargetException\n",
"\n",
"ws = Workspace.from_config() # this automatically looks for a directory .azureml\n",
"\n",
"# Choose a name for your CPU cluster\n",
"cpu_cluster_name = \"cpu-cluster\"\n",
"\n",
"# Verify that cluster does not exist already\n",
"try:\n",
" cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" max_nodes=4, \n",
" idle_seconds_before_scaledown=2400)\n",
" cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
"\n",
"cpu_cluster.wait_for_completion(show_output=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> <span style=\"color:darkblue;font-weight:bold\"> ! INFORMATION \n",
"> When the cluster has been created it will have 0 nodes provisioned. Therefore, the cluster does not incur costs until you submit a job. This cluster will scale down when it has been idle for 2400 seconds (40 minutes).</span>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Next Steps\n",
"\n",
"In the next tutorial, you walk through submitting a script to the Azure Machine Learning compute cluster.\n",
"\n",
"[Tutorial: Run \"Hello World\" Python Script on Azure](day1-part2-hello-world.ipynb)\n"
]
}
],
"metadata": {
"authors": [
{
"name": "samkemp"
}
],
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
},
"notice": "Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License."
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,4 @@
name: day1-part1-setup
dependencies:
- pip:
- azureml-sdk

View File

@@ -0,0 +1,204 @@
{
"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/tutorials/get-started-day1/day1-part2-hello-world.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Tutorial: \"Hello World\" (Part 2 of 4)\n",
"\n",
"---\n",
"## Introduction\n",
"In **part 2 of this get started series**, you will submit a trivial \"hello world\" python script to the cloud by:\n",
"\n",
"- Running Python code in the cloud with Azure Machine Learning SDK\n",
"- Switching between debugging locally on a compute instance.\n",
"- Submitting remote runs in the cloud\n",
"- Monitoring and recording runs in the Azure Machine Learning studio\n",
"\n",
"This notebook follows the steps provided on the [Python (day 1) - \"hello world\" documentation page](https://aka.ms/day1aml). This tutorial is part of a **four-part tutorial series** in which you learn the fundamentals of Azure Machine Learning and complete simple jobs-based machine learning tasks in the Azure cloud. It builds off the work you completed in [Tutorial part 1: set up an Azure Machine Learning compute cluster](day1-part1-setup.ipynb).\n",
"\n",
"## Pre-requisites\n",
"\n",
"- Complete [Tutorial part 1: set up an Azure Machine Learning compute cluster](day1-part1-setup.ipynb) if you don't already have an Azure Machine Learning compute cluster.\n",
"- Familiarity with Python and Machine Learning concepts.\n",
"- If you are using a compute instance in Azure Machine Learning to run this notebook series, you are all set. Otherwise, please follow the [Configure a development environment for Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/how-to-configure-environment)\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Your code\n",
"\n",
"In the `code/hello` subdirectory you will find a trivial python script [hello.py](code/hello/hello.py) that has the following code:\n",
"\n",
"```Python\n",
"# code/hello/hello.py\n",
"print(\"hello world!\")\n",
"```\n",
"\n",
"In this tutorial you are going to submit this trivial python script to an Azure Machine Learning Compute Cluster."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Test in your development environment\n",
"\n",
"You can test your code works on a compute instance or locally (for example, a laptop), which has the benefit of interactive debugging of code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"!python code/hello/hello.py"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Submit your code to Azure Machine Learning\n",
"\n",
"Below you create a __*control script*__ this is where you specify _how_ your code is submitted to Azure Machine Learning. The code you submit to Azure Machine Learning (in this case `hello.py`) does not need anything specific to Azure Machine Learning - it can be any valid Python code. It is only the control script that is Azure Machine Learning specific.\n",
"\n",
"The code below will show a Jupyter widget that tracks the progress of your run, and displays logs.\n",
"\n",
"> <span style=\"color:purple; font-weight:bold\">! NOTE <br>\n",
"> The very first run will take 5-10minutes to complete. This is because in the background a docker image is built in the cloud, the compute cluster is resized from 0 to 1 node, and the docker image is downloaded to the compute. Subsequent runs are much quicker (~15 seconds) as the docker image is cached on the compute - you can test this by resubmitting the code below after the first run has completed.</span>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remote run",
"batchai",
"configure run",
"use notebook widget"
]
},
"outputs": [],
"source": [
"from azureml.core import Workspace, Experiment, ScriptRunConfig\n",
"from azureml.widgets import RunDetails\n",
"\n",
"ws = Workspace.from_config()\n",
"experiment = Experiment(workspace=ws, name='day1-experiment-hello')\n",
"\n",
"config = ScriptRunConfig(source_directory='./code/hello', script='hello.py', compute_target='cpu-cluster')\n",
"\n",
"run = experiment.submit(config)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Understanding the control code\n",
"\n",
"| Code |Description | \n",
"|---|---|\n",
"| `ws = Workspace.from_config()` | [Workspace](https://docs.microsoft.com/python/api/azureml-core/azureml.core.workspace.workspace?view=azure-ml-py&preserve-view=true) connects to your Azure Machine Learning workspace, so that you can communicate with your Azure Machine Learning resources. |\n",
"| `experiment = Experiment( ... )` | [Experiment](https://docs.microsoft.com/python/api/azureml-core/azureml.core.experiment.experiment?view=azure-ml-py&preserve-view=true) provides a simple way to organize multiple runs under a single name. <br>Later you can see how experiments make it easy to compare metrics between dozens of runs. |\n",
"| `config = ScriptRunConfig( ... )` | [ScriptRunConfig](https://docs.microsoft.com/python/api/azureml-core/azureml.core.scriptrunconfig?view=azure-ml-py&preserve-view=true) wraps your `hello.py` code and passes it to your workspace.<br> As the name suggests, you can use this class to _configure_ how you want your _script_ to _run_ in Azure Machine Learning. <br>Also specifies what compute target the script will run on. <br>In this code, the target is the compute cluster you created in the [setup tutorial](tutorial-1st-experiment-sdk-setup-local.md). |\n",
"| `run = experiment.submit(config)` | Submits your script. This submission is called a [Run](https://docs.microsoft.com/python/api/azureml-core/azureml.core.run(class)?view=azure-ml-py&preserve-view=true). <br>A run encapsulates a single execution of your code. Use a run to monitor the script progress, capture the output,<br> analyze the results, visualize metrics and more. |\n",
"| `aml_url = run.get_portal_url()` | The `run` object provides a handle on the execution of your code. Monitor its progress from <br> the Azure Machine Learning Studio with the URL that is printed from the python script. |\n",
"|`RunDetails(run).show()` | There is an Azure Machine Learning widget that shows the progress of your job along with streaming the log files.\n",
"\n",
"## View the logs\n",
"\n",
"The widget has a dropdown box titled **Output logs** select `70_driver_log.txt`, which shows the following standard output: \n",
"\n",
"```\n",
" 1: [2020-08-04T22:15:44.407305] Entering context manager injector.\n",
" 2: [context_manager_injector.py] Command line Options: Namespace(inject=['ProjectPythonPath:context_managers.ProjectPythonPath', 'RunHistory:context_managers.RunHistory', 'TrackUserError:context_managers.TrackUserError', 'UserExceptions:context_managers.UserExceptions'], invocation=['hello.py'])\n",
" 3: Starting the daemon thread to refresh tokens in background for process with pid = 31263\n",
" 4: Entering Run History Context Manager.\n",
" 5: Preparing to call script [ hello.py ] with arguments: []\n",
" 6: After variable expansion, calling script [ hello.py ] with arguments: []\n",
" 7:\n",
" 8: Hello world!\n",
" 9: Starting the daemon thread to refresh tokens in background for process with pid = 31263\n",
"10:\n",
"11:\n",
"12: The experiment completed successfully. Finalizing run...\n",
"13: Logging experiment finalizing status in history service.\n",
"14: [2020-08-04T22:15:46.541334] TimeoutHandler __init__\n",
"15: [2020-08-04T22:15:46.541396] TimeoutHandler __enter__\n",
"16: Cleaning up all outstanding Run operations, waiting 300.0 seconds\n",
"17: 1 items cleaning up...\n",
"18: Cleanup took 0.1812913417816162 seconds\n",
"19: [2020-08-04T22:15:47.040203] TimeoutHandler __exit__\n",
"```\n",
"\n",
"On line 8 above, you see the \"Hello world!\" output. The 70_driver_log.txt file contains the standard output from run and can be useful when debugging remote runs in the cloud. You can also view the run by clicking on the **Click here to see the run in Azure Machine Learning studio** link in the wdiget.\n",
"\n",
"## Next steps\n",
"\n",
"In this tutorial, you took a simple \"hello world\" script and ran it on Azure. You saw how to connect to your Azure Machine Learning workspace, create an Experiment, and submit your `hello.py` code to the cloud.\n",
"\n",
"In the [next tutorial](day1-part3-train-model.ipynb), you build on these learnings by running something more interesting than `print(\"Hello world!\")`.\n"
]
}
],
"metadata": {
"authors": [
{
"name": "samkemp"
}
],
"celltoolbar": "Edit Metadata",
"kernel_info": {
"name": "python3-azureml"
},
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
},
"notice": "Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.",
"nteract": {
"version": "nteract-front-end@1.0.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,5 @@
name: day1-part2-hello-world
dependencies:
- pip:
- azureml-sdk
- azureml-widgets

View File

@@ -0,0 +1,289 @@
{
"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/tutorials/get-started-day1/day1-part3-train-model.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Tutorial: Train your first ML model (Part 3 of 4)\n",
"\n",
"---\n",
"## Introduction\n",
"In the [previous tutorial](day1-part2-hello-world.ipynb), you ran a trivial \"Hello world!\" script in the cloud using Azure Machine Learning's Python SDK. This time you take it a step further by submitting a script that will train a machine learning model. This example will help you understand how Azure Machine Learning eases consistent behavior between debugging on a compute instance or laptop development environment, and remote runs.\n",
"\n",
"Learning these concepts means that by the end of this session, you can:\n",
"\n",
"* Use Conda to define an Azure Machine Learning environment.\n",
"* Train a model in the cloud.\n",
"* Log metrics to Azure Machine Learning.\n",
"\n",
"This notebook follows the steps provided on the [Python (day 1) - train a model documentation page](https://aka.ms/day1aml).\n",
"\n",
"## Prerequisites\n",
"\n",
"- You have completed the following:\n",
" - [Setup on your compute cluster](day1-part1-setup.ipynb)\n",
" - [Tutorial: Hello World example](day1-part2-hello-world.md)\n",
"- Familiarity with Python and Machine Learning concepts\n",
"- If you are using a compute instance in Azure Machine Learning to run this notebook series, you are all set. Otherwise, please follow the [Configure a development environment for Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/how-to-configure-environment)\n",
"---\n",
"\n",
"## Your machine learning code\n",
"\n",
"This tutorial shows you how to train a PyTorch model on the CIFAR 10 dataset using an Azure Machine Learning Cluster. In this case you will be using a CPU cluster, but this could equally be a GPU cluster. Whilst this tutorial uses PyTorch, the steps we show you apply to *any* machine learning code. \n",
"\n",
"In the `code/pytorch-cifar10-train` subdirectory you will see 2 files:\n",
"\n",
"1. [model.py](code/pytorch-cifar10-train/model.py) - this defines the neural network architecture\n",
"1. [train.py](code/pytorch-cifar10-train/train.py) - This is the training script. This script downloads the CIFAR10 dataset using PyTorch `torchvision.dataset` APIs, sets up the network defined in\n",
"`model.py`, and trains it for two epochs using standard SGD and cross-entropy loss.\n",
"\n",
"Note the code is based on [this introductory example from PyTorch](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html). "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Define the Python environment for your machine learning code\n",
"\n",
"For demonstration purposes, we're going to use a Conda environment but the steps for a pip virtual environment are almost identical. This environment has all the dependencies that your model and training script require. \n",
"\n",
"In the `configuration` directory there is a *conda dependencies* file called [pytorch-env.yml](configuration/pytorch-env.yml) that specifies the dependencies to run the python code. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Test in your development environment\n",
"\n",
"Test your script runs on either your compute instance or laptop using this environment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!python code/pytorch-cifar10-train/train.py"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**You should notice that the script has downloaded the data into a directory called `data`.**\n",
"\n",
"## Submit your machine learning code to Azure Machine Learning\n",
"\n",
"The difference to the control script below and the one used to submit \"hello world\" is that you adjust the environment to be set from the conda dependencies file you created earlier.\n",
"\n",
"> <span style=\"color:purple; font-weight:bold\">! NOTE <br>\n",
"> The first time you run this script, Azure Machine Learning will build a new docker image from your PyTorch environment. The whole run could take 5-10 minutes to complete. You can see the docker build logs in the widget by selecting the `20_image_build_log.txt` in the log files dropdown. This image will be reused in future runs making them run much quicker.</span>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remote run",
"batchai",
"configure run",
"use notebook widget"
]
},
"outputs": [],
"source": [
"from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig\n",
"from azureml.widgets import RunDetails\n",
"\n",
"ws = Workspace.from_config()\n",
"experiment = Experiment(workspace=ws, name='day1-experiment-train')\n",
"config = ScriptRunConfig(source_directory='code/pytorch-cifar10-train/', script='train.py', compute_target='cpu-cluster')\n",
"\n",
"env = Environment.from_conda_specification(name='pytorch-env', file_path='configuration/pytorch-env.yml')\n",
"config.run_config.environment = env\n",
"\n",
"run = experiment.submit(config)\n",
"\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Understand the control code\n",
"\n",
"Compared to the control script that submitted the \"hello world\" example, this control script introduces the following:\n",
"\n",
"| Code | Description\n",
"| --- | --- |\n",
"| `env = Environment.from_conda_specification( ...)` | Azure Machine Learning provides the concept of an `Environment` to represent a reproducible, <br>versioned Python environment for running experiments. Here you have created it from a yaml conda dependencies file.|\n",
"| `config.run_config.environment = env` | adds the environment to the ScriptRunConfig. |\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**There are many ways to create AML environments, including [from a pip requirements.txt](https://docs.microsoft.com/python/api/azureml-core/azureml.core.environment.environment?view=azure-ml-py&preserve-view=true#from-pip-requirements-name--file-path-), or even [from an existing local Conda environment](https://docs.microsoft.com/python/api/azureml-core/azureml.core.environment.environment?view=azure-ml-py&preserve-view=true#from-existing-conda-environment-name--conda-environment-name-).**\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once your image is built, select `70_driver_log.txt` to see the output of your training script, which should look like:\n",
"\n",
"```txt\n",
"Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz\n",
"...\n",
"Files already downloaded and verified\n",
"epoch=1, batch= 2000: loss 2.19\n",
"...\n",
"epoch=2, batch=12000: loss 1.27\n",
"Finished Training\n",
"```\n",
"\n",
"Environments can be registered to a workspace with `env.register(ws)`, allowing them to be easily shared, reused, and versioned. Environments make it easy to reproduce previous results and to collaborate with your team.\n",
"\n",
"Azure Machine Learning also maintains a collection of curated environments. These environments cover common ML scenarios and are backed by cached Docker images. Cached Docker images make the first remote run faster.\n",
"\n",
"In short, using registered environments can save you time! More details can be found on the [environments documentation](./how-to-use-environments.md)\n",
"\n",
"## Log training metrics\n",
"\n",
"Now that you have a model training in Azure Machine Learning, start tracking some performance metrics.\n",
"The current training script prints metrics to the terminal. Azure Machine Learning provides a\n",
"mechanism for logging metrics with more functionality. By adding a few lines of code, you gain the ability to visualize metrics in the studio and to compare metrics between multiple runs.\n",
"\n",
"### Machine learning code updates\n",
"\n",
"In the `code/pytorch-cifar10-train-with-logging` directory you will notice the [train.py](code/pytorch-cifar10-train-with-logging/train.py) script has been modified with two additional lines that will log the loss to the Azure Machine Learning Studio:\n",
"\n",
"```python\n",
"# in train.py\n",
"run = Run.get_context()\n",
"...\n",
"run.log('loss', loss)\n",
"```\n",
"\n",
"Metrics in Azure Machine Learning are:\n",
"\n",
"- Organized by experiment and run so it's easy to keep track of and\n",
"compare metrics.\n",
"- Equipped with a UI so we can visualize training performance in the studio or in the notebook widget.\n",
"- **Designed to scale** You can submit concurrent experiments and the Azure Machine Learning cluster will scale out (up to the maximum node count of the cluster) to run the experiments in parallel."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Update the Environment for your machine learning code\n",
"\n",
"The `train.py` script just took a new dependency on `azureml.core`. Therefore, the conda dependecies file [pytorch-aml-env](configuration/pytorch-aml-env.yml) reflects this change."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Submit your machine learning code to Azure Machine Learning\n",
"Submit your code once more. This time the widget includes the metrics where you can now see live updates on the model training loss!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remote run",
"batchai",
"configure run",
"use notebook widget",
"get metrics"
]
},
"outputs": [],
"source": [
"from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig\n",
"from azureml.widgets import RunDetails\n",
"\n",
"ws = Workspace.from_config()\n",
"experiment = Experiment(workspace=ws, name='day1-experiment-train')\n",
"config = ScriptRunConfig(source_directory='code/pytorch-cifar10-train-with-logging', script='train.py', compute_target='cpu-cluster')\n",
"\n",
"env = Environment.from_conda_specification(name='pytorch-aml-env', file_path='configuration/pytorch-aml-env.yml')\n",
"config.run_config.environment = env\n",
"\n",
"run = experiment.submit(config)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Next steps\n",
"\n",
"In this session, you upgraded from a basic \"Hello world!\" script to a more realistic\n",
"training script that required a specific Python environment to run. You saw how\n",
"to take a local Conda environment to the cloud with Azure Machine Learning Environments. Finally, you\n",
"saw how in a few lines of code you can log metrics to Azure Machine Learning.\n",
"\n",
"In the next session, you'll see how to work with data in Azure Machine Learning by uploading the CIFAR10\n",
"dataset to Azure.\n",
"\n",
"[Tutorial: Bring your own data](day1-part4-data.ipynb)\n"
]
}
],
"metadata": {
"authors": [
{
"name": "samkemp"
}
],
"celltoolbar": "Edit Metadata",
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
},
"notice": "Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License."
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,7 @@
name: day1-part3-train-model
dependencies:
- pip:
- azureml-sdk
- azureml-widgets
- pytorch
- torchvision

View File

@@ -0,0 +1,297 @@
{
"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/tutorials/get-started-day1/day1-part4-data.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Tutorial: Bring your own data (Part 4 of 4)\n",
"\n",
"---\n",
"## Introduction\n",
"\n",
"In the previous [Tutorial: Train a model in the cloud](day1-part3-train-model.ipynb) article, the CIFAR10 data was downloaded using the inbuilt `torchvision.datasets.CIFAR10` method in the PyTorch API. However, in many cases you are going to want to use your own data in a remote training run. This article focuses on the workflow you can leverage such that you can work with your own data in Azure Machine Learning. \n",
"\n",
"By the end of this tutorial you would have a better understanding of:\n",
"\n",
"- How to upload your data to Azure\n",
"- Best practices for working with cloud data in Azure Machine Learning\n",
"- Working with command-line arguments\n",
"\n",
"This notebook follows the steps provided on the [Python (day 1) - bring your own data documentation page](https://aka.ms/day1aml).\n",
"\n",
"## Prerequisites\n",
"\n",
"- You have completed:\n",
" - Setup on your [Azure Machine Learning Compute Cluster](day1-part1-setup.ipynb)\n",
" - [Tutorial: Hello World](day1-part2-hello-world.ipynb)\n",
" - [Tutorial: Train a model in the cloud](day1-part3-train-model.ipynb)\n",
"- Familiarity with Python and Machine Learning concepts\n",
"- If you are using a compute instance in Azure Machine Learning to run this notebook series, you are all set. Otherwise, please follow the [Configure a development environment for Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/how-to-configure-environment)\n",
"\n",
"---\n",
"\n",
"## Your machine learning code\n",
"\n",
"By now you have your training script running in Azure Machine Learning, and can monitor the model performance. Let's _parametrize_ the training script by introducing\n",
"arguments. Using arguments will allow you to easily compare different hyperparmeters.\n",
"\n",
"Presently our training script is set to download the CIFAR10 dataset on each run. The python code in [code/pytorch-cifar10-your-data/train.py](code/pytorch-cifar10-your-data/train.py) now uses **`argparse` to parametize the script.**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Understanding your machine learning code changes\n",
"\n",
"The code used in `train.py` has leveraged the `argparse` library to set up the `data_path`, `learning_rate`, and `momentum`.\n",
"\n",
"```python\n",
"# .... other code\n",
"parser = argparse.ArgumentParser()\n",
"parser.add_argument('--data_path', type=str, help='Path to the training data')\n",
"parser.add_argument('--learning_rate', type=float, default=0.001, help='Learning rate for SGD')\n",
"parser.add_argument('--momentum', type=float, default=0.9, help='Momentum for SGD')\n",
"args = parser.parse_args()\n",
"# ... other code\n",
"```\n",
"\n",
"Also the `train.py` script was adapted to update the optimizer to use the user-defined parameters:\n",
"\n",
"```python\n",
"optimizer = optim.SGD(\n",
" net.parameters(),\n",
" lr=args.learning_rate, # get learning rate from command-line argument\n",
" momentum=args.momentum, # get momentum from command-line argument\n",
")\n",
"```\n",
"\n",
"## Test your machine learning code locally\n",
"\n",
"To run the modified training script locally, run the python command below.\n",
"\n",
"You avoid having to download the CIFAR10 dataset by passing in a local path to the\n",
"data. Also you can experiment with different values for _learning rate_ and\n",
"_momentum_ hyperparameters without having to hard-code them in the training script.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!python code/pytorch-cifar10-your-data/train.py --data_path ./data --learning_rate 0.003 --momentum 0.92"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Upload your data to Azure\n",
"\n",
"In order to run this script in Azure Machine Learning, you need to make your training data available in Azure. Your Azure Machine Learning workspace comes equipped with a _default_ **Datastore** - an Azure Blob storage account - that you can use to store your training data.\n",
"\n",
"> <span style=\"color:purple; font-weight:bold\">! NOTE <br>\n",
"> Azure Machine Learning allows you to connect other cloud-based datastores that store your data. For more details, see [datastores documentation](./concept-data.md).</span>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"ws = Workspace.from_config()\n",
"datastore = ws.get_default_datastore()\n",
"datastore.upload(src_dir='./data', target_path='datasets/cifar10', overwrite=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `target_path` specifies the path on the datastore where the CIFAR10 data will be uploaded.\n",
"\n",
"## Submit your machine learning code to Azure Machine Learning\n",
"\n",
"As you have done previously, create a new Python control script:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remote run",
"batchai",
"configure run",
"use notebook widget",
"get metrics",
"use datastore"
]
},
"outputs": [],
"source": [
"from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig, Dataset\n",
"from azureml.widgets import RunDetails\n",
"\n",
"ws = Workspace.from_config()\n",
"\n",
"datastore = ws.get_default_datastore()\n",
"dataset = Dataset.File.from_files(path=(datastore, 'datasets/cifar10'))\n",
"\n",
"experiment = Experiment(workspace=ws, name='day1-experiment-data')\n",
"\n",
"config = ScriptRunConfig(source_directory='./code/pytorch-cifar10-your-data',\n",
" script='train.py',\n",
" compute_target='cpu-cluster',\n",
" arguments=[\n",
" '--data_path', dataset.as_named_input('input').as_mount(),\n",
" '--learning_rate', 0.003,\n",
" '--momentum', 0.92])\n",
"\n",
"# set up pytorch environment\n",
"env = Environment.from_conda_specification(name='pytorch-aml-env',file_path='configuration/pytorch-aml-env.yml')\n",
"config.run_config.environment = env\n",
"\n",
"run = experiment.submit(config)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Understand the control code\n",
"\n",
"The above control code has the following additional code compared to the control code written in [previous tutorial](03-train-model.ipynb)\n",
"\n",
"**`dataset = Dataset.File.from_files(path=(datastore, 'datasets/cifar10'))`**: A Dataset is used to reference the data you uploaded to the Azure Blob Store. Datasets are an abstraction layer on top of your data that are designed to improve reliability and trustworthiness.\n",
"\n",
"\n",
"**`config = ScriptRunConfig(...)`**: We modified the `ScriptRunConfig` to include a list of arguments that will be passed into `train.py`. We also specified `dataset.as_named_input('input').as_mount()`, which means the directory specified will be _mounted_ to the compute target.\n",
"\n",
"## Inspect the 70_driver_log log file\n",
"\n",
"In the navigate to the 70_driver_log.txt file - you should see the following output:\n",
"\n",
"```\n",
"Processing 'input'.\n",
"Processing dataset FileDataset\n",
"{\n",
" \"source\": [\n",
" \"('workspaceblobstore', 'datasets/cifar10')\"\n",
" ],\n",
" \"definition\": [\n",
" \"GetDatastoreFiles\"\n",
" ],\n",
" \"registration\": {\n",
" \"id\": \"XXXXX\",\n",
" \"name\": null,\n",
" \"version\": null,\n",
" \"workspace\": \"Workspace.create(name='XXXX', subscription_id='XXXX', resource_group='X')\"\n",
" }\n",
"}\n",
"Mounting input to /tmp/tmp9kituvp3.\n",
"Mounted input to /tmp/tmp9kituvp3 as folder.\n",
"Exit __enter__ of DatasetContextManager\n",
"Entering Run History Context Manager.\n",
"Current directory: /mnt/batch/tasks/shared/LS_root/jobs/dsvm-aml/azureml/tutorial-session-3_1600171983_763c5381/mounts/workspaceblobstore/azureml/tutorial-session-3_1600171983_763c5381\n",
"Preparing to call script [ train.py ] with arguments: ['--data_path', '$input', '--learning_rate', '0.003', '--momentum', '0.92']\n",
"After variable expansion, calling script [ train.py ] with arguments: ['--data_path', '/tmp/tmp9kituvp3', '--learning_rate', '0.003', '--momentum', '0.92']\n",
"\n",
"Script type = None\n",
"===== DATA =====\n",
"DATA PATH: /tmp/tmp9kituvp3\n",
"LIST FILES IN DATA PATH...\n",
"['cifar-10-batches-py', 'cifar-10-python.tar.gz']\n",
"```\n",
"\n",
"Notice:\n",
"\n",
"1. Azure Machine Learning has mounted the blob store to the compute cluster automatically for you.\n",
"2. The ``dataset.as_named_input('input').as_mount()`` used in the control script resolves to the mount point\n",
"3. In the machine learning code we include a line to list the directorys under the data directory - you can see the list above.\n",
"\n",
"## Clean up resources\n",
"\n",
"The compute cluster will scale down to zero after 40minutes of idle time. When the compute is idle you will not be charged. If you want to delete the cluster use:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"ct = ws.compute_targets['cpu-cluster']\n",
"ct.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you're not going to use what you've created here, delete the resources you just created with this quickstart so you don't incur any charges for storage. In the Azure portal, select and delete your resource group.\n",
"\n",
"## Next Steps\n",
"\n",
"To learn more about the capabilities of Azure Machine Learning please refer to the following documentation:\n",
"\n",
"* [Azure Machine Learning Pipelines](https://docs.microsoft.com/en-us/azure/machine-learning/concept-ml-pipelines#building-pipelines-with-the-python-sdk)\n",
"* [Deploy models for real-time scoring](https://docs.microsoft.com/en-us/azure/machine-learning/tutorial-deploy-models-with-aml)\n",
"* [Hyper parameter tuning with Azure Machine Learning](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters)\n",
"* [Prep your code for production](https://docs.microsoft.com/azure/machine-learning/tutorial-convert-ml-experiment-to-production)"
]
}
],
"metadata": {
"authors": [
{
"name": "samkemp"
}
],
"celltoolbar": "Edit Metadata",
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
},
"notice": "Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License."
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,7 @@
name: day1-part4-data
dependencies:
- pip:
- azureml-sdk
- azureml-widgets
- pytorch
- torchvision