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.objectModel
Constructor
Model(workspace, name=None, id=None, tags=None, properties=None, version=None, run_id=None, model_framework=None, expand=True, **kwargs)
Parameters
- name
- str
The name of the model to retrieve. The latest model with the specified name is returned, if it exists.
- id
- str
The ID of the model to retrieve. The model with the specified ID is returned, if it exists.
- tags
- list
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
- list
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
- 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.
- 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.
- name
- str
The name of the model to retrieve. The latest model with the specified name is returned, if it exists.
- id
- str
The ID of the model to retrieve. The model with the specified ID is returned, if it exists.
- tags
- list
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
- list
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
- 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.
- 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.
- expand
- bool
If true, will return models with all subproperties populated e.g. run, dataset, and experiment.
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)
Full sample is available from https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb
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)
Full sample is available from https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.ipynb
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
- created_by
- dict
The user that created the Model.
- created_time
- datetime
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
- bool
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.
- resource_configuration
- ResourceConfiguration
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 |
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
If
|
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
- datasets
- list[tuple(<xref:str :> (Dataset or DatasetSnapshot))]
A list of tuples representing a pairing of dataset purpose to Dataset object.
Exceptions
add_properties
Add key value pairs to the properties dictionary of this model.
add_properties(properties)
Parameters
Exceptions
add_tags
Add key value pairs to the tags dictionary of this model.
add_tags(tags)
Parameters
Exceptions
delete
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
- 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.
- inference_config
- InferenceConfig
An InferenceConfig object used to determine required model properties.
- deployment_config
- WebserviceDeploymentConfiguration
A WebserviceDeploymentConfiguration used to configure the webservice. If one is not provided, an empty configuration object will be used based on the desired target.
- deployment_target
- ComputeTarget
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.
- overwrite
- bool
Indicates whether to overwrite the existing service if a service with the specified name already exists.
- show_output
- bool
Indicates whether to display the progress of service deployment.
Returns
A Webservice object corresponding to the deployed webservice.
Return type
Exceptions
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
Returns
The Model representation of the provided JSON object.
Return type
Exceptions
download
Download the model to target directory of the local file system.
download(target_dir='.', exist_ok=False, exists_ok=None)
Parameters
- target_dir
- str
The path to a directory in which to download the model. Defaults to "."
- exist_ok
- bool
Indicates whether to replace downloaded dir/files if they exist. Defaults to False.
Returns
The path to file or folder of the model.
Return type
Exceptions
get_model_path
Return the path to model.
The function will search for the model in the following locations.
If version
is None:
- Download from remote to cache (if workspace is provided)
- Load from cache azureml-models/$MODEL_NAME/$LATEST_VERSION/
- ./$MODEL_NAME
If version
is not None:
- Load from cache azureml-models/$MODEL_NAME/$SPECIFIED_VERSION/
- Download from remote to cache (if workspace is provided)
static get_model_path(model_name, version=None, _workspace=None)
Parameters
- version
- int
The version of the model to retrieve. Defaults to the latest version.
- _workspace
- Workspace
The workspace to retrieve a model from. Can't use remotely. If not specified only local cache is searched.
Returns
The path on disk to the model.
Return type
Exceptions
get_sas_urls
Return a dictionary of key-value pairs containing filenames and corresponding SAS URLs.
get_sas_urls()
Returns
Dictionary of key-value pairs containing filenames and corresponding SAS URLs
Return type
Exceptions
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
- tags
- list
Will filter based on the provided list, by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]
- properties
- list
Will filter based on the provided list, by either 'key' or '[key, value]'. Ex. ['key', ['key2', 'key2 value']]
- expand
- bool
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.
- page_count
- int
The number of items to retrieve in a page. Currently support values up to 255. Defaults to 255.
- model_framework
- str
If provided, will only return models with the specified framework, if any.
Returns
A list of models, optionally filtered.
Return type
Exceptions
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
A list of Model objects to include in the package. Can be an empty list.
- inference_config
- InferenceConfig
An InferenceConfig object to configure the operation of the models. This must include an Environment object.
- generate_dockerfile
- bool
Whether to create a Dockerfile that can be run locally instead of building an image.
Returns
A ModelPackage object.
Return type
Exceptions
print_configuration
Print the user configuration.
static print_configuration(models, inference_config, deployment_config, deployment_target)
Parameters
- inference_config
- InferenceConfig
An InferenceConfig object used to determine required model properties.
- deployment_config
- WebserviceDeploymentConfiguration
A WebserviceDeploymentConfiguration used to configure the webservice.
Exceptions
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
- inference_config
- InferenceConfig
An InferenceConfig object used to determine required model properties.
- input_dataset
- Dataset
The input dataset for profiling. Input dataset should have a single column and sample inputs should be in string format.
- cpu
- float
The number of cpu cores to use on the largest test instance. Currently support values up to 3.5.
- memory_in_gb
- float
The amount of memory (in GB) to use on the largest test instance. Can be a decimal. Currently support values up to 15.0.
Return type
Exceptions
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
- model_path
- 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.
- tags
- dict(<xref:{str : str}>)
An optional dictionary of key value tags to assign to the model.
- 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.
- datasets
- list[(str, AbstractDataset)]
A list of tuples where the first element describes the dataset-model relationship and the second element is the dataset.
- 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.
If provided in conjunction with a model_path
to a folder, only the specified
files will be bundled into the Model object.
- sample_input_dataset
- AbstractDataset
Sample input dataset for the registered model.
- sample_output_dataset
- AbstractDataset
Sample output dataset for the registered model.
- resource_configuration
- ResourceConfiguration
A resource configuration to run the registered model.
Returns
The registered model object.
Return type
Exceptions
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)
Full sample is available from https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb
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
Exceptions
serialize
Convert this Model into a json serialized dictionary.
serialize()
Returns
The json representation of this Model
Return type
Exceptions
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
- tags
- dict(<xref:{str : str}>)
A dictionary of tags to update the model with. These tags replace existing tags for the model.
- description
- str
The new description to use for the model. This name replaces the existing name.
- sample_input_dataset
- AbstractDataset
The sample input dataset to use for the registered model. This sample input dataset replaces the existing dataset.
- sample_output_dataset
- AbstractDataset
The sample output dataset to use for the registered model. This sample output dataset replaces the existing dataset.
- resource_configuration
- ResourceConfiguration
The resource configuration to use to run the registered model.
Exceptions
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
Exceptions
Feedback
Submit and view feedback for