Databricks Machine Learning Associate Question 101
Single answerYou are training a machine learning model and want to manually log metrics, artifacts, and the trained model to MLflow using a single run. Which of the following code snippets correctly logs these components to an MLflow run?
- A
mlflow.start_run(); mlflow.log_metric('accuracy', 0.95); mlflow.log_artifact('model_description.txt'); mlflow.sklearn.log_model(model, 'model'); mlflow.end_run()
- B
with mlflow.start_run(): mlflow.log_metric('accuracy', 0.95); mlflow.log_artifact('model_description.txt'); mlflow.sklearn.log_model(model, 'model')
- C
mlflow.start_run(): mlflow.log_metric('accuracy', 0.95); mlflow.log_artifact('model_description.txt'); mlflow.sklearn.log_model(model, 'model')
- D
mlflow.start_run(); mlflow.log_metric('accuracy', 0.95); mlflow.log_artifact('model_description.txt'); mlflow.sklearn.log_model(model, 'model')
Show answer and explanation
Correct answer: B
Explanation
The with mlflow.start_run() context manager is the recommended and simplest way to manage an MLflow run. It ensures that the run is properly started and ended, avoiding any potential issues with forgetting to end the run manually. Within the with block, you can log metrics, artifacts, and models to the MLflow tracking server. Other approaches either have syntax errors or require additional steps to manage the run lifecycle.
- A. Incorrect.
This option is invalid because
mlflow.end_run()is not required when using thewithstatement. Additionally, usingmlflow.start_run()without thewithstatement requires additional management of ending the run. - B. Correct.
This option is correct because it uses the
with mlflow.start_run()context manager, which automatically starts and ends the MLflow run. It correctly logs the metric, artifact, and model within the same run. - C. Incorrect.
This option is invalid because the syntax
mlflow.start_run():is incorrect. A colon cannot be used with a function call. - D. Incorrect.
This option is invalid because it does not use the
withstatement or callmlflow.end_run()to properly manage the lifecycle of the MLflow run.