tencent cloud

Tencent Cloud DataBuddy

Recording Training Metrics

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-10-09 16:14:14
AI 번역
In the DataBuddy data science module, training metric recording is based on the MLflow protocol. Parameters, metrics, and artifacts that you record by calling MLflow APIs in Notebook are automatically aggregated into the runs of the corresponding experiments for later viewing and comparison.
This document describes how to record these three types of information in Notebook through the MLflow API and view the recorded results on the experiment details page.

Prerequisites

Before you start recording, make sure:
You have created the target experiment (see Create an Experiment) and obtained the experiment ID or experiment name.
The current account has edit or management permissions on the experiment.
The MLflow client is installed in Notebook. The default DataBuddy environment has MLflow preinstalled, so no additional installation is required.
The three types of information that can be recorded in the MLflow protocol are: parameters, metrics, and artifacts. For the meaning and typical examples of each type, see What Is a Model Experiment > Key Concepts.

Recording Method Selection

DataBuddy supports two recording methods, which you can choose flexibly based on your scenario:
Method
Scenario
Automatic recording
Use mainstream frameworks such as sklearn / xgboost / lightgbm / pytorch / tensorflow without manually writing log_*. Parameters, metrics, and models are automatically captured during framework training.
Manual recording
Customize the training process; record metrics that are not captured by the framework by default, and fully control the timing and content of recording.

Automatic Recording

Call mlflow.autolog() before mlflow.start_run(). During framework training, parameters, metrics, models, and training datasets are automatically captured:
import mlflow
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

mlflow.set_experiment(experiment_id="3")
mlflow.autolog() # Automatic logging

with mlflow.start_run():
db = load_diabetes()
X_train, X_test, y_train, y_test = train_test_split(db.data, db.target)
rf = RandomForestRegressor(n_estimators=100, max_depth=6)
rf.fit(X_train, y_train)
# Parameters (n_estimators, max_depth), training metrics, and model artifacts are all automatically recorded.
Note:
Autologging is one of the recommended ways to register models: automatically recorded models carry a signature by default, which can be directly used for Catalog registration. A model signature is a mandatory prerequisite for model registration.

Manual Recording

1.Manual Recording Parameters

Call mlflow.log_param within the with mlflow.start_run() context:
import mlflow

with mlflow.start_run(run_name="manual_run"):
# Single parameter
mlflow.log_param("learning_rate", 0.01)
mlflow.log_param("batch_size", 64)
mlflow.log_param("optimizer", "Adam")

# Batch recording
mlflow.log_params({
"n_estimators": 100,
"max_depth": 6,
"max_features": 3,
})
Value Constraints:
key is a string, and its maximum length is specified by the MLflow protocol.
The value type can be a string, an integer, or a floating-point number.
A parameter with the same name can be recorded only once within a single Run. Duplicate recording will cause an error.

2.Manually Recording Metrics

Call mlflow.log_metric within the with mlflow.start_run() context. You can specify step to plot curves:
import mlflow

with mlflow.start_run(run_name="manual_run"):
# Single metric
mlflow.log_metric("accuracy", 0.92)
mlflow.log_metric("auc", 0.88)

# Record loss by epoch during training
for epoch in range(100):
loss = train_one_epoch(...)
mlflow.log_metric("loss", loss, step=epoch)

# Batch recording
mlflow.log_metrics({
"precision": 0.91,
"recall": 0.89,
"f1": 0.90,
})
Note:
The metric value type must be numeric (integer or floating-point).
The same key can be recorded multiple times and is organized into a time series by step, which is displayed as a line chart in the experiment details chart view.
System metrics such as CPU utilization, memory usage, network traffic, and disk IO are automatically collected by DataBuddy, eliminating the need for manual recording.

3.Manually Recording Artifacts

Artifacts include any files such as serialized models, logs, configurations, and images. Recording methods fall into two categories:
1. Record a generic artifact file.
import mlflow

with mlflow.start_run():
# Record a single file
mlflow.log_artifact("output/eval_report.html")

# Record to a subdirectory
mlflow.log_artifact("config/params.yaml", artifact_path="configs")

# Record an entire directory
mlflow.log_artifacts("output/figures", artifact_path="figures")
2. Record a model artifact.
Different ML frameworks use their corresponding log_model methods. Common examples:
# scikit-learn
mlflow.sklearn.log_model(
sk_model=model,
name="sklearn-model",
input_example=X_train, # Provide an input example to automatically generate a signature.
)

# PyTorch
mlflow.pytorch.log_model(model, "model")

# Custom Python model
mlflow.pyfunc.log_model(artifact_path="model", python_model=my_model)
Attention:
Models registered to the Catalog must carry a signature. It is recommended to pass input_example= when calling log_model so that MLflow can infer the signature automatically, or to explicitly construct a mlflow.models.signature.ModelSignature before the call. Models without a signature will be rejected during subsequent registration.
3. Register the model directly when recording.
You can use the registered_model_name= parameter to register the model to the Catalog synchronously when calling log_model. For the same model name, the first registration creates V1, and each subsequent registration automatically increments the version number by +1.
mlflow.sklearn.log_model(
sk_model=model,
name="sklearn-model",
input_example=X_train,
registered_model_name="my_catalog.my_schema.churn_model",
)
For detailed rules on model registration, see Model Version Management.

Complete Example

The following is an end-to-end example that demonstrates how to record parameters, metrics, and the model, and complete registration in a single training run:

import mlflow
import mlflow.sklearn
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

mlflow.set_experiment("regression_demo")

with mlflow.start_run() as run:
X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

params = {"max_depth": 2, "random_state": 42}
model = RandomForestRegressor(**params)
model.fit(X_train, y_train)

# Record parameters
mlflow.log_params(params)

# Record metrics
y_pred = model.predict(X_test)
mlflow.log_metrics({"mse": mean_squared_error(y_test, y_pred)})

# Record and register the model (synchronously register it to the Catalog)
mlflow.sklearn.log_model(
sk_model=model,
name="sklearn-model",
input_example=X_train,
registered_model_name="catalog_name.schema_name.model_name",
)

Parent-Child Runs and Hyperparameter Tuning

Nest a child Run within the context of a parent Run. This is commonly used in hyperparameter search scenarios:
import mlflow

with mlflow.start_run(run_name="Parent Run") as parent:
mlflow.log_param("model_type", "RandomForest")
for n in [50, 100, 200]:
with mlflow.start_run(run_name=f"n_estimators={n}", nested=True):
mlflow.log_param("n_estimators", n)
# ... Train and record metrics ...
The Run task list on the experiment details page displays parent Runs and their child Runs in a nested manner, making it easier to view them hierarchically.

Experiment Details

1. How to View Experiment Details

After recording is complete, go to the experiment details to view:
1.1 Go to Data Science > Model Experiments, and click the target experiment name to enter its details.
1.2 By default, all Runs are displayed in a list under Run Tasks.
1.3 Click a Run task name to enter the Run details, which contain the following 4 tabs:
Tab
Content.
Overview
Basic information about this run. Click to jump to the dataset, model, and code file pages. Edit tags and search parameter configurations and metrics.
Model Metrics
Display visualization charts of metrics recorded by log_metric (bar charts, line charts, and more).
System Metrics
System-level monitoring charts for CPU utilization, memory, network, disk, and more
Model Files
All artifact files of the current Run, with support for browsing, copying, and downloading.

2. Adding Custom Tags

On the Overview page, you can add custom key-value tags to the Run for classification and search.
How to do it: Enter a key-value pair in the Add Tag area. After you enter each pair, click Save, and the system automatically adds a new row. Click the delete button at the end of a row to remove that row.

3. Verifying Results

After recording is complete, you can confirm the recording result in the following ways:
In Overview, you can view all recorded parameters, metrics, and custom tags.
You can view the corresponding charts in Model Metrics and System Metrics.
In Model Files, you can view the recorded tree structure of artifact files.
If the model is registered synchronously, you can find the corresponding registered model in the Model Management list.

FAQs

What Should I Do If the Error "Parameter already logged" Occurs When mlflow.log_param Is Called?

A parameter with the same name can be recorded only once within a single Run. Check whether the code repeatedly records the same parameter in a loop. If you do need to record changing values by time step, use mlflow.log_metric(key, value, step=...) instead.

Why Does the Metric Curve Show Only One Point?

When step is not passed to mlflow.log_metric(key, value), values are accumulated in the order they are recorded by default. If it is called only once, the curve has only one point. Call log_metric(key, value, step=epoch) by epoch in the training loop to plot a complete curve.

What Should I Do If the Model Has No Signature When It Is Registered?

To register a model, the model must include a signature. Please:
1. Pass input_example= when calling log_model to let MLflow infer the signature automatically, or.
2. Explicitly construct mlflow.models.signature.ModelSignature and pass it through the signature= parameter, or.
3. Enable mlflow.autolog() to have the framework automatically log models with signatures.
If the model does not have a signature, it will not be recorded, and the Model Files section will not display the recorded model files.

What Should I Do If a Manually Started Run Remains in the Running State?

If the code exits abnormally without properly closing the Run, the Run status may remain stuck. It is recommended to always use the with mlflow.start_run() as run: context manager, which automatically calls mlflow.end_run() to close the Run even when an exception occurs.

References

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백