You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MLflow报错AttributeError:无last_active_run属性,求解决方案

问题描述

运行MLflow官方sklearn_autolog示例时触发报错:AttributeError: module 'mlflow' has no attribute 'last_active_run'。已通过以下命令获取示例文件:

wget https://raw.githubusercontent.com/mlflow/mlflow/master/examples/sklearn_autolog/utils.py
wget https://raw.githubusercontent.com/mlflow/mlflow/master/examples/sklearn_autolog/pipeline.py

报错核心代码(pipeline.py)

run_id = mlflow.last_active_run().info.run_id

完整报错栈

INFO mlflow.utils.autologging_utils: Created MLflow autologging run with ID '8cc3f4e03b4e417b95a64f1a9a41be63', which will track hyperparameters, performance metrics, model artifacts, and lineage information for the current sklearn workflow
Traceback (most recent call last):
  File "/Users/taein/Desktop/mlflow/pipeline.py", line 33, in <module>
    main()
  File "/Users/taein/Desktop/mlflow/pipeline.py", line 23, in main
    run_id = mlflow.last_active_run().info.run_id
AttributeError: module 'mlflow' has no attribute 'last_active_run'
原因分析

mlflow.last_active_run()是MLflow 2.3.0版本才新增的API,本地安装的MLflow版本低于该版本时,会出现此属性不存在的兼容性错误。官方示例基于最新版MLflow编写,与旧版本不兼容。

解决方案

方案1:升级MLflow到最新版本

执行命令完成升级,即可直接运行原示例代码:

pip install --upgrade mlflow

方案2:修改代码适配旧版本MLflow

若无需升级,可将mlflow.last_active_run()替换为旧版本兼容的逻辑,修改pipeline.py中的对应代码:

修改后的完整pipeline.py

from pprint import pprint

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

import mlflow
from mlflow.tracking import MlflowClient
from utils import fetch_logged_data


def main():
    # enable autologging
    mlflow.sklearn.autolog()

    # prepare training data
    X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
    y = np.dot(X, np.array([1, 2])) + 3

    # train a model
    pipe = Pipeline([("scaler", StandardScaler()), ("lr", LinearRegression())])
    pipe.fit(X, y)
    
    # 替换last_active_run为兼容旧版本的逻辑
    run = mlflow.active_run()
    if run is None:
        # 兜底获取最新运行记录
        client = MlflowClient()
        run = client.search_runs(experiment_ids=["0"], order_by=["start_time DESC"], max_results=1)[0]
    run_id = run.info.run_id
    
    print("Logged data and model in run: {}".format(run_id))

    # show logged data
    for key, data in fetch_logged_data(run_id).items():
        print("\n---------- logged {} ----------".format(key))
        pprint(data)


if __name__ == "__main__":
    main()

内容的提问来源于stack exchange,提问作者Tae In Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 15:24:20