- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-28-2025 10:31 AM
Looking at your error, the issue is that run_id is not defined when you try to use it.
The problem is in how you're getting the run ID from the MLflow run object.
Here are the correct ways to fix this:
Solution 1: Fix the run_id extraction
The issue is in your code where you have:
autolog_run = mlflow.last_active_run()
model_uri = "runs:{}/model".format(autolog_run.info.run_id) # This line has the error
The correct way:
import mlflow
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
# Set tracking URI
mlflow.set_tracking_uri("databricks")
mlflow.set_registry_uri("databricks-uc")
# Start MLflow run explicitly
with mlflow.start_run() as run:
# Train model
X, y = datasets.load_iris(return_X_y=True, as_frame=True)
clf = RandomForestClassifier(max_depth=7)
clf.fit(X, y)
# Log model
mlflow.sklearn.log_model(clf, "model")
# Get run_id from the active run
run_id = run.info.run_id
# Register model
model_uri = f"runs:/{run_id}/model"
mlflow.register_model(model_uri, "principal_analysts.nco.iris_model")
Solution 2: Use mlflow.active_run() instead
import mlflow
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
mlflow.set_tracking_uri("databricks")
mlflow.set_registry_uri("databricks-uc")
with mlflow.start_run():
# Train model
X, y = datasets.load_iris(return_X_y=True, as_frame=True)
clf = RandomForestClassifier(max_depth=7)
clf.fit(X, y)
# Log model
mlflow.sklearn.log_model(clf, "model")
# Get current active run
current_run = mlflow.active_run()
run_id = current_run.info.run_id
# Register model
model_uri = f"runs:/{run_id}/model"
mlflow.register_model(model_uri, "principal_analysts.nco.iris_model")
The Key Fix
The main issue in your original code was this line:
run_id = run.info.run_id # 'run' was not defined in this scope
They properly capture the run_id within the correct scope where the run object is available.
The error you're seeing suggests that either:
The run variable is not in scope when you try to access run.info.run_id
The run object is None or doesn't have the expected structure
Try Solution 1 first - it's the most straightforward and should resolve your issue.