<jupyter_start><jupyter_text>Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-how-to-use-estimatorstep.png)  How to use EstimatorStep in AML PipelineThis notebook shows how to use the EstimatorStep with Azure Machine Learning Pipelines. Estimator is a convenient object in Azure Machine Learning that wraps run configuration information to help simplify the tasks of specifying how a script is executed. Prerequisite:* Understand the [architecture and terms](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture) introduced by Azure Machine Learning* If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration notebook](https://aka.ms/pl-config) to:    * install the AML SDK    * create a workspace and its configuration file (`config.json`) Let's get started. First let's import some Python libraries.<jupyter_code>import azureml.core
# check core SDK version number
print("Azure ML SDK Version: ", azureml.core.VERSION)<jupyter_output><empty_output><jupyter_text>Initialize workspaceInitialize a [Workspace](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architectureworkspace) object from the existing workspace you created in the Prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored in `config.json`.<jupyter_code>from azureml.core import Workspace
ws = Workspace.from_config()
print('Workspace name: ' + ws.name, 
      'Azure region: ' + ws.location, 
      'Subscription id: ' + ws.subscription_id, 
      'Resource group: ' + ws.resource_group, sep = '\n')<jupyter_output><empty_output><jupyter_text>Create or Attach existing AmlComputeYou will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecturecompute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource. If we could not find the cluster with the given name, then we will create a new cluster here. We will create an `AmlCompute` cluster of `STANDARD_NC6` GPU VMs. This process is broken down into 3 steps:1. create the configuration (this step is local and only takes a second)2. create the cluster (this step will take about **20 seconds**)3. provision the VMs to bring the cluster to the initial size (of 1 in this case). This step will take about **3-5 minutes** and is providing only sparse output in the process. Please make sure to wait until the call returns before moving to the next cell<jupyter_code>from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException

# choose a name for your cluster
cluster_name = "cpu-cluster"

try:
    cpu_cluster = ComputeTarget(workspace=ws, name=cluster_name)
    print('Found existing compute target')
except ComputeTargetException:
    print('Creating a new compute target...')
    compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_NC6', max_nodes=4)

    # create the cluster
    cpu_cluster = ComputeTarget.create(ws, cluster_name, compute_config)

    # can poll for a minimum number of nodes and for a specific timeout. 
    # if no min node count is provided it uses the scale settings for the cluster
    cpu_cluster.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)

# use get_status() to get a detailed status for the current cluster. 
print(cpu_cluster.get_status().serialize())<jupyter_output><empty_output><jupyter_text>Now that you have created the compute target, let's see what the workspace's `compute_targets` property returns. You should now see one entry named 'cpu-cluster' of type `AmlCompute`.  Use a simple scriptWe have already created a simple "hello world" script. This is the script that we will submit through the estimator pattern. It prints a hello-world message, and if Azure ML SDK is installed, it will also logs an array of values ([Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)).  Build an Estimator objectEstimator by default will attempt to use Docker-based execution. You can also enable Docker and let estimator pick the default CPU image supplied by Azure ML for execution. You can target an AmlCompute cluster (or any other supported compute target types). You can also customize the conda environment by adding conda and/or pip packages.> Note: The arguments to the entry script used in the Estimator object should be specified as *list* using    'estimator_entry_script_arguments' parameter when instantiating EstimatorStep. Estimator object's parameter    'script_params' accepts a dictionary. However 'estimator_entry_script_arguments' parameter expects arguments as    a list.> Estimator object initialization involves specifying a list of DataReference objects in its 'inputs' parameter.    In Pipelines, a step can take another step's output or DataReferences as input. So when creating an EstimatorStep,    the parameters 'inputs' and 'outputs' need to be set explicitly and that will override 'inputs' parameter    specified in the Estimator object.   > The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `source_directory` for the step. This helps reduce the size of the snapshot created for the step (only the specific folder is snapshotted). Since changes in any files in the `source_directory` would trigger a re-upload of the snapshot, this helps keep the reuse of the step when there are no changes in the `source_directory` of the step.<jupyter_code>from azureml.core import Datastore
from azureml.data.data_reference import DataReference
from azureml.pipeline.core import PipelineData

def_blob_store = Datastore(ws, "workspaceblobstore")

input_data = DataReference(
    datastore=def_blob_store,
    data_reference_name="input_data",
    path_on_datastore="20newsgroups/20news.pkl")

output = PipelineData("output", datastore=def_blob_store)

source_directory = 'estimator_train'
from azureml.train.estimator import Estimator

est = Estimator(source_directory=source_directory, 
                compute_target=cpu_cluster, 
                entry_script='dummy_train.py', 
                conda_packages=['scikit-learn'])<jupyter_output><empty_output><jupyter_text>Create an EstimatorStep[EstimatorStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.estimator_step.estimatorstep?view=azure-ml-py) adds a step to run Estimator in a Pipeline.- **name:** Name of the step- **estimator:** Estimator object- **estimator_entry_script_arguments:** - **runconfig_pipeline_params:** Override runconfig properties at runtime using key-value pairs each with name of the runconfig property and PipelineParameter for that property- **inputs:** Inputs- **outputs:** Output is list of PipelineData- **compute_target:** Compute target to use - **allow_reuse:** Whether the step should reuse previous results when run with the same settings/inputs. If this is false, a new run will always be generated for this step during pipeline execution.- **version:** Optional version tag to denote a change in functionality for the step<jupyter_code>from azureml.pipeline.steps import EstimatorStep

est_step = EstimatorStep(name="Estimator_Train", 
                         estimator=est, 
                         estimator_entry_script_arguments=["--datadir", input_data, "--output", output],
                         runconfig_pipeline_params=None, 
                         inputs=[input_data], 
                         outputs=[output], 
                         compute_target=cpu_cluster)<jupyter_output><empty_output><jupyter_text>Build and Submit the Experiment<jupyter_code>from azureml.pipeline.core import Pipeline
from azureml.core import Experiment
pipeline = Pipeline(workspace=ws, steps=[est_step])
pipeline_run = Experiment(ws, 'Estimator_sample').submit(pipeline)<jupyter_output><empty_output><jupyter_text>View Run Details<jupyter_code>from azureml.widgets import RunDetails
RunDetails(pipeline_run).show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07384066587395957, 'fraction_numerical': 0.0038049940546967895, 'mean_word_length': 5.007857142857143, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 32, 'https://': 7, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '11635', 'license': 'MIT', 'n_tokens_mistral': 2304, 'n_tokens_neox': 2204, 'n_words': 848, 'path': 'how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-how-to-use-estimatorstep.ipynb', 'repo_name': 'skaarthik/MachineLearningNotebooks', 'size': '8410'}