2 条题解
-
0
NUMPY031 题解:忽略 NumPy 警告
题目
如何忽略所有 NumPy 警告(不推荐)?
解题思路
使用
np.seterr()或np.errstate()上下文管理器。代码
import numpy as np # 方法1:seterr defaults = np.seterr(all="ignore") Z = np.ones(1) / 0 _ = np.seterr(**defaults) # 方法2:errstate(推荐) with np.errstate(all="ignore"): Z = np.ones(1) / 0代码详解
方法1:seterr
np.seterr(all="ignore")—— 设置所有错误为忽略- 执行可能有警告的操作
np.seterr(**defaults)—— 恢复默认设置
方法2:errstate(推荐)
with np.errstate(all="ignore"): # 可能产生警告的代码- 自动管理警告状态
- 出作用域后自动恢复
警告类型
np.seterr(divide='ignore', # 除零 over='ignore', # 溢出 under='ignore', # 下溢 invalid='ignore') # 无效操作警告等级
np.seterr(all='warn') # 警告(默认) np.seterr(all='print') # 打印 np.seterr(all='raise') # 抛出异常 np.seterr(all='ignore') # 忽略为什么不推荐?
- 警告通常是代码问题的信号
- 忽略警告可能导致隐藏的 bug
- 建议使用
np.errstate精确控制
核心知识点
np.seterr()—— 设置错误处理方式np.errstate()—— 上下文管理器- 建议只在必要时忽略警告
- 1
信息
- ID
- 82
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- (无)
- 标签
- (无)
- 递交数
- 0
- 已通过
- 0
- 上传者