<jupyter_start><jupyter_text>03 - Registering a Model in your WorkspaceNow that we have trained a set of models and identified the run containing the best model, we want to deploy the model for inferencing.<jupyter_code>import environs

e_vars = environs.Env()
e_vars.read_env('../workshop.env')

USER_NAME = e_vars.str("USER_NAME")
EXPERIMENT_NAME = e_vars.str('EXPERIMENT_NAME')
ENVIRONMENT_NAME = e_vars.str("ENVIRONMENT_NAME")
DATASET_NAME = e_vars.str("DATASET_NAME")

SERVICE_NAME = e_vars.str("SERVICE_NAME")
MODEL_NAME = e_vars.str("MODEL_NAME")

if not USER_NAME:
    raise NotImplementedError("Please enter your username in the `.env` file and run this cell again.")
from azureml.core import Workspace, Experiment

ws = Workspace.from_config()
experiment = Experiment(ws, EXPERIMENT_NAME)<jupyter_output><empty_output><jupyter_text>Find the Best RunWe can use the SDK to search through our runs to determine which was the best run. In our case, we'll use RMSE to determine the best metric.<jupyter_code>from tqdm import tqdm

def find_best_run(experiment, metric, goal='minimize'):
     runs = {}
     run_metrics = {}
    
     # Create dictionaries containing the runs and the metrics for all runs containing the metric
     for r in tqdm(experiment.get_runs(include_children=True)):
         metrics = r.get_metrics()
         if metric in metrics.keys():
             runs[r.id] = r
             run_metrics[r.id] = metrics
            
     if goal == 'minimize':
         min_run = min(run_metrics, key=lambda k: run_metrics[k][metric])
         return runs[min_run]
     else:
         max_run = max(run_metrics, key=lambda k: run_metrics[k][metric])
         return runs[max_run]

best_run = find_best_run(experiment, 'rmse', 'minimize')

# Display the metrics
best_run.get_metrics()<jupyter_output><empty_output><jupyter_text>Register a model from best runWe have already identified which run contains the "best model" by our evaluation criteria.  Each run has a file structure associated with it that contains various files collected during the run.  Since a run can have many outputs we need to tell AML which file from those outputs represents the model that we want to use for our deployment.  We can use the `run.get_file_names()` method to list the files associated with the run, and then use the `run.register_model()` method to place the model in the workspace's model registry.When using `run.register_model()` we supply a `model_name` that is meaningful for our scenario and the `model_path` of the model relative to the run.  In this case, the model path is what is returned from `run.get_file_names()`<jupyter_code># View the files in the run
for f in best_run.get_file_names():
    if 'logs' not in f:
        print(f)
    
# Register the model with the workspace
model = best_run.register_model(model_name=MODEL_NAME, model_path='outputs/model.pkl')<jupyter_output><empty_output><jupyter_text>Once a model is registered, it is accessible from the list of models on the AML workspace.  If you register models with the same name multiple times, AML keeps a version history of those models for you.  The `Model.list()` lists all models in a workspace, and can be filtered by name, tags, or model properties.<jupyter_code># Find all models called "diabetes_regression_model" and display their version numbers
from azureml.core.model import Model

models = Model.list(ws, name=MODEL_NAME)
for m in models:
    print(m.name, m.version)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07903780068728522, 'fraction_numerical': 0.000572737686139748, 'mean_word_length': 4.483516483516484, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, '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': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '13033', 'license': 'MIT', 'n_tokens_mistral': 1055, 'n_tokens_neox': 1038, 'n_words': 395, 'path': 'src/03-deployment/03-Register-Model.ipynb', 'repo_name': 'ezwiefel/aml-workshop', 'size': '3492'}