Get started with Azure Machine Learning using the Python SDK

    This article will use the Azure Machine Learning SDK for Python 3 to create and implement the  Azure Machine Learning Service workspace . This workspace is the main building block in the cloud for experimenting, learning, and deploying machine learning models with Azure Machine Learning.




    You'll start by setting up your own Python environment and the Jupyter Notebook server. For information about starting without installation, see  Quick Start. Get started with Azure Machine Learning using the Azure portal .


    In this short tutorial, you:


    • Install the Python SDK
    • Create a workspace in your Azure subscription.
    • create a configuration file for the workspace that will be used later in other notebooks and scripts;
    • write down the code that will log the values ​​inside the workspace;
    • View the recorded values ​​in the work area.

    You create a workspace and its configuration file that can be used as necessary components for working with other manuals and articles with Machine Learning instructions. As with other Azure services, Azure Machine Learning has certain limits and quotas. Learn more about quotas and how to send requests for additional quotas.


    The following Azure resources are automatically added to the workspace if available in your area:



     Note


    The code in this article requires the Azure Machine Learning SDK 1.0.2 or later. The code has been tested with version 1.0.8.


    If you don’t have an Azure subscription yet, create a free Azure account before you get started. Try the  free or paid version of Azure Machine Learning Service .


    Install SDK


     Important!


    Skip this section if you are using the Virtual Machine to process and analyze Azure or Azure Databricks data.


    • Azure data processing and analysis virtual machines created after September 27, 2018 come with the Python SDK already installed.
    • In an Azure Databricks environment, complete the  Databricks installation steps instead .


    Before installing the SDK, it is recommended that you first create a Python sandbox. Although Miniconda is used in this article  , you can also use the fully installed Anaconda tool   or  Python virtualenv .


    Miniconda Installation


    Download and install Miniconda . Select Python 3.7 or later to install. Do not select Python 2.x.


    Creating a Python Sandbox


    1. Open a command prompt, and then create a conda environment called  myenv  and install Python 3.6. The Azure Machine Learning SDK will work with Python 3.5.2 or later, but the automatic machine learning components are not fully functional in Python 3.7.


      conda create -n myenv -y Python=3.6
    2. Activate the environment.


      conda activate myenv

    Install SDK


    1. In an activated conda environment, install the core components of the Azure Machine Learning SDK with Jupyter Notebook Features. Installation takes several minutes depending on the configuration of the computer.


       pip install --upgrade azureml-sdk[notebooks]
    2. Install the Jupyter Notebook server in a conda environment.


      conda install -y nb_conda
    3. To use this environment for Azure Machine Learning Tutorials, install the following packages.


      conda install -y cython matplotlib pandas
    4. To use this environment for Azure Machine Learning Tutorials, install automatic machine learning components.


      pip install --upgrade azureml-sdk[automl]

    Create workspace


    Create a workspace in a Jupyter Notebook using the Python SDK.


    1. Create the directory that you want to use for the quick start guide and tutorials, or navigate to it.

    2. To start the Jupyter Notebook, enter this command:


      jupyter notebook
    3. In a browser window, create a notebook using a standard kernel  Python 3.

    4. To view the SDK version, enter the following Python code in a notebook cell and execute it.


      import azureml.core
      print(azureml.core.VERSION)
    5. Find the value for the parameter   in the  list of subscriptions in the Azure portal . Use any subscription in which you are given the role of the owner or member.


      from azureml.core import Workspace
      ws = Workspace.create(name='myworkspace',
                            subscription_id='', 
                            resource_group='myresourcegroup',
                            create_resource_group=True,
                            location='eastus2' 
                           )

      When you run the code, you may be prompted to log in to your Azure account. When you log in, the authentication token will be cached locally.

    6. To view workspace information, such as the associated vault, container registry, and key vault, enter the following code.


      ws.get_details()


    Configuration file entry


    Save the workspace information in a configuration file in the current directory. This file is called  aml_config \ config.json .


    Этот файл конфигурации рабочей области упрощает дальнейшую загрузку этой же рабочей области. Вы можете загрузить ее с помощью других записных книжек и скриптов в том же каталоге или подкаталоге.


    # Create the configuration file.
    ws.write_config()
    # Use this code to load the workspace from 
    # other scripts and notebooks in this directory.
    # ws = Workspace.from_config()

    Этот вызов API write_config() позволяет создать файл конфигурации в текущем каталоге. Файл config.json содержит следующее:


    {
        "subscription_id": "",
        "resource_group": "myresourcegroup",
        "workspace_name": "myworkspace"
    }

    Используйте рабочую область


    Запустите код, использующий базовые интерфейсы API пакета SDK для отслеживания нескольких экспериментальных запусков.


    1. Создайте эксперимент в рабочей области.
    2. Введите одно значение в эксперимент.
    3. Введите список значений в эксперимент.

    from azureml.core import Experiment
    # Create a new experiment in your workspace.
    exp = Experiment(workspace=ws, name='myexp')
    # Start a run and start the logging service.
    run = exp.start_logging()
    # Log a single  number.
    run.log('my magic number', 42)
    # Log a list (Fibonacci numbers).
    run.log_list('my list', [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) 
    # Finish the run.
    run.complete()

    Просмотр зарегистрированных результатов


    После завершения выполнения сведения об экспериментальном запуске можно просмотреть на портале Azure. Чтобы вывести URL-адрес расположения с результатами последнего запуска, используйте следующий код.


    print(run.get_portal_url())

    Use the link to view the logged values ​​on the Azure portal in a browser.


    Registered Values ​​in the Azure Portal


    Resource Cleanup


     Important!


    Created resources can be used as essential components when working with other Azure Machine Learning guides.


    If you do not plan to use the resources created in this article, delete them so that there is no charge.


    ws.delete(delete_dependent_resources=True)

    Additional Information


    In this article, you created resources for experimenting and deploying models. In addition, you ran the code in a notebook and studied the execution log from this code in your workspace in the cloud.


    Guide Training Image Classification Models


    You can also learn  more advanced examples on GitHub .


    Also popular now: