如何在不修改库代码的情况下屏蔽torchmetrics的UserWarning?
你遇到的警告内容如下:
/Users/dev/miniconda/envs/pytorch/lib/python3.10/site-packages/torchmetrics/utilities/prints.py:36:
UserWarning: Torchmetrics v0.9 introduced a new argument class
property calledfull_state_updatethat has not been set for this
class (SMAPE). The property determines ifupdateby default needs
access to the full metric state. If this is not the case, significant
speedups can be achieved and we recommend setting this toFalse. We
provide an checking functionfrom torchmetrics.utilities import check_forward_no_full_statethat can be used to check if thefull_state_update=True(old and potential slower behaviour, default
for now) or iffull_state_update=Falsecan be used safely.
你尝试用warnings上下文管理器屏蔽但无效,确实是因为torchmetrics通过自定义的_warn函数触发警告,普通的上下文过滤没覆盖到。下面给你两种不修改库代码的解决方法:
方法一:设置SMAPE的full_state_update属性(推荐)
这不仅能消除警告,还能按官方建议优化性能:
- 先检查是否可以安全设置为
False:
from torchmetrics import SMAPE from torchmetrics.utilities import check_forward_no_full_state # 运行后如果输出True,就可以安全启用快速模式 can_use_fast_mode = check_forward_no_full_state(SMAPE) print(can_use_fast_mode)
- 启用快速模式(二选一即可):
- 单个实例生效:
metric = SMAPE(full_state_update=False)- 所有SMAPE实例全局生效:
SMAPE.full_state_update = False
方法二:精准屏蔽该特定警告
如果不想修改metric参数,可以通过精准匹配警告的来源和内容来屏蔽:
import warnings # 只屏蔽来自torchmetrics.prints模块的这条特定SMAPE警告 warnings.filterwarnings( "ignore", message=r".*full_state_update that has not been set for this class \(SMAPE\).*", category=UserWarning, module=r"torchmetrics\.utilities\.prints" )
这种方式不会影响其他正常警告的输出。
内容的提问来源于stack exchange,提问作者chronosynclastic

