<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/parallel-run/tabular-dataset-inference-iris.png)  Using Azure Machine Learning Pipelines for Batch Inference for CSV FilesIn this notebook, we will demonstrate how to make predictions on large quantities of data asynchronously using the ML pipelines with Azure Machine Learning. Batch inference (or batch scoring) provides cost-effective inference, with unparalleled throughput for asynchronous applications. Batch prediction pipelines can scale to perform inference on terabytes of production data. Batch prediction is optimized for high throughput, fire-and-forget predictions for a large collection of data.> **Tip**If your system requires low-latency processing (to process a single document or small set of documents quickly), use [real-time scoring](https://docs.microsoft.com/azure/machine-learning/service/how-to-consume-web-service) instead of batch prediction.In this example we will take use a machine learning model already trained to predict different types of iris flowers and run that trained model on some of the data in a CSV file which has characteristics of different iris flowers.  However, the same example can be extended to manipulating data to any embarrassingly-parallel processing through a python script.The outline of this notebook is as follows:- Create a DataStore referencing the CSV files stored in a blob container.- Register the pretrained model into the model registry. - Use the registered model to do batch inference on the CSV files in the data blob container. PrerequisitesIf you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the configuration Notebook located at https://github.com/Azure/MachineLearningNotebooks first. This sets you up with a working config file that has information on your workspace, subscription id, etc.   Connect to workspaceCreate a workspace object from the existing workspace. Workspace.from_config() reads the file config.json and loads the details into an object named ws.<jupyter_code># Check core SDK version number
import azureml.core

print("SDK version:", azureml.core.VERSION)
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 compute resourceBy 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.> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.**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.**<jupyter_code>import os
from azureml.core.compute import AmlCompute, ComputeTarget

# choose a name for your cluster
compute_name = os.environ.get("AML_COMPUTE_CLUSTER_NAME", "cpu-cluster")
compute_min_nodes = os.environ.get("AML_COMPUTE_CLUSTER_MIN_NODES", 0)
compute_max_nodes = os.environ.get("AML_COMPUTE_CLUSTER_MAX_NODES", 4)

# This example uses CPU VM. For using GPU VM, set SKU to STANDARD_NC6
vm_size = os.environ.get("AML_COMPUTE_CLUSTER_SKU", "STANDARD_D2_V2")


if compute_name in ws.compute_targets:
    compute_target = ws.compute_targets[compute_name]
    if compute_target and type(compute_target) is AmlCompute:
        print('found compute target. just use it. ' + compute_name)
else:
    print('creating a new compute target...')
    provisioning_config = AmlCompute.provisioning_configuration(vm_size = vm_size,
                                                                min_nodes = compute_min_nodes, 
                                                                max_nodes = compute_max_nodes)

    # create the cluster
    compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)
    
    # can poll for a minimum number of nodes and for a specific timeout.
    # if no min node count is provided it will use the scale settings for the cluster
    compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)
    
     # For a more detailed view of current AmlCompute status, use get_status()
    print(compute_target.get_status().serialize())<jupyter_output><empty_output><jupyter_text>Create a datastore containing sample imagesThe input dataset used for this notebook is CSV data which has attributes of different iris flowers. We have created a public blob container `sampledata` on an account named `pipelinedata`, containing iris data set. In the next step, we create a datastore with the name `iris_datastore`, which points to this container. In the call to `register_azure_blob_container` below, setting the `overwrite` flag to `True` overwrites any datastore that was created previously with that name. This step can be changed to point to your blob container by providing your own `datastore_name`, `container_name`, and `account_name`.<jupyter_code>from azureml.core.datastore import Datastore

account_name = "pipelinedata"
datastore_name="iris_datastore_data"
container_name="sampledata"

iris_data = Datastore.register_azure_blob_container(ws, 
                      datastore_name=datastore_name, 
                      container_name= container_name, 
                      account_name=account_name, 
                      overwrite=True)<jupyter_output><empty_output><jupyter_text>Create a TabularDatasetA [TabularDataSet](https://docs.microsoft.com/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) references single or multiple files which contain data in a tabular structure (ie like CSV files) in your datastores or public urls. TabularDatasets provides you with the ability to download or mount the files to your compute. 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.You can use dataset objects as inputs. Register the datasets to the workspace if you want to reuse them later.<jupyter_code>from azureml.core.dataset import Dataset

iris_ds_name = 'iris_data'

path_on_datastore = iris_data.path('iris/')
input_iris_ds = Dataset.Tabular.from_delimited_files(path=path_on_datastore, validate=False)
named_iris_ds = input_iris_ds.as_named_input(iris_ds_name)<jupyter_output><empty_output><jupyter_text>Intermediate/Output DataIntermediate data (or output of a Step) is represented by [PipelineData](https://docs.microsoft.com/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinedata?view=azure-ml-py) object. PipelineData can be produced by one step and consumed in another step by providing the PipelineData object as an output of one step and the input of one or more steps.<jupyter_code>from azureml.pipeline.core import PipelineData

datastore = ws.get_default_datastore()
output_folder = PipelineData(name='inferences', datastore=datastore)<jupyter_output><empty_output><jupyter_text>Registering the Model with the WorkspaceGet the pretrained model from a publicly available Azure Blob container, then register it to use in your workspace<jupyter_code>model_container_name="iris-model"
model_datastore_name="iris_model_datastore"

model_datastore = Datastore.register_azure_blob_container(ws, 
                      datastore_name=model_datastore_name, 
                      container_name= model_container_name, 
                      account_name=account_name, 
                      overwrite=True)
from azureml.core.model import Model

model_datastore.download('iris_model.pkl')

# register downloaded model
model = Model.register(model_path = "iris_model.pkl/iris_model.pkl",
                       model_name = "iris-prs", # this is the name the model is registered as
                       tags = {'pretrained': "iris"},
                       workspace = ws)<jupyter_output><empty_output><jupyter_text>Using your model to make batch predictionsTo use the model to make batch predictions, you need an **entry script** and a list of **dependencies**: An entry scriptThis script accepts requests, scores the requests by using the model, and returns the results.- __init()__ - Typically this function loads the model into a global object. This function is run only once at the start of batch processing per worker node/process. init method can make use of following environment variables (ParallelRunStep input):    1.	AZUREML_BI_OUTPUT_PATH â€“ output folder path- __run(mini_batch)__ - The method to be parallelized. Each invocation will have one minibatch.__mini_batch__: Batch inference will invoke run method and pass either a list or Pandas DataFrame as an argument to the method. Each entry in min_batch will be - a filepath if input is a FileDataset, a Pandas DataFrame if input is a TabularDataset.__run__ method response: run() method should return a Pandas DataFrame or an array. For append_row output_action, these returned elements are appended into the common output file. For summary_only, the contents of the elements are ignored. For all output actions, each returned output element indicates one successful inference of input element in the input mini-batch.    User should make sure that enough data is included in inference result to map input to inference. Inference output will be written in output file and not guaranteed to be in order, user should use some key in the output to map it to input.     DependenciesHelper scripts or Python/Conda packages required to run the entry script. Print inferencing script<jupyter_code>scripts_folder = "Code"
script_file = "iris_score.py"

# peek at contents
with open(os.path.join(scripts_folder, script_file)) as inference_file:
    print(inference_file.read())<jupyter_output><empty_output><jupyter_text>Build and run the batch inference pipelineThe data, models, and compute resource are now available. Let's put all these together in a pipeline.   Specify the environment to run the scriptSpecify the conda dependencies for your script. This will allow us to install pip packages as well as configure the inference environment.* Always include **azureml-core** and **azureml-dataset-runtime\[fuse\]** in the pip package list to make ParallelRunStep run properly.* For TabularDataset, add **pandas** as `run(mini_batch)` uses `pandas.DataFrame` as mini_batch type.If you're using custom image (`batch_env.python.user_managed_dependencies = True`), you need to install the package to your image.<jupyter_code>from azureml.core import Environment
from azureml.core.runconfig import CondaDependencies

predict_conda_deps = CondaDependencies.create(pip_packages=["scikit-learn==0.20.3",
                                                            "azureml-core", "azureml-dataset-runtime[pandas,fuse]"])

predict_env = Environment(name="predict_environment")
predict_env.python.conda_dependencies = predict_conda_deps
predict_env.spark.precache_packages = False<jupyter_output><empty_output><jupyter_text>Create the configuration to wrap the inference script<jupyter_code>from azureml.pipeline.steps import ParallelRunStep, ParallelRunConfig

# In a real-world scenario, you'll want to shape your process per node and nodes to fit your problem domain.
parallel_run_config = ParallelRunConfig(
    source_directory=scripts_folder,
    entry_script=script_file,  # the user script to run against each input
    mini_batch_size='1KB',
    error_threshold=5,
    output_action='append_row',
    append_row_file_name="iris_outputs.txt",
    environment=predict_env,
    compute_target=compute_target, 
    node_count=2,
    run_invocation_timeout=600
)<jupyter_output><empty_output><jupyter_text>Create the pipeline stepCreate the pipeline step using the script, environment configuration, and parameters. Specify the compute target you already attached to your workspace as the target of execution of the script. We will use ParallelRunStep to create the pipeline step.<jupyter_code>distributed_csv_iris_step = ParallelRunStep(
    name='example-iris',
    inputs=[named_iris_ds],
    output=output_folder,
    parallel_run_config=parallel_run_config,
    arguments=['--model_name', 'iris-prs'],
    allow_reuse=False
)<jupyter_output><empty_output><jupyter_text>Run the pipelineAt this point you can run the pipeline and examine the output it produced. The Experiment object is used to track the run of the pipeline<jupyter_code>from azureml.core import Experiment
from azureml.pipeline.core import Pipeline

pipeline = Pipeline(workspace=ws, steps=[distributed_csv_iris_step])

pipeline_run = Experiment(ws, 'iris-prs').submit(pipeline)<jupyter_output><empty_output><jupyter_text>View progress of Pipeline runThe pipeline run status could be checked in Azure Machine Learning portal (https://ml.azure.com). The link to the pipeline run could be retrieved by inspecting the `pipeline_run` object.<jupyter_code># This will output information of the pipeline run, including the link to the details page of portal.
pipeline_run<jupyter_output><empty_output><jupyter_text>Optional: View detailed logs (streaming)<jupyter_code>## Wait the run for completion and show output log to console
pipeline_run.wait_for_completion(show_output=True)<jupyter_output><empty_output><jupyter_text>View ResultsIn the iris_score.py file above you can see that the Result with the prediction of the iris variety gets returned and then appended to the original input of the row from the csv file. These results are written to the DataStore specified in the PipelineData object as the output data, which in this case is called *inferences*. This contains the outputs from  all of the worker nodes used in the compute cluster. You can download this data to view the results ... below just filters to a random 20 rows<jupyter_code>import pandas as pd
import tempfile

prediction_run = pipeline_run.find_step_run(distributed_csv_iris_step.name)[0]
prediction_output = prediction_run.get_output_data(output_folder.name)

target_dir = tempfile.mkdtemp()
prediction_output.download(local_path=target_dir)
result_file = os.path.join(target_dir, prediction_output.path_on_datastore, parallel_run_config.append_row_file_name)

# cleanup output format
df = pd.read_csv(result_file, delimiter=" ", header=None)
df.columns = ["sepal.length", "sepal.width", "petal.length", "petal.width", "variety"]
print("Prediction has ", df.shape[0], " rows")

random_subset = df.sample(n=20)
random_subset.head(20)<jupyter_output><empty_output><jupyter_text>Cleanup compute resourcesFor re-occurring jobs, it may be wise to keep compute the compute resources and allow compute nodes to scale down to 0. However, since this is just a single run job, we are free to release the allocated compute resources.<jupyter_code># uncomment below and run if compute resources are no longer needed 
# compute_target.delete()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.06261545321358049, 'fraction_numerical': 0.0026753296388304986, 'mean_word_length': 4.926764816912042, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 63, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 11, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '27752', 'license': 'MIT', 'n_tokens_mistral': 4287, 'n_tokens_neox': 4157, 'n_words': 1645, 'path': 'how-to-use-azureml/machine-learning-pipelines/parallel-run/tabular-dataset-inference-iris.ipynb', 'repo_name': 'aydensutt/MachineLearningNotebooks', 'size': '15699'}