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

参数优化循环中如何将模型警告信息存入DataFrame?

解决方案

可以通过Python的warnings模块捕获训练过程中的目标警告,同时收集每次迭代的参数、Gini值及警告信息,最终转换为你需要的DataFrame格式。具体实现代码如下:

import pandas as pd
import warnings
from your_module import modelABC  # 替换为modelABC实际所在的模块路径
from sklearn.exceptions import ConvergenceWarning  # 若modelABC属于其他库,请替换为对应库的ConvergenceWarning类

# 初始化结果存储列表
results = []

for i in range(10):
    order = i + 1
    gini_value = None
    note = ""
    
    # 捕获迭代过程中的警告
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")  # 确保所有警告都被捕获记录
        # 训练模型并获取Gini值
        model = modelABC(order=order).fit()
        gini_value = model.gini
        
        # 检查是否出现目标收敛警告
        if w:
            for warning in w:
                if issubclass(warning.category, ConvergenceWarning):
                    note = "ConvergenceWarning"
                    break
    
    # 转换Gini值为百分比格式,存入结果列表
    gini_percent = f"{int(gini_value * 100)}%"
    results.append({"i": order, "Gini": gini_percent, "Note": note})

# 转换为目标DataFrame
result_df = pd.DataFrame(results)
print(result_df)

关键细节说明:

  • warnings.catch_warnings(record=True)上下文管理器:负责捕获并临时存储当前迭代产生的所有警告。
  • warnings.simplefilter("always"):关闭默认的警告过滤规则,确保ConvergenceWarning这类可能被默认忽略的警告也能被捕获。
  • 警告类型判断:通过匹配警告的类别,精确记录目标收敛警告,避免误记其他无关警告。

内容的提问来源于stack exchange,提问作者TranCanNam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:53:13