mirror of
https://github.com/Azure/MachineLearningNotebooks.git
synced 2025-12-23 20:00:06 -05:00
tutorial update
This commit is contained in:
@@ -15,7 +15,7 @@
|
||||
"source": [
|
||||
"# Tutorial #1: Train an image classification model with Azure Machine Learning\n",
|
||||
"\n",
|
||||
"In this tutorial, you train a machine learning model both locally and on remote compute resources. You'll use the training and deployment workflow for Azure Machine Learning service (preview) in a Python Jupyter notebook. You can then use the notebook as a template to train your own machine learning model with your own data. This tutorial is **part one of a two-part tutorial series**. \n",
|
||||
"In this tutorial, you train a machine learning model on remote compute resources. You'll use the training and deployment workflow for Azure Machine Learning service (preview) in a Python Jupyter notebook. You can then use the notebook as a template to train your own machine learning model with your own data. This tutorial is **part one of a two-part tutorial series**. \n",
|
||||
"\n",
|
||||
"This tutorial trains a simple logistic regression using the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset and [scikit-learn](http://scikit-learn.org) with Azure Machine Learning. MNIST is a popular dataset consisting of 70,000 grayscale images. Each image is a handwritten digit of 28x28 pixels, representing a number from 0 to 9. The goal is to create a multi-class classifier to identify the digit a given image represents. \n",
|
||||
"\n",
|
||||
@@ -31,9 +31,7 @@
|
||||
"\n",
|
||||
"## Prerequisites\n",
|
||||
"\n",
|
||||
"Use [these instructions](https://aka.ms/aml-how-to-configure-environment) to: \n",
|
||||
"* Create a workspace and its configuration file (**config.json**) \n",
|
||||
"* Save your **config.json** to the same folder as this notebook"
|
||||
"See prerequisites in the [Azure Machine Learning documentation](https://docs.microsoft.com/azure/machine-learning/service/tutorial-train-models-with-aml#prerequisites)."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -128,10 +126,10 @@
|
||||
"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",
|
||||
"### Create or Attach existing compute resource\n",
|
||||
"By using Azure Machine Learning Compute, a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. Examples include VMs with GPU support. In this tutorial, you create Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\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."
|
||||
"**Creation of compute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace the code will skip the creation process."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -206,12 +204,13 @@
|
||||
"source": [
|
||||
"import urllib.request\n",
|
||||
"\n",
|
||||
"os.makedirs('./data', exist_ok = True)\n",
|
||||
"data_folder = os.path.join(os.getcwd(), 'data')\n",
|
||||
"os.makedirs(data_folder, exist_ok = True)\n",
|
||||
"\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz', filename='./data/train-images.gz')\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz', filename='./data/train-labels.gz')\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', filename='./data/test-images.gz')\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', filename='./data/test-labels.gz')"
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz', filename=os.path.join(data_folder, 'train-images.gz'))\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz', filename=os.path.join(data_folder, 'train-labels.gz'))\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', filename=os.path.join(data_folder, 'test-images.gz'))\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', filename=os.path.join(data_folder, 'test-labels.gz'))"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -233,11 +232,10 @@
|
||||
"from utils import load_data\n",
|
||||
"\n",
|
||||
"# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster.\n",
|
||||
"X_train = load_data('./data/train-images.gz', False) / 255.0\n",
|
||||
"y_train = load_data('./data/train-labels.gz', True).reshape(-1)\n",
|
||||
"\n",
|
||||
"X_test = load_data('./data/test-images.gz', False) / 255.0\n",
|
||||
"y_test = load_data('./data/test-labels.gz', True).reshape(-1)\n",
|
||||
"X_train = load_data(os.path.join(data_folder, 'train-images.gz'), False) / 255.0\n",
|
||||
"X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0\n",
|
||||
"y_train = load_data(os.path.join(data_folder, 'train-labels.gz'), True).reshape(-1)\n",
|
||||
"y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)\n",
|
||||
"\n",
|
||||
"# now let's show some randomly chosen images from the traininng set.\n",
|
||||
"count = 0\n",
|
||||
@@ -279,62 +277,15 @@
|
||||
"ds = ws.get_default_datastore()\n",
|
||||
"print(ds.datastore_type, ds.account_name, ds.container_name)\n",
|
||||
"\n",
|
||||
"ds.upload(src_dir='./data', target_path='mnist', overwrite=True, show_progress=True)"
|
||||
"ds.upload(src_dir=data_folder, target_path='mnist', overwrite=True, show_progress=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You now have everything you need to start training a model. \n",
|
||||
"\n",
|
||||
"## Train a local model\n",
|
||||
"\n",
|
||||
"Train a simple logistic regression model using scikit-learn locally.\n",
|
||||
"\n",
|
||||
"**Training locally can take a minute or two** depending on your computer configuration."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%time\n",
|
||||
"from sklearn.linear_model import LogisticRegression\n",
|
||||
"\n",
|
||||
"clf = LogisticRegression()\n",
|
||||
"clf.fit(X_train, y_train)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Next, make predictions using the test set and calculate the accuracy."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"y_hat = clf.predict(X_test)\n",
|
||||
"print(np.average(y_hat == y_test))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"With just a few lines of code, you have a 92% accuracy.\n",
|
||||
"\n",
|
||||
"## Train on a remote cluster\n",
|
||||
"\n",
|
||||
"Now you can expand on this simple model by building a model with a different regularization rate. This time you'll train the model on a remote resource. \n",
|
||||
"\n",
|
||||
"For this task, submit the job to the remote training cluster you set up earlier. To submit a job you:\n",
|
||||
"* Create a directory\n",
|
||||
"* Create a training script\n",
|
||||
@@ -352,7 +303,8 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"script_folder = './sklearn-mnist'\n",
|
||||
"import os\n",
|
||||
"script_folder = os.path.join(os.getcwd(), \"sklearn-mnist\")\n",
|
||||
"os.makedirs(script_folder, exist_ok=True)"
|
||||
]
|
||||
},
|
||||
@@ -362,7 +314,7 @@
|
||||
"source": [
|
||||
"### Create a training script\n",
|
||||
"\n",
|
||||
"To submit the job to the cluster, first create a training script. Run the following code to create the training script called `train.py` in the directory you just created. This training adds a regularization rate to the training algorithm, so produces a slightly different model than the local version."
|
||||
"To submit the job to the cluster, first create a training script. Run the following code to create the training script called `train.py` in the directory you just created. "
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -681,8 +633,7 @@
|
||||
"\n",
|
||||
"> * Set up your development environment\n",
|
||||
"> * Access and examine the data\n",
|
||||
"> * Train a simple logistic regression locally using the popular scikit-learn machine learning library\n",
|
||||
"> * Train multiple models on a remote cluster\n",
|
||||
"> * Train multiple models on a remote cluster using the popular scikit-learn machine learning library\n",
|
||||
"> * Review training details and register the best model\n",
|
||||
"\n",
|
||||
"You are ready to deploy this registered model using the instructions in the next part of the tutorial series:\n",
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
"> * Deploy the model to ACI\n",
|
||||
"> * Test the deployed model\n",
|
||||
"\n",
|
||||
"ACI is not ideal for production deployments, but it is great for testing and understanding the workflow. For scalable production deployments, consider using AKS.\n",
|
||||
"ACI is a great solution for testing and understanding the workflow. For scalable production deployments, consider using Azure Kubernetes Service. For more information, see [how to deploy and where](https://docs.microsoft.com/azure/machine-learning/service/how-to-deploy-and-where).\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Prerequisites\n",
|
||||
@@ -68,10 +68,12 @@
|
||||
"import os\n",
|
||||
"import urllib.request\n",
|
||||
"\n",
|
||||
"os.makedirs('./data', exist_ok=True)\n",
|
||||
"data_folder = os.path.join(os.getcwd(), 'data')\n",
|
||||
"os.makedirs(data_folder, exist_ok = True)\n",
|
||||
"\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', filename='./data/test-images.gz')\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', filename='./data/test-labels.gz')"
|
||||
"\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', filename=os.path.join(data_folder, 'test-images.gz'))\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', filename=os.path.join(data_folder, 'test-labels.gz'))"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -101,7 +103,7 @@
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
" \n",
|
||||
"import azureml\n",
|
||||
"import azureml.core\n",
|
||||
"\n",
|
||||
"# display the core SDK version number\n",
|
||||
"print(\"Azure ML SDK Version: \", azureml.core.VERSION)"
|
||||
@@ -127,11 +129,18 @@
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from azureml.core import Workspace\n",
|
||||
"from azureml.core.model import Model\n",
|
||||
"import os \n",
|
||||
"ws = Workspace.from_config()\n",
|
||||
"model=Model(ws, 'sklearn_mnist')\n",
|
||||
"model.download(target_dir='.', exist_ok=True)\n",
|
||||
"\n",
|
||||
"model.download(target_dir=os.getcwd(), exist_ok=True)\n",
|
||||
"\n",
|
||||
"# verify the downloaded model file\n",
|
||||
"os.stat('./sklearn_mnist_model.pkl')"
|
||||
"file_path = os.path.join(os.getcwd(), \"sklearn_mnist_model.pkl\")\n",
|
||||
"\n",
|
||||
"os.stat(file_path)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -157,10 +166,12 @@
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from utils import load_data\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"data_folder = os.path.join(os.getcwd(), 'data')\n",
|
||||
"# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the neural network converge faster\n",
|
||||
"X_test = load_data('./data/test-images.gz', False) / 255.0\n",
|
||||
"y_test = load_data('./data/test-labels.gz', True).reshape(-1)"
|
||||
"X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0\n",
|
||||
"y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -181,7 +192,7 @@
|
||||
"import pickle\n",
|
||||
"from sklearn.externals import joblib\n",
|
||||
"\n",
|
||||
"clf = joblib.load('./sklearn_mnist_model.pkl')\n",
|
||||
"clf = joblib.load( os.path.join(os.getcwd(), 'sklearn_mnist_model.pkl'))\n",
|
||||
"y_hat = clf.predict(X_test)"
|
||||
]
|
||||
},
|
||||
@@ -220,7 +231,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# normalize the diagnal cells so that they don't overpower the rest of the cells when visualized\n",
|
||||
"# normalize the diagonal cells so that they don't overpower the rest of the cells when visualized\n",
|
||||
"row_sums = conf_mx.sum(axis=1, keepdims=True)\n",
|
||||
"norm_conf_mx = conf_mx / row_sums\n",
|
||||
"np.fill_diagonal(norm_conf_mx, 0)\n",
|
||||
@@ -282,7 +293,7 @@
|
||||
"\n",
|
||||
"def init():\n",
|
||||
" global model\n",
|
||||
" # retreive the path to the model file using the model name\n",
|
||||
" # retrieve the path to the model file using the model name\n",
|
||||
" model_path = Model.get_model_path('sklearn_mnist')\n",
|
||||
" model = joblib.load(model_path)\n",
|
||||
"\n",
|
||||
|
||||
@@ -13,14 +13,16 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Tutorial (part 1): Prepare data for regression modeling"
|
||||
"# Tutorial: Prepare data for regression modeling"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"In this tutorial, you learn how to prep data for regression modeling using the Azure Machine Learning Data Prep SDK. Perform various transformations to filter and combine two different NYC Taxi data sets. The end goal of this tutorial set is to predict the cost of a taxi trip by training a model on data features including pickup hour, day of week, number of passengers, and coordinates. This tutorial is part one of a two-part tutorial series.\n",
|
||||
"In this tutorial, you learn how to prepare data for regression modeling by using the Azure Machine Learning Data Prep SDK. You run various transformations to filter and combine two different NYC taxi data sets.\n",
|
||||
"\n",
|
||||
"This tutorial is **part one of a two-part tutorial series**. After you complete the tutorial series, you can predict the cost of a taxi trip by training a model on data features. These features include the pickup day and time, the number of passengers, and the pickup location.\n",
|
||||
"\n",
|
||||
"In this tutorial, you:\n",
|
||||
"\n",
|
||||
@@ -29,17 +31,39 @@
|
||||
"> * Load two datasets with different field names\n",
|
||||
"> * Cleanse data to remove anomalies\n",
|
||||
"> * Transform data using intelligent transforms to create new features\n",
|
||||
"> * Save your dataflow object to use in a regression model\n",
|
||||
"\n",
|
||||
"You can prepare your data in Python using the [Azure Machine Learning Data Prep SDK](https://aka.ms/data-prep-sdk)."
|
||||
"> * Save your dataflow object to use in a regression model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Import packages\n",
|
||||
"Begin by importing the SDK."
|
||||
"## Prerequisites\n",
|
||||
"\n",
|
||||
"To run the notebook you will need:\n",
|
||||
"\n",
|
||||
"* A Python 3.6 notebook server with the following installed:\n",
|
||||
" * The Azure Machine Learning Data Prep SDK for Python\n",
|
||||
"* The tutorial notebook\n",
|
||||
"\n",
|
||||
"Navigate back to the [tutorial page](https://docs.microsoft.com/azure/machine-learning/service/tutorial-data-prep) for specific environment setup instructions.\n",
|
||||
"\n",
|
||||
"## <a name=\"start\"></a>Set up your development environment\n",
|
||||
"\n",
|
||||
"All the setup for your development work can be accomplished in a Python notebook. Setup includes the following actions:\n",
|
||||
"\n",
|
||||
"* Install the SDK\n",
|
||||
"* Import Python packages\n",
|
||||
"\n",
|
||||
"### Install and import packages\n",
|
||||
"\n",
|
||||
"Use the following to install necessary packages if you don't already have them.\n",
|
||||
"\n",
|
||||
"```shell\n",
|
||||
"pip install azureml-dataprep\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"Import the SDK."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -65,17 +89,25 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from IPython.display import display\n",
|
||||
"dataset_root = \"https://dprepdata.blob.core.windows.net/demo\"\n",
|
||||
"\n",
|
||||
"green_path = \"/\".join([dataset_root, \"green-small/*\"])\n",
|
||||
"yellow_path = \"/\".join([dataset_root, \"yellow-small/*\"])\n",
|
||||
"\n",
|
||||
"green_df = dprep.read_csv(path=green_path, header=dprep.PromoteHeadersMode.GROUPED)\n",
|
||||
"# auto_read_file will automatically identify and parse the file type, and is useful if you don't know the file type\n",
|
||||
"yellow_df = dprep.auto_read_file(path=yellow_path)\n",
|
||||
"green_df_raw = dprep.read_csv(path=green_path, header=dprep.PromoteHeadersMode.GROUPED)\n",
|
||||
"# auto_read_file automatically identifies and parses the file type, which is useful when you don't know the file type.\n",
|
||||
"yellow_df_raw = dprep.auto_read_file(path=yellow_path)\n",
|
||||
"\n",
|
||||
"green_df.head(5)\n",
|
||||
"yellow_df.head(5)"
|
||||
"display(green_df_raw.head(5))\n",
|
||||
"display(yellow_df_raw.head(5))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"A `Dataflow` object is similar to a dataframe, and represents a series of lazily-evaluated, immutable operations on data. Operations can be added by invoking the different transformation and filtering methods available. The result of adding an operation to a `Dataflow` is always a new `Dataflow` object."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -89,7 +121,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now you populate some variables with shortcut transforms that will apply to all dataflows. The variable `drop_if_all_null` will be used to delete records where all fields are null. The variable `useful_columns` holds an array of column descriptions that are retained in each dataflow."
|
||||
"Now you populate some variables with shortcut transforms to apply to all dataflows. The `drop_if_all_null` variable is used to delete records where all fields are null. The `useful_columns` variable holds an array of column descriptions that are kept in each dataflow."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -110,7 +142,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You first work with the green taxi data and get it into a valid shape that can be combined with the yellow taxi data. Create a temporary dataflow `tmp_df`, and call the `replace_na()`, `drop_nulls()`, and `keep_columns()` functions using the shortcut transform variables you created. Additionally, rename all the columns in the dataframe to match the names in `useful_columns`."
|
||||
"You first work with the green taxi data to get it into a valid shape that can be combined with the yellow taxi data. Call the `replace_na()`, `drop_nulls()`, and `keep_columns()` functions by using the shortcut transform variables you created. Additionally, rename all the columns in the dataframe to match the names in the `useful_columns` variable."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -119,7 +151,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = (green_df\n",
|
||||
"green_df = (green_df_raw\n",
|
||||
" .replace_na(columns=all_columns)\n",
|
||||
" .drop_nulls(*drop_if_all_null)\n",
|
||||
" .rename_columns(column_pairs={\n",
|
||||
@@ -138,14 +170,14 @@
|
||||
" \"Trip_distance\": \"distance\"\n",
|
||||
" })\n",
|
||||
" .keep_columns(columns=useful_columns))\n",
|
||||
"tmp_df.head(5)"
|
||||
"green_df.head(5)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Overwrite the `green_df` variable with the transforms performed on `tmp_df` in the previous step."
|
||||
"Run the same transformation steps on the yellow taxi data. These functions ensure that null data is removed from the data set, which will help increase machine learning model accuracy."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -154,23 +186,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"green_df = tmp_df"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Perform the same transformation steps to the yellow taxi data."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = (yellow_df\n",
|
||||
"yellow_df = (yellow_df_raw\n",
|
||||
" .replace_na(columns=all_columns)\n",
|
||||
" .drop_nulls(*drop_if_all_null)\n",
|
||||
" .rename_columns(column_pairs={\n",
|
||||
@@ -195,14 +211,14 @@
|
||||
" \"trip_distance\": \"distance\"\n",
|
||||
" })\n",
|
||||
" .keep_columns(columns=useful_columns))\n",
|
||||
"tmp_df.head(5)"
|
||||
"yellow_df.head(5)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Again, overwrite `yellow_df` with `tmp_df`, and then call the `append_rows()` function on the green taxi data to append the yellow taxi data, creating a new combined dataframe."
|
||||
"Call the `append_rows()` function on the green taxi data to append the yellow taxi data. A new combined dataframe is created."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -211,7 +227,6 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"yellow_df = tmp_df\n",
|
||||
"combined_df = green_df.append_rows([yellow_df])"
|
||||
]
|
||||
},
|
||||
@@ -226,7 +241,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Examine the pickup and drop-off coordinates summary statistics to see how the data is distributed. First define a `TypeConverter` object to change the lat/long fields to decimal type. Next, call the `keep_columns()` function to restrict output to only the lat/long fields, and then call `get_profile()`."
|
||||
"Examine the pickup and drop-off coordinates summary statistics to see how the data is distributed. First, define a `TypeConverter` object to change the latitude and longitude fields to decimal type. Next, call the `keep_columns()` function to restrict output to only the latitude and longitude fields, and then call the `get_profile()` function. These function calls create a condensed view of the dataflow to just show the lat/long fields, which makes it easier to evaluate missing or out-of-scope coordinates."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -243,7 +258,7 @@
|
||||
" \"dropoff_latitude\": decimal_type\n",
|
||||
"})\n",
|
||||
"combined_df.keep_columns(columns=[\n",
|
||||
" \"pickup_longitude\", \"pickup_latitude\", \n",
|
||||
" \"pickup_longitude\", \"pickup_latitude\",\n",
|
||||
" \"dropoff_longitude\", \"dropoff_latitude\"\n",
|
||||
"]).get_profile()"
|
||||
]
|
||||
@@ -252,7 +267,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"From the summary statistics output, you see that there are coordinates that are missing, and coordinates that are not in New York City. Filter out coordinates not in the city border by chaining column filter commands within the `filter()` function, and defining minimum and maximum bounds for each field. Then call `get_profile()` again to verify the transformation."
|
||||
"From the summary statistics output, you see there are missing coordinates and coordinates that aren't in New York City (this is determined from subjective analysis). Filter out coordinates for locations that are outside the city border. Chain the column filter commands within the `filter()` function and define the minimum and maximum bounds for each field. Then call the `get_profile()` function again to verify the transformation."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -261,11 +276,11 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = (combined_df\n",
|
||||
"latlong_filtered_df = (combined_df\n",
|
||||
" .drop_nulls(\n",
|
||||
" columns=[\"pickup_longitude\", \"pickup_latitude\", \"dropoff_longitude\", \"dropoff_latitude\"],\n",
|
||||
" column_relationship=dprep.ColumnRelationship(dprep.ColumnRelationship.ANY)\n",
|
||||
" ) \n",
|
||||
" )\n",
|
||||
" .filter(dprep.f_and(\n",
|
||||
" dprep.col(\"pickup_longitude\") <= -73.72,\n",
|
||||
" dprep.col(\"pickup_longitude\") >= -74.09,\n",
|
||||
@@ -276,28 +291,12 @@
|
||||
" dprep.col(\"dropoff_latitude\") <= 40.88,\n",
|
||||
" dprep.col(\"dropoff_latitude\") >= 40.53\n",
|
||||
" )))\n",
|
||||
"tmp_df.keep_columns(columns=[\n",
|
||||
" \"pickup_longitude\", \"pickup_latitude\", \n",
|
||||
"latlong_filtered_df.keep_columns(columns=[\n",
|
||||
" \"pickup_longitude\", \"pickup_latitude\",\n",
|
||||
" \"dropoff_longitude\", \"dropoff_latitude\"\n",
|
||||
"]).get_profile()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Overwrite `combined_df` with the transformations you made to `tmp_df`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"combined_df = tmp_df"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
@@ -309,7 +308,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Look at the data profile for the `store_forward` column."
|
||||
"Look at the data profile for the `store_forward` column. This field is a boolean flag that is `Y` when the taxi did not have a connection to the server after the trip, and thus had to store the trip data in memory, and later forward it to the server when connected."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -318,14 +317,14 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"combined_df.keep_columns(columns='store_forward').get_profile()"
|
||||
"latlong_filtered_df.keep_columns(columns='store_forward').get_profile()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"From the data profile output of `store_forward`, you see that the data is inconsistent and there are missing/null values. Replace these values using the `replace()` and `fill_nulls()` functions, and in both cases change to the string \"N\"."
|
||||
"Notice that the data profile output in the `store_forward` column shows that the data is inconsistent and there are missing or null values. Use the `replace()` and `fill_nulls()` functions to replace these values with the string \"N\":"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -334,14 +333,14 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"combined_df = combined_df.replace(columns=\"store_forward\", find=\"0\", replace_with=\"N\").fill_nulls(\"store_forward\", \"N\")"
|
||||
"replaced_stfor_vals_df = latlong_filtered_df.replace(columns=\"store_forward\", find=\"0\", replace_with=\"N\").fill_nulls(\"store_forward\", \"N\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Execute another `replace` function, this time on the `distance` field. This reformats distance values that are incorrectly labeled as `.00`, and fills any nulls with zeros. Convert the `distance` field to numerical format."
|
||||
"Execute the `replace` function on the `distance` field. The function reformats distance values that are incorrectly labeled as `.00`, and fills any nulls with zeros. Convert the `distance` field to numerical format. These incorrect data points are likely anomolies in the data collection system on the taxi cabs."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -350,15 +349,15 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"combined_df = combined_df.replace(columns=\"distance\", find=\".00\", replace_with=0).fill_nulls(\"distance\", 0)\n",
|
||||
"combined_df = combined_df.to_number([\"distance\"])"
|
||||
"replaced_distance_vals_df = replaced_stfor_vals_df.replace(columns=\"distance\", find=\".00\", replace_with=0).fill_nulls(\"distance\", 0)\n",
|
||||
"replaced_distance_vals_df = replaced_distance_vals_df.to_number([\"distance\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Split the pick up and drop off datetimes into respective date and time columns. Use `split_column_by_example()` to perform the split. In this case, the optional `example` parameter of `split_column_by_example()` is omitted. Therefore the function will automatically determine where to split based on the data."
|
||||
"Split the pickup and dropoff datetime values into the respective date and time columns. Use the `split_column_by_example()` function to make the split. In this case, the optional `example` parameter of the `split_column_by_example()` function is omitted. Therefore, the function automatically determines where to split based on the data."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -367,10 +366,10 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = (combined_df\n",
|
||||
"time_split_df = (replaced_distance_vals_df\n",
|
||||
" .split_column_by_example(source_column=\"pickup_datetime\")\n",
|
||||
" .split_column_by_example(source_column=\"dropoff_datetime\"))\n",
|
||||
"tmp_df.head(5)"
|
||||
"time_split_df.head(5)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -386,21 +385,21 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df_renamed = (tmp_df\n",
|
||||
"renamed_col_df = (time_split_df\n",
|
||||
" .rename_columns(column_pairs={\n",
|
||||
" \"pickup_datetime_1\": \"pickup_date\",\n",
|
||||
" \"pickup_datetime_2\": \"pickup_time\",\n",
|
||||
" \"dropoff_datetime_1\": \"dropoff_date\",\n",
|
||||
" \"dropoff_datetime_2\": \"dropoff_time\"\n",
|
||||
" }))\n",
|
||||
"tmp_df_renamed.head(5)"
|
||||
"renamed_col_df.head(5)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Overwrite `combined_df` with the executed transformations, and then call `get_profile()` to see full summary statistics after all transformations."
|
||||
"Call the `get_profile()` function to see the full summary statistics after all cleansing steps."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -409,8 +408,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"combined_df = tmp_df_renamed\n",
|
||||
"combined_df.get_profile()"
|
||||
"renamed_col_df.get_profile()"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -424,9 +422,11 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Split the pickup and drop-off date further into day of week, day of month, and month. To get day of week, use the `derive_column_by_example()` function. This function takes as a parameter an array of example objects that define the input data, and the desired output. The function then automatically determines your desired transformation. For pickup and drop-off time columns, split into hour, minute, and second using the `split_column_by_example()` function with no example parameter.\n",
|
||||
"Split the pickup and dropoff date further into the day of the week, day of the month, and month values. To get the day of the week value, use the `derive_column_by_example()` function. The function takes an array parameter of example objects that define the input data, and the preferred output. The function automatically determines your preferred transformation. For the pickup and dropoff time columns, split the time into the hour, minute, and second by using the `split_column_by_example()` function with no example parameter.\n",
|
||||
"\n",
|
||||
"Once you have generated these new features, delete the original fields in favor of the newly generated features using `drop_columns()`. Rename all remaining fields to accurate descriptions."
|
||||
"After you generate the new features, use the `drop_columns()` function to delete the original fields as the newly generated features are preferred. Rename the rest of the fields to use meaningful descriptions.\n",
|
||||
"\n",
|
||||
"Transforming the data in this way to create new time-based features will improve machine learning model accuracy. For example, generating a new feature for the weekday will help establish a relationship between the day of the week and the taxi fare price, which is often more expensive on certain days of the week due to high demand."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -435,10 +435,10 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = (combined_df\n",
|
||||
"transformed_features_df = (renamed_col_df\n",
|
||||
" .derive_column_by_example(\n",
|
||||
" source_columns=\"pickup_date\", \n",
|
||||
" new_column_name=\"pickup_weekday\", \n",
|
||||
" source_columns=\"pickup_date\",\n",
|
||||
" new_column_name=\"pickup_weekday\",\n",
|
||||
" example_data=[(\"2009-01-04\", \"Sunday\"), (\"2013-08-22\", \"Thursday\")]\n",
|
||||
" )\n",
|
||||
" .derive_column_by_example(\n",
|
||||
@@ -446,17 +446,17 @@
|
||||
" new_column_name=\"dropoff_weekday\",\n",
|
||||
" example_data=[(\"2013-08-22\", \"Thursday\"), (\"2013-11-03\", \"Sunday\")]\n",
|
||||
" )\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" .split_column_by_example(source_column=\"pickup_time\")\n",
|
||||
" .split_column_by_example(source_column=\"dropoff_time\")\n",
|
||||
" # the following two split_column_by_example calls reference the generated column names from the above two calls\n",
|
||||
" # The following two calls to split_column_by_example reference the column names generated from the previous two calls.\n",
|
||||
" .split_column_by_example(source_column=\"pickup_time_1\")\n",
|
||||
" .split_column_by_example(source_column=\"dropoff_time_1\")\n",
|
||||
" .drop_columns(columns=[\n",
|
||||
" \"pickup_date\", \"pickup_time\", \"dropoff_date\", \"dropoff_time\", \n",
|
||||
" \"pickup_date\", \"pickup_time\", \"dropoff_date\", \"dropoff_time\",\n",
|
||||
" \"pickup_date_1\", \"dropoff_date_1\", \"pickup_time_1\", \"dropoff_time_1\"\n",
|
||||
" ])\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" .rename_columns(column_pairs={\n",
|
||||
" \"pickup_date_2\": \"pickup_month\",\n",
|
||||
" \"pickup_date_3\": \"pickup_monthday\",\n",
|
||||
@@ -470,14 +470,14 @@
|
||||
" \"dropoff_time_2\": \"dropoff_second\"\n",
|
||||
" }))\n",
|
||||
"\n",
|
||||
"tmp_df.head(5)"
|
||||
"transformed_features_df.head(5)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"From the data above, you see that the pickup and drop-off date and time components produced from the derived transformations are correct. Drop the `pickup_datetime` and `dropoff_datetime` columns as they are no longer needed."
|
||||
"Notice that the data shows that the pickup and dropoff date and time components produced from the derived transformations are correct. Drop the `pickup_datetime` and `dropoff_datetime` columns because they're no longer needed (granular time features like hour, minute and second are more useful for model training)."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -486,7 +486,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = tmp_df.drop_columns(columns=[\"pickup_datetime\", \"dropoff_datetime\"])"
|
||||
"processed_df = transformed_features_df.drop_columns(columns=[\"pickup_datetime\", \"dropoff_datetime\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -502,7 +502,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"type_infer = tmp_df.builders.set_column_types()\n",
|
||||
"type_infer = processed_df.builders.set_column_types()\n",
|
||||
"type_infer.learn()\n",
|
||||
"type_infer"
|
||||
]
|
||||
@@ -511,7 +511,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The inference results look correct based on the data, now apply the type conversions to the dataflow."
|
||||
"The inference results look correct based on the data. Now apply the type conversions to the dataflow."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -520,15 +520,15 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = type_infer.to_dataflow()\n",
|
||||
"tmp_df.get_profile()"
|
||||
"type_converted_df = type_infer.to_dataflow()\n",
|
||||
"type_converted_df.get_profile()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Before packaging the dataflow, perform two final filters on the data set. To eliminate incorrect data points, filter the dataflow on records where both the `cost` and `distance` are greater than zero."
|
||||
"Before you package the dataflow, run two final filters on the data set. To eliminate incorrectly captured data points, filter the dataflow on records where both the `cost` and `distance` variable values are greater than zero. This step will significantly improve machine learning model accuracy, because data points with a zero cost or distance represent major outliers that throw off prediction accuracy."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -537,15 +537,15 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tmp_df = tmp_df.filter(dprep.col(\"distance\") > 0)\n",
|
||||
"tmp_df = tmp_df.filter(dprep.col(\"cost\") > 0)"
|
||||
"final_df = type_converted_df.filter(dprep.col(\"distance\") > 0)\n",
|
||||
"final_df = final_df.filter(dprep.col(\"cost\") > 0)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"At this point, you have a fully transformed and prepared dataflow object to use in a machine learning model. The DataPrep SDK includes object serialization functionality, which is used as follows."
|
||||
"You now have a fully transformed and prepared dataflow object to use in a machine learning model. The SDK includes object serialization functionality, which is used as shown in the following code."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -557,8 +557,7 @@
|
||||
"import os\n",
|
||||
"file_path = os.path.join(os.getcwd(), \"dflows.dprep\")\n",
|
||||
"\n",
|
||||
"dflow_prepared = tmp_df\n",
|
||||
"package = dprep.Package([dflow_prepared])\n",
|
||||
"package = dprep.Package([final_df])\n",
|
||||
"package.save(file_path)"
|
||||
]
|
||||
},
|
||||
@@ -573,7 +572,9 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Delete the file `dflows.dprep` (whether you are running locally or in Azure Notebooks) in your current directory if you do not wish to continue with part two of the tutorial. If you continue on to part two, you will need the `dflows.dprep` file in the current directory."
|
||||
"To continue with part two of the tutorial, you need the **dflows.dprep** file in the current directory.\n",
|
||||
"\n",
|
||||
"If you don't plan to continue to part two, delete the **dflows.dprep** file in your current directory. Delete this file whether you're running the execution locally or in [Azure Notebooks](https://notebooks.azure.com/)."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -11,20 +11,19 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Tutorial (part 2): Use automated machine learning to build your regression model \n",
|
||||
"# Tutorial: Use automated machine learning to build your regression model\n",
|
||||
"\n",
|
||||
"This tutorial is **part two of a two-part tutorial series**. In the previous tutorial, you [prepared the NYC taxi data for regression modeling](regression-part1-data-prep.ipynb).\n",
|
||||
"\n",
|
||||
"Now, you're ready to start building your model with Azure Machine Learning service. In this part of the tutorial, you will use the prepared data and automatically generate a regression model to predict taxi fare prices. Using the automated ML capabilities of the service, you define your machine learning goals and constraints, launch the automated machine learning process and then allow the algorithm selection and hyperparameter-tuning to happen for you. The automated ML technique iterates over many combinations of algorithms and hyperparameters until it finds the best model based on your criterion.\n",
|
||||
"Now you're ready to start building your model with Azure Machine Learning service. In this part of the tutorial, you use the prepared data and automatically generate a regression model to predict taxi fare prices. By using the automated machine learning capabilities of the service, you define your machine learning goals and constraints. You launch the automated machine learning process. Then allow the algorithm selection and hyperparameter tuning to happen for you. The automated machine learning technique iterates over many combinations of algorithms and hyperparameters until it finds the best model based on your criterion.\n",
|
||||
"\n",
|
||||
"In this tutorial, you learn how to:\n",
|
||||
"In this tutorial, you learn the following tasks:\n",
|
||||
"\n",
|
||||
"> * Setup a Python environment and import the SDK packages\n",
|
||||
"> * Set up a Python environment and import the SDK packages\n",
|
||||
"> * Configure an Azure Machine Learning service workspace\n",
|
||||
"> * Auto-train a regression model \n",
|
||||
"> * Run the model locally with custom parameters\n",
|
||||
"> * Explore the results\n",
|
||||
"> * Register the best model\n",
|
||||
"\n",
|
||||
"If you don\u00e2\u20ac\u2122t have an Azure subscription, create a [free account](https://aka.ms/AMLfree) before you begin. \n",
|
||||
"\n",
|
||||
@@ -33,17 +32,40 @@
|
||||
"\n",
|
||||
"## Prerequisites\n",
|
||||
"\n",
|
||||
"> * [Run the data preparation tutorial](regression-part1-data-prep.ipynb)\n",
|
||||
"To run the notebook you will need:\n",
|
||||
"\n",
|
||||
"> * Automated machine learning configured environment e.g. Azure notebooks, Local Python environment or Data Science Virtual Machine. [Setup](https://docs.microsoft.com/azure/machine-learning/service/samples-notebooks) automated machine learning."
|
||||
"* [Run the data preparation tutorial](regression-part1-data-prep.ipynb).\n",
|
||||
"* A Python 3.6 notebook server with the following installed:\n",
|
||||
" * The Azure Machine Learning SDK for Python with `automl` and `notebooks` extras\n",
|
||||
" * `matplotlib`\n",
|
||||
"* The tutorial notebook\n",
|
||||
"* A machine learning workspace\n",
|
||||
"* The configuration file for the workspace in the same directory as the notebook\n",
|
||||
"\n",
|
||||
"Navigate back to the [tutorial page](https://docs.microsoft.com/azure/machine-learning/service/tutorial-auto-train-models) for specific environment setup instructions.\n",
|
||||
"\n",
|
||||
"## <a name=\"start\"></a>Set up your development environment\n",
|
||||
"\n",
|
||||
"All the setup for your development work can be accomplished in a Python notebook. Setup includes the following actions:\n",
|
||||
"\n",
|
||||
"* Install the SDK\n",
|
||||
"* Import Python packages\n",
|
||||
"* Configure your workspace"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Import packages\n",
|
||||
"Import Python packages you need in this tutorial."
|
||||
"### Install and import packages\n",
|
||||
"\n",
|
||||
"If you are following the tutorial in your own Python environment, use the following to install necessary packages.\n",
|
||||
"\n",
|
||||
"```shell\n",
|
||||
"pip install azureml-sdk[automl,notebooks] matplotlib\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"Import the Python packages you need in this tutorial:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -55,7 +77,8 @@
|
||||
"import azureml.core\n",
|
||||
"import pandas as pd\n",
|
||||
"from azureml.core.workspace import Workspace\n",
|
||||
"import logging"
|
||||
"import logging\n",
|
||||
"import os"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -64,9 +87,11 @@
|
||||
"source": [
|
||||
"### Configure workspace\n",
|
||||
"\n",
|
||||
"Create a workspace object from the existing workspace. A `Workspace` is a class that accepts your Azure subscription and resource information, and creates a cloud resource to monitor and track your model runs. `Workspace.from_config()` reads the file **aml_config/config.json** and loads the details into an object named `ws`. `ws` is used throughout the rest of the code in this tutorial.\n",
|
||||
"Create a workspace object from the existing workspace. A `Workspace` is a class that accepts your Azure subscription and resource information. It also creates a cloud resource to monitor and track your model runs.\n",
|
||||
"\n",
|
||||
"Once you have a workspace object, specify a name for the experiment and create and register a local directory with the workspace. The history of all runs is recorded under the specified experiment."
|
||||
"`Workspace.from_config()` reads the file **aml_config/config.json** and loads the details into an object named `ws`. `ws` is used throughout the rest of the code in this tutorial.\n",
|
||||
"\n",
|
||||
"After you have a workspace object, specify a name for the experiment. Create and register a local directory with the workspace. The history of all runs is recorded under the specified experiment and in the [Azure portal](https://portal.azure.com)."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -81,8 +106,6 @@
|
||||
"# project folder\n",
|
||||
"project_folder = './automated-ml-regression'\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"output = {}\n",
|
||||
"output['SDK version'] = azureml.core.VERSION\n",
|
||||
"output['Subscription ID'] = ws.subscription_id\n",
|
||||
@@ -101,7 +124,7 @@
|
||||
"source": [
|
||||
"## Explore data\n",
|
||||
"\n",
|
||||
"Utilize the data flow object created in the previous tutorial. Open and execute the data flow and review the results."
|
||||
"Use the data flow object created in the previous tutorial. To summarize, part 1 of this tutorial cleaned the NYC Taxi data so it could be used in a machine learning model. Now, you use various features from the data set and allow an automated model to build relationships between the features and the price of a taxi trip. Open and run the data flow and review the results:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -123,7 +146,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You prepare the data for the experiment by adding columns to `dflow_X` to be features for our model creation. You define `dflow_y` to be our prediction value; cost.\n"
|
||||
"You prepare the data for the experiment by adding columns to `dflow_x` to be features for our model creation. You define `dflow_y` to be our prediction value, **cost**:\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -142,7 +165,7 @@
|
||||
"source": [
|
||||
"### Split data into train and test sets\n",
|
||||
"\n",
|
||||
"Now you split the data into training and test sets using the `train_test_split` function in the `sklearn` library. This function segregates the data into the x (features) data set for model training and the y (values to predict) data set for testing. The `test_size` parameter determines the percentage of data to allocate to testing. The `random_state` parameter sets a seed to the random generator, so that your train-test splits are always deterministic."
|
||||
"Now you split the data into training and test sets by using the `train_test_split` function in the `sklearn` library. This function segregates the data into the x, **features**, dataset for model training and the y, **values to predict**, dataset for testing. The `test_size` parameter determines the percentage of data to allocate to testing. The `random_state` parameter sets a seed to the random generator, so that your train-test splits are always deterministic:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -166,28 +189,28 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You now have the necessary packages and data ready for auto training for your model. \n",
|
||||
"The purpose of this step is to have data points to test the finished model that haven't been used to train the model, in order to measure true accuracy. In other words, a well-trained model should be able to accurately make predictions from data it hasn't already seen. You now have the necessary packages and data ready for autotraining your model.\n",
|
||||
"\n",
|
||||
"## Automatically train a model\n",
|
||||
"\n",
|
||||
"To automatically train a model:\n",
|
||||
"1. Define settings for the experiment run\n",
|
||||
"1. Submit the experiment for model tuning\n",
|
||||
"To automatically train a model, take the following steps:\n",
|
||||
"1. Define settings for the experiment run. Attach your training data to the configuration, and modify settings that control the training process.\n",
|
||||
"1. Submit the experiment for model tuning. After submitting the experiment, the process iterates through different machine learning algorithms and hyperparameter settings, adhering to your defined constraints. It chooses the best-fit model by optimizing an accuracy metric.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Define settings for autogeneration and tuning\n",
|
||||
"\n",
|
||||
"Define the experiment parameters and models settings for autogeneration and tuning. View the full list of [settings](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train).\n",
|
||||
"Define the experiment parameters and models settings for autogeneration and tuning. View the full list of [settings](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train). Submitting the experiment with these default settings will take approximately 10-15 min, but if you want a shorter run time, reduce either `iterations` or `iteration_timeout_minutes`.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"|Property| Value in this tutorial |Description|\n",
|
||||
"|----|----|---|\n",
|
||||
"|**iteration_timeout_minutes**|10|Time limit in minutes for each iteration|\n",
|
||||
"|**iterations**|30|Number of iterations. In each iteration, the model trains with the data with a specific pipeline|\n",
|
||||
"|**primary_metric**|spearman_correlation | Metric that you want to optimize.|\n",
|
||||
"|**preprocess**| True | True enables experiment to perform preprocessing on the input.|\n",
|
||||
"|**iteration_timeout_minutes**|10|Time limit in minutes for each iteration. Reduce this value to decrease total runtime.|\n",
|
||||
"|**iterations**|30|Number of iterations. In each iteration, a new machine learning model is trained with your data. This is the primary value that affects total run time.|\n",
|
||||
"|**primary_metric**|spearman_correlation | Metric that you want to optimize. The best-fit model will be chosen based on this metric.|\n",
|
||||
"|**preprocess**| True | By using **True**, the experiment can preprocess the input data (handling missing data, converting text to numeric, etc.)|\n",
|
||||
"|**verbosity**| logging.INFO | Controls the level of logging.|\n",
|
||||
"|**n_cross_validationss**|5|Number of cross validation splits\n"
|
||||
"|**n_cross_validationss**|5| Number of cross-validation splits to perform when validation data is not specified.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -206,6 +229,13 @@
|
||||
"}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Use your defined training settings as a parameter to an `AutoMLConfig` object. Additionally, specify your training data and the type of model, which is `regression` in this case."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
@@ -233,7 +263,7 @@
|
||||
"source": [
|
||||
"### Train the automatic regression model\n",
|
||||
"\n",
|
||||
"Start the experiment to run locally. Pass the defined `automated_ml_config` object to the experiment, and set the output to `true` to view progress during the experiment."
|
||||
"Start the experiment to run locally. Pass the defined `automated_ml_config` object to the experiment. Set the output to `True` to view progress during the experiment:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -252,6 +282,13 @@
|
||||
"local_run = experiment.submit(automated_ml_config, show_output=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The output shown updates live as the experiment runs. For each iteration, you see the model type, the run duration, and the training accuracy. The field `BEST` tracks the best running training score based on your metric type."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
@@ -262,7 +299,7 @@
|
||||
"\n",
|
||||
"### Option 1: Add a Jupyter widget to see results\n",
|
||||
"\n",
|
||||
"Use the Jupyter notebook widget to see a graph and a table of all results."
|
||||
"If you use a Jupyter notebook, use this Jupyter notebook widget to see a graph and a table of all results:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -285,7 +322,7 @@
|
||||
"source": [
|
||||
"### Option 2: Get and examine all run iterations in Python\n",
|
||||
"\n",
|
||||
"Alternatively, you can retrieve the history of each experiment and explore the individual metrics for each iteration run."
|
||||
"You can also retrieve the history of each experiment and explore the individual metrics for each iteration run. By examining RMSE (root_mean_squared_error) for each individual model run, you see that most iterations are predicting the taxi fair cost within a reasonable margin ($3-4).\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -316,7 +353,7 @@
|
||||
"source": [
|
||||
"## Retrieve the best model\n",
|
||||
"\n",
|
||||
"Select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best run and the fitted model for the last fit invocation. There are overloads on `get_output` that allow you to retrieve the best run and fitted model for any logged metric or a particular iteration."
|
||||
"Select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best run and the fitted model for the last fit invocation. By using the overloads on `get_output`, you can retrieve the best run and fitted model for any logged metric or a particular iteration:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -330,34 +367,13 @@
|
||||
"print(fitted_model)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Register the model\n",
|
||||
"\n",
|
||||
"Register the model in your Azure Machine Learning Workspace."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"description = 'Automated Machine Learning Model'\n",
|
||||
"tags = None\n",
|
||||
"local_run.register_model(description=description, tags=tags)\n",
|
||||
"print(local_run.model_id) # Use this id to deploy the model as a web service in Azure"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Test the best model accuracy\n",
|
||||
"\n",
|
||||
"Use the best model to run predictions on the test data set. The function `predict` uses the best model, and predicts the values of y (trip cost) from the `x_test` data set. Print the first 10 predicted cost values from `y_predict`."
|
||||
"Use the best model to run predictions on the test dataset to predict taxi fares. The function `predict` uses the best model and predicts the values of y, **trip cost**, from the `x_test` dataset. Print the first 10 predicted cost values from `y_predict`:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -374,7 +390,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Create a scatter plot to visualize the predicted cost values compared to the actual cost values. The following code uses the `distance` feature as the x-axis, and trip `cost` as the y-axis. The first 100 predicted and actual cost values are created as separate series, in order to compare the variance of predicted cost at each trip distance value. Examining the plot shows that the distance/cost relationship is nearly linear, and the predicted cost values are in most cases very close to the actual cost values for the same trip distance."
|
||||
"Create a scatter plot to visualize the predicted cost values compared to the actual cost values. The following code uses the `distance` feature as the x-axis and trip `cost` as the y-axis. To compare the variance of predicted cost at each trip distance value, the first 100 predicted and actual cost values are created as separate series. Examining the plot shows that the distance/cost relationship is nearly linear, and the predicted cost values are in most cases very close to the actual cost values for the same trip distance."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -407,7 +423,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Calculate the `root mean squared error` of the results. Use the `y_test` dataframe, and convert it to a list to compare to the predicted values. The function `mean_squared_error` takes two arrays of values, and calculates the average squared error between them. Taking the square root of the result gives an error in the same units as the y variable (cost), and indicates roughly how far your predictions are from the actual value. "
|
||||
" Calculate the `root mean squared error` of the results. Use the `y_test` dataframe. Convert it to a list to compare to the predicted values. The function `mean_squared_error` takes two arrays of values and calculates the average squared error between them. Taking the square root of the result gives an error in the same units as the y variable, **cost**. It indicates roughly how far the taxi fare predictions are from the actual fares:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -427,7 +443,7 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Run the following code to calculate MAPE (mean absolute percent error) using the full `y_actual` and `y_predict` data sets. This metric calculates an absolute difference between each predicted and actual value, sums all the differences, and then expresses that sum as a percent of the total of the actual values."
|
||||
"Run the following code to calculate mean absolute percent error (MAPE) by using the full `y_actual` and `y_predict` datasets. This metric calculates an absolute difference between each predicted and actual value and sums all the differences. Then it expresses that sum as a percent of the total of the actual values:"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -454,21 +470,46 @@
|
||||
"print(1 - mean_abs_percent_error)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"From the final prediction accuracy metrics, you see that the model is fairly good at predicting taxi fares from the data set's features, typically within +- $3.00. The traditional machine learning model development process is highly resource-intensive, and requires significant domain knowledge and time investment to run and compare the results of dozens of models. Using automated machine learning is a great way to rapidly test many different models for your scenario."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Clean up resources\n",
|
||||
"\n",
|
||||
">The resources you created can be used as prerequisites to other Azure Machine Learning service tutorials and how-to articles. \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"If you don't plan to use the resources you created, delete them, so you don't incur any charges:\n",
|
||||
"\n",
|
||||
"1. In the Azure portal, select **Resource groups** on the far left.\n",
|
||||
"\n",
|
||||
"1. From the list, select the resource group you created.\n",
|
||||
"\n",
|
||||
"1. Select **Delete resource group**.\n",
|
||||
"\n",
|
||||
"1. Enter the resource group name. Then select **Delete**."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Next steps\n",
|
||||
"\n",
|
||||
"In this automated machine learning tutorial, you:\n",
|
||||
"In this automated machine learning tutorial, you did the following tasks:\n",
|
||||
"\n",
|
||||
"* Configured a workspace and prepared data for an experiment.\n",
|
||||
"* Trained by using an automated regression model locally with custom parameters.\n",
|
||||
"* Explored and reviewed training results.\n",
|
||||
"\n",
|
||||
"> * Configured a workspace and prepared data for an experiment\n",
|
||||
"> * Trained using an automated regression model locally with custom parameters\n",
|
||||
"> * Explored and reviewed training results\n",
|
||||
"> * Registered the best model\n",
|
||||
"\n",
|
||||
"You can also try out the [image classification tutorial](img-classification-part1-training.ipynb)."
|
||||
"[Deploy your model](https://docs.microsoft.com/azure/machine-learning/service/tutorial-deploy-models-with-aml) with Azure Machine Learning."
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user