Saltar al contenido

Lección 15 · Evaluation

Evaluate Machine Learning Models

Use mlflow.models.evaluate for classifiers and regressors, add your own metric, check quality thresholds before release and study results by group.

A single accuracy number hides a lot. MLflow can compute a set of evaluation results for a model on a dataset and attach them to a run, so every model is judged in the same way.

Two evaluation systems

MLflow has two:

  • mlflow.models.evaluate for classic models such as classifiers and regressors (this lesson).
  • mlflow.genai.evaluate for LLM apps and agents (next lesson).

They are not interchangeable, so check which one an example uses.

Evaluate a classifier

Python
import mlflow
from mlflow.models import infer_signature

eval_data = X_test.copy()
eval_data["label"] = y_test

with mlflow.start_run():
    info = mlflow.sklearn.log_model(
        model,
        name="model",
        signature=infer_signature(X_test, model.predict(X_test)),
    )
    result = mlflow.models.evaluate(
        info.model_uri,
        data=eval_data,
        targets="label",
        model_type="classifier",
    )

print(result.metrics)

For model_type="classifier", the documented results include metrics such as accuracy, precision, recall, F1, ROC AUC and log loss, plus items such as a confusion matrix. For "regressor", you get measures such as MAE, MSE, RMSE and R squared. Which items appear depends on your model and data.

Understand the confusion matrix

Do not treat these numbers as magic. This stand-in computes precision, recall and F1 from first principles with a tiny made-up example.

Python Stand-in: confusion matrix, precision and recall

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Accuracy looks decent, yet the model misses half of the positive cases. For rare events such as fraud, precision and recall tell you much more than accuracy.

Your own metric

You can add a metric with make_metric from mlflow.models and pass it through extra_metrics. Your evaluation function receives predictions, targets and the built-in metrics, and returns a MetricValue whose aggregate_results holds your numbers. Check the current docs for the exact signature before you write one. A business cost is a good example, because a missed fraud case may cost far more than a false alarm.

Python Stand-in: a business cost metric

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The costs are invented. Agree on real ones with the people who own the decision.

Quality gates

Since MLflow 2.18.0, threshold validation is a separate step:

Python
from mlflow.models import MetricThreshold

thresholds = {"f1_score": MetricThreshold(threshold=0.80, greater_is_better=True)}

mlflow.validate_evaluation_results(
    candidate_result=result,
    validation_thresholds=thresholds,
)

If a threshold fails, an exception is raised. In a pipeline, that stops the release. Metric names depend on the model type, so print result.metrics to find the right key.

Look at groups, not only totals

A good average can hide a group that the model serves badly, such as a region, a language or an age band. Split your evaluation data into meaningful groups, evaluate each one, and log the results. Small groups give noisy scores, so show the number of examples next to every score.

An evaluation is only as good as its data. If the test set is stale, tiny or leaked into training, a beautiful report means little. Keep it fixed, versioned and separate.

Regression models

For a number such as a price, you compare predictions with true values. Two common measures behave differently:

Measure Meaning Sensitive to large errors?
MAE Average size of the error Less
RMSE Square root of the average squared error More

If a single large mistake is very costly, watch RMSE. If you care about the typical error, MAE is easier to explain. Report both when you can, in the units of the target, so that people understand them.

Always compare with a baseline

A score means little on its own. Compare it with a simple baseline, for example predicting the most common class, or predicting the average value. If your complex model barely beats the baseline, the added complexity may not be worth it. Log the baseline as its own run in the same experiment, so it shows up in every comparison.

Thresholds for classifiers

Many classifiers produce a probability. A decision threshold turns it into a yes or no. Lowering the threshold usually catches more positive cases and raises more false alarms. Choose the threshold on validation data, based on the costs of each error type, and record it as a parameter. Changing the threshold after you look at the test results is another way of tuning on the test set.

Evaluate more than quality

Before release, consider measures such as:

  • Prediction time for one request and for a batch.
  • Memory use and model size.
  • Behavior with missing or unusual values.
  • Stability across data from different time periods.

Data from a later period is especially useful. If the model does much worse on newer data than on a random split, the world may be changing, or the random split may leak information from the future. For time-based problems, split by time.

Report for people

A table of numbers is not a decision. Add a short note to the run that says what was compared, which result passed, which groups are weak, and what you recommend. Reviewers who do not know the code can then take part in the decision, which matters whenever the model affects customers or employees.

Common mistakes

Do not include the target column, or a column derived from it, among the input features. This is called leakage. It produces excellent scores in evaluation and poor results in real use. If a score looks too good to be true, check how each feature is created and whether it would be available at prediction time.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Which function evaluates a classic classifier?

    mlflow.models.evaluate is the classic machine learning system.
  2. 2. What happens when a validation threshold fails?

    The failure raises an exception, which can stop a release pipeline.
  3. 3. Fraud is 1% of cases and a model predicts 'not fraud' for everything. What is true?

    It is right 99% of the time yet finds no fraud at all.

Summary

  • Use mlflow.models.evaluate for classic models.
  • Check precision, recall and business costs, not only accuracy.
  • Validate thresholds with validate_evaluation_results.
  • Evaluate by group and keep evaluation data fixed.

Next: Evaluate LLM Apps

Tu progreso se guarda en este navegador. No necesitas una cuenta.