Model Class

Represents the result of machine learning training.

A model is the result of a Azure Machine learning training Run or some other model training process outside of Azure. Regardless of how the model is produced, it can be registered in a workspace, where it is represented by a name and a version. With the Model class, you can package models for use with Docker and deploy them as a real-time endpoint that can be used for inference requests.

For an end-to-end tutorial showing how models are created, managed, and consumed, see Train image classification model with MNIST data and scikit-learn using Azure Machine Learning.

Model constructor.

The Model constructor is used to retrieve a cloud representation of a Model object associated with the provided workspace. Must provide either name or ID.

Inheritance
builtins.object
Model

Constructor

Model(workspace, name=None, id=None, tags=None, properties=None, version=None, run_id=None, model_framework=None, expand=True, **kwargs)

Parameters

Name Description
workspace
Required

The workspace object containing the model to retrieve.

name
str

The name of the model to retrieve. The latest model with the specified name is returned, if it exists.

Default value: None
id
str

The ID of the model to retrieve. The model with the specified ID is returned, if it exists.

Default value: None
tags

An optional list of tags used to filter returned results. Results are filtered based on the provided list, searching by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]

Default value: None
properties

An optional list of properties used to filter returned results. Results are filtered based on the provided list, searching by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]

Default value: None
version
int

The model version to return. When provided along with the name parameter, the specific version of the specified named model is returned, if it exists. If version is omitted, the lastest version of the model is returned.

Default value: None
run_id
str

Optional ID used to filter returned results.

Default value: None
model_framework
str

Optional framework name used to filter returned results. If specified, results are returned for the models matching the specified framework. See Framework for allowed values.

Default value: None
workspace
Required

The workspace object containing the model to retrieve.

name
Required
str

The name of the model to retrieve. The latest model with the specified name is returned, if it exists.

id
Required
str

The ID of the model to retrieve. The model with the specified ID is returned, if it exists.

tags
Required

An optional list of tags used to filter returned results. Results are filtered based on the provided list, searching by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]

properties
Required

An optional list of properties used to filter returned results. Results are filtered based on the provided list, searching by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]

version
Required
int

The model version to return. When provided along with the name parameter, the specific version of the specified named model is returned, if it exists. If version is omitted, the lastest version of the model is returned.

run_id
Required
str

Optional ID used to filter returned results.

model_framework
Required
str

Optional framework name used to filter returned results. If specified, results are returned for the models matching the specified framework. See Framework for allowed values.

expand

If true, will return models with all subproperties populated e.g. run, dataset, and experiment.

Default value: True

Remarks

The Model constructor is used to retrieve a cloud representation of a Model object associated with the specified workspace. At least the name or ID must be provided to retrieve models, but there are also other options for filtering including by tags, properties, version, run ID, and framework.


   from azureml.core.model import Model
   model = Model(ws, 'my_model_name')

The following sample shows how to fetch specific version of a model.


   from azureml.core.model import Model
   model = Model(ws, 'my_model_name', version=1)

Registering a model creates a logical container for the one or more files that make up your model. In addition to the content of the model file itself, a registered model also stores model metadata, including model description, tags, and framework information, that is useful when managing and deploying the model in your workspace. For example, with tags you can categorize your models and apply filters when listing models in your workspace. After registration, you can then download or deploy the registered model and receive all the files and metadata that were registered.

The following sample shows how to register a model specifying tags and a description.


   from azureml.core.model import Model

   model = Model.register(model_path="sklearn_regression_model.pkl",
                          model_name="sklearn_regression_model",
                          tags={'area': "diabetes", 'type': "regression"},
                          description="Ridge regression model to predict diabetes",
                          workspace=ws)

The following sample shows how to register a model specifying framework, input and output datasets, and resource configuration.


   import sklearn

   from azureml.core import Model
   from azureml.core.resource_configuration import ResourceConfiguration


   model = Model.register(workspace=ws,
                          model_name='my-sklearn-model',                # Name of the registered model in your workspace.
                          model_path='./sklearn_regression_model.pkl',  # Local file to upload and register as a model.
                          model_framework=Model.Framework.SCIKITLEARN,  # Framework used to create the model.
                          model_framework_version=sklearn.__version__,  # Version of scikit-learn used to create the model.
                          sample_input_dataset=input_dataset,
                          sample_output_dataset=output_dataset,
                          resource_configuration=ResourceConfiguration(cpu=1, memory_in_gb=0.5),
                          description='Ridge regression model to predict diabetes progression.',
                          tags={'area': 'diabetes', 'type': 'regression'})

   print('Name:', model.name)
   print('Version:', model.version)

The Variables section lists attributes of a local representation of the cloud Model object. These variables should be considered read-only. Changing their values will not be reflected in the corresponding cloud object.

Variables

Name Description
created_by

The user that created the Model.

created_time

When the Model was created.

azureml.core.Model.description

A description of the Model object.

azureml.core.Model.id

The Model ID. This takes the form of <model name>:<model version>.

mime_type
str

The Model mime type.

azureml.core.Model.name

The name of the Model.

model_framework
str

The framework of the Model.

model_framework_version
str

The framework version of the Model.

azureml.core.Model.tags

A dictionary of tags for the Model object.

azureml.core.Model.properties

Dictionary of key value properties for the Model. These properties cannot be changed after registration, however new key value pairs can be added.

unpack

Whether or not the Model needs to be unpacked (untarred) when pulled to a local context.

url
str

The url location of the Model.

azureml.core.Model.version

The version of the Model.

azureml.core.Model.workspace

The Workspace containing the Model.

azureml.core.Model.experiment_name

The name of the Experiment that created the Model.

azureml.core.Model.run_id

The ID of the Run that created the Model.

parent_id
str

The ID of the parent Model of the Model.

derived_model_ids

A list of Model IDs that have been derived from this Model.

resource_configuration

The ResourceConfiguration for this Model. Used for profiling.

Methods

add_dataset_references

Associate the provided datasets with this Model.

add_properties

Add key value pairs to the properties dictionary of this model.

add_tags

Add key value pairs to the tags dictionary of this model.

delete

Delete this model from its associated workspace.

deploy

Deploy a Webservice from zero or more Model objects.

The resulting Webservice is a real-time endpoint that can be used for inference requests. The Model deploy function is similar to the deploy function of the Webservice class, but does not register the models. Use the Model deploy function if you have model objects that are already registered.

deserialize

Convert a JSON object into a model object.

Conversion fails if the specified workspace is not the workspace the model is registered with.

download

Download the model to target directory of the local file system.

get_model_path

Return the path to model.

The function will search for the model in the following locations.

If version is None:

  1. Download from remote to cache (if workspace is provided)
  2. Load from cache azureml-models/$MODEL_NAME/$LATEST_VERSION/
  3. ./$MODEL_NAME

If version is not None:

  1. Load from cache azureml-models/$MODEL_NAME/$SPECIFIED_VERSION/
  2. Download from remote to cache (if workspace is provided)
get_sas_urls

Return a dictionary of key-value pairs containing filenames and corresponding SAS URLs.

list

Retrieve a list of all models associated with the provided workspace, with optional filters.

package

Create a model package in the form of a Docker image or Dockerfile build context.

print_configuration

Print the user configuration.

profile

Profiles the model to get resource requirement recommendations.

This is a long running operation that can take up to 25 min depending on the size of the dataset.

register

Register a model with the provided workspace.

remove_tags

Remove the specified keys from tags dictionary of this model.

serialize

Convert this Model into a json serialized dictionary.

update

Perform an in-place update of the model.

Existing values of specified parameters are replaced.

update_tags_properties

Perform an update of the tags and properties of the model.

add_dataset_references

Associate the provided datasets with this Model.

add_dataset_references(datasets)

Parameters

Name Description
datasets
Required
list[tuple(<xref:str :> (Dataset or DatasetSnapshot))]

A list of tuples representing a pairing of dataset purpose to Dataset object.

Exceptions

Type Description

add_properties

Add key value pairs to the properties dictionary of this model.

add_properties(properties)

Parameters

Name Description
properties
Required
dict(<xref:str : str>)

The dictionary of properties to add.

Exceptions

Type Description

add_tags

Add key value pairs to the tags dictionary of this model.

add_tags(tags)

Parameters

Name Description
tags
Required
dict(<xref:{str : str}>)

The dictionary of tags to add.

Exceptions

Type Description

delete

Delete this model from its associated workspace.

delete()

Exceptions

Type Description

deploy

Deploy a Webservice from zero or more Model objects.

The resulting Webservice is a real-time endpoint that can be used for inference requests. The Model deploy function is similar to the deploy function of the Webservice class, but does not register the models. Use the Model deploy function if you have model objects that are already registered.

static deploy(workspace, name, models, inference_config=None, deployment_config=None, deployment_target=None, overwrite=False, show_output=False)

Parameters

Name Description
workspace
Required

A Workspace object to associate the Webservice with.

name
Required
str

The name to give the deployed service. Must be unique to the workspace, only consist of lowercase letters, numbers, or dashes, start with a letter, and be between 3 and 32 characters long.

models
Required

A list of model objects. Can be an empty list.

inference_config

An InferenceConfig object used to determine required model properties.

Default value: None
deployment_config

A WebserviceDeploymentConfiguration used to configure the webservice. If one is not provided, an empty configuration object will be used based on the desired target.

Default value: None
deployment_target

A ComputeTarget to deploy the Webservice to. As Azure Container Instances has no associated ComputeTarget, leave this parameter as None to deploy to Azure Container Instances.

Default value: None
overwrite

Indicates whether to overwrite the existing service if a service with the specified name already exists.

Default value: False
show_output

Indicates whether to display the progress of service deployment.

Default value: False

Returns

Type Description

A Webservice object corresponding to the deployed webservice.

Exceptions

Type Description

deserialize

Convert a JSON object into a model object.

Conversion fails if the specified workspace is not the workspace the model is registered with.

static deserialize(workspace, model_payload)

Parameters

Name Description
workspace
Required

The workspace object the model is registered with.

model_payload
Required

A JSON object to convert to a Model object.

Returns

Type Description

The Model representation of the provided JSON object.

Exceptions

Type Description

download

Download the model to target directory of the local file system.

download(target_dir='.', exist_ok=False, exists_ok=None)

Parameters

Name Description
target_dir
str

The path to a directory in which to download the model. Defaults to "."

Default value: .
exist_ok

Indicates whether to replace downloaded dir/files if they exist. Defaults to False.

Default value: False
exists_ok

DEPRECATED. Use exist_ok.

Default value: None

Returns

Type Description
str

The path to file or folder of the model.

Exceptions

Type Description

get_model_path

Return the path to model.

The function will search for the model in the following locations.

If version is None:

  1. Download from remote to cache (if workspace is provided)
  2. Load from cache azureml-models/$MODEL_NAME/$LATEST_VERSION/
  3. ./$MODEL_NAME

If version is not None:

  1. Load from cache azureml-models/$MODEL_NAME/$SPECIFIED_VERSION/
  2. Download from remote to cache (if workspace is provided)
static get_model_path(model_name, version=None, _workspace=None)

Parameters

Name Description
model_name
Required
str

The name of the model to retrieve.

version
int

The version of the model to retrieve. Defaults to the latest version.

Default value: None
_workspace

The workspace to retrieve a model from. Can't use remotely. If not specified only local cache is searched.

Default value: None

Returns

Type Description
str

The path on disk to the model.

Exceptions

Type Description

get_sas_urls

Return a dictionary of key-value pairs containing filenames and corresponding SAS URLs.

get_sas_urls()

Returns

Type Description

Dictionary of key-value pairs containing filenames and corresponding SAS URLs

Exceptions

Type Description

list

Retrieve a list of all models associated with the provided workspace, with optional filters.

static list(workspace, name=None, tags=None, properties=None, run_id=None, latest=False, dataset_id=None, expand=True, page_count=255, model_framework=None)

Parameters

Name Description
workspace
Required

The workspace object to retrieve models from.

name
str

If provided, will only return models with the specified name, if any.

Default value: None
tags

Will filter based on the provided list, by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]

Default value: None
properties

Will filter based on the provided list, by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]

Default value: None
run_id
str

Will filter based on the provided run ID.

Default value: None
latest

If true, will only return models with the latest version.

Default value: False
dataset_id
str

Will filter based on the provided dataset ID.

Default value: None
expand

If true, will return models with all subproperties populated e.g. run, dataset, and experiment. Setting this to false should speed up list() method completion in case of many models.

Default value: True
page_count
int

The number of items to retrieve in a page. Currently support values up to 255. Defaults to 255.

Default value: 255
model_framework
str

If provided, will only return models with the specified framework, if any.

Default value: None

Returns

Type Description

A list of models, optionally filtered.

Exceptions

Type Description

package

Create a model package in the form of a Docker image or Dockerfile build context.

static package(workspace, models, inference_config=None, generate_dockerfile=False, image_name=None, image_label=None)

Parameters

Name Description
workspace
Required

The workspace in which to create the package.

models
Required

A list of Model objects to include in the package. Can be an empty list.

inference_config

An InferenceConfig object to configure the operation of the models. This must include an Environment object.

Default value: None
generate_dockerfile

Whether to create a Dockerfile that can be run locally instead of building an image.

Default value: False
image_name
str

When building an image, the name for the resulting image.

Default value: None
image_label
str

When building an image, the label for the resulting image.

Default value: None

Returns

Type Description

A ModelPackage object.

Exceptions

Type Description

print_configuration

Print the user configuration.

static print_configuration(models, inference_config, deployment_config, deployment_target)

Parameters

Name Description
models
Required

A list of model objects. Can be an empty list.

inference_config
Required

An InferenceConfig object used to determine required model properties.

deployment_config
Required

A WebserviceDeploymentConfiguration used to configure the webservice.

deployment_target
Required

A ComputeTarget to deploy the Webservice to.

Exceptions

Type Description

profile

Profiles the model to get resource requirement recommendations.

This is a long running operation that can take up to 25 min depending on the size of the dataset.

static profile(workspace, profile_name, models, inference_config, input_dataset, cpu=None, memory_in_gb=None, description=None)

Parameters

Name Description
workspace
Required

A Workspace object in which to profile the model.

profile_name
Required
str

The name of the profiling run.

models
Required

A list of model objects. Can be an empty list.

inference_config
Required

An InferenceConfig object used to determine required model properties.

input_dataset
Required

The input dataset for profiling. Input dataset should have a single column and sample inputs should be in string format.

cpu

The number of cpu cores to use on the largest test instance. Currently support values up to 3.5.

Default value: None
memory_in_gb

The amount of memory (in GB) to use on the largest test instance. Can be a decimal. Currently support values up to 15.0.

Default value: None
description
str

Description to be associated with the profiling run.

Default value: None

Returns

Type Description

Exceptions

Type Description
<xref:azureml.exceptions.WebserviceException>, <xref:azureml.exceptions.UserErrorException>

register

Register a model with the provided workspace.

static register(workspace, model_path, model_name, tags=None, properties=None, description=None, datasets=None, model_framework=None, model_framework_version=None, child_paths=None, sample_input_dataset=None, sample_output_dataset=None, resource_configuration=None)

Parameters

Name Description
workspace
Required

The workspace to register the model with.

model_path
Required
str

The path on the local file system where the model assets are located. This can be a direct pointer to a single file or folder. If pointing to a folder, the child_paths parameter can be used to specify individual files to bundle together as the Model object, as opposed to using the entire contents of the folder.

model_name
Required
str

The name to register the model with.

tags
dict(<xref:{str : str}>)

An optional dictionary of key value tags to assign to the model.

Default value: None
properties
dict(<xref:{str : str}>)

An optional dictionary of key value properties to assign to the model. These properties can't be changed after model creation, however new key value pairs can be added.

Default value: None
description
str

A text description of the model.

Default value: None
datasets

A list of tuples where the first element describes the dataset-model relationship and the second element is the dataset.

Default value: None
model_framework
str

The framework of the registered model. Using the system-supported constants from the Framework class allows for simplified deployment for some popular frameworks.

Default value: None
model_framework_version
str

The framework version of the registered model.

Default value: None
child_paths

If provided in conjunction with a model_path to a folder, only the specified files will be bundled into the Model object.

Default value: None
sample_input_dataset

Sample input dataset for the registered model.

Default value: None
sample_output_dataset

Sample output dataset for the registered model.

Default value: None
resource_configuration

A resource configuration to run the registered model.

Default value: None

Returns

Type Description

The registered model object.

Exceptions

Type Description

Remarks

In addition to the content of the model file itself, a registered model also stores model metadata, including model description, tags, and framework information, that is useful when managing and deploying the model in your workspace. For example, with tags you can categorize your models and apply filters when listing models in your workspace.

The following sample shows how to register a model specifying tags and a description.


   from azureml.core.model import Model

   model = Model.register(model_path="sklearn_regression_model.pkl",
                          model_name="sklearn_regression_model",
                          tags={'area': "diabetes", 'type': "regression"},
                          description="Ridge regression model to predict diabetes",
                          workspace=ws)

If you have a model that was produced as a result of an experiment run, you can register it from a run object directly without downloading it to a local file first. In order to do that use the register_model method as documented in the Run class.

remove_tags

Remove the specified keys from tags dictionary of this model.

remove_tags(tags)

Parameters

Name Description
tags
Required

The list of keys to remove

Exceptions

Type Description

serialize

Convert this Model into a json serialized dictionary.

serialize()

Returns

Type Description

The json representation of this Model

Exceptions

Type Description

update

Perform an in-place update of the model.

Existing values of specified parameters are replaced.

update(tags=None, description=None, sample_input_dataset=None, sample_output_dataset=None, resource_configuration=None)

Parameters

Name Description
tags
dict(<xref:{str : str}>)

A dictionary of tags to update the model with. These tags replace existing tags for the model.

Default value: None
description
str

The new description to use for the model. This name replaces the existing name.

Default value: None
sample_input_dataset

The sample input dataset to use for the registered model. This sample input dataset replaces the existing dataset.

Default value: None
sample_output_dataset

The sample output dataset to use for the registered model. This sample output dataset replaces the existing dataset.

Default value: None
resource_configuration

The resource configuration to use to run the registered model.

Default value: None

Exceptions

Type Description

update_tags_properties

Perform an update of the tags and properties of the model.

update_tags_properties(add_tags=None, remove_tags=None, add_properties=None)

Parameters

Name Description
add_tags
dict(<xref:{str : str}>)

A dictionary of tags to add.

Default value: None
remove_tags

A list of tag names to remove.

Default value: None
add_properties
dict(<xref:{str : str}>)

A dictionary of properties to add.

Default value: None

Exceptions

Type Description