使用np.testing断言二维数组失败时如何打印完整数组内容
问题说明
使用np.testing.assert_all_equal、np.testing.assert_almost_equal等NumPy内置断言校验数组匹配性时,报错输出里的二维数组0轴默认最多仅展示3个元素,剩余内容会被...截断,无法直接定位数组不匹配的具体位置。尝试通过np.set_printoptions(edgeitems=10)修改全局打印配置不会对该报错输出生效。
复现代码
import numpy as np x1 = np.expand_dims(np.arange(10), 1) x2 = np.expand_dims(np.arange(10), 1) x2[8] = 0 np.testing.assert_almost_equal(x1, x2)
默认报错输出
AssertionError: Arrays are not almost equal to 7 decimals Mismatched elements: 1 / 10 (10%) Max absolute difference: 8 Max relative difference: 0. x: array([[0], [1], [2],... y: array([[0], [1], [2],...
解决方案
np.set_printoptions配置不生效的核心原因是:NumPy的testing模块维护了独立的打印配置,不会读取全局打印参数设置。可以通过以下两种方式实现完整数组打印:
- 临时方案:调用断言函数时传入
verbose=True参数,会强制打印完整的数组内容,不做任何截断,适合单次调试场景:
np.testing.assert_almost_equal(x1, x2, verbose=True)
- 全局配置方案:直接修改
np.testing模块的打印规则,一次配置后所有后续断言失败都会按设置打印数组:
import numpy as np # 方案1:设置首尾展示的元素数量足够大,覆盖常用数组长度 np.testing.print_options(edgeitems=100) # 方案2:设置打印阈值为无穷大,彻底关闭所有数组截断逻辑 np.testing.print_options(threshold=np.inf)
配置完成后再运行断言,报错时就会输出完整的数组内容,可直接定位到不匹配的元素位置。
内容的提问来源于stack exchange,提问作者quant
相关产品推荐
相关产品推荐

