比较矩阵和NAN时,numpy.isclose中可能存在一个错误
考虑下一段代码:比较矩阵和NAN时,numpy.isclose中可能存在一个错误,numpy,matrix,nan,Numpy,Matrix,Nan,考虑下一段代码: In [90]: m1 = np.matrix([1,2,3], dtype=np.float32) In [91]: m2 = np.matrix([1,2,3], dtype=np.float32) In [92]: m3 = np.matrix([1,2,'nan'], dtype=np.float32) In [93]: np.isclose(m1, m2, equal_nan=True) Out[93]: matrix([[ True, True, True
In [90]: m1 = np.matrix([1,2,3], dtype=np.float32)
In [91]: m2 = np.matrix([1,2,3], dtype=np.float32)
In [92]: m3 = np.matrix([1,2,'nan'], dtype=np.float32)
In [93]: np.isclose(m1, m2, equal_nan=True)
Out[93]: matrix([[ True, True, True]], dtype=bool)
In [94]: np.isclose(m1, m3, equal_nan=True)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-94-5d2b979bc263> in <module>()
----> 1 np.isclose(m1, m3, equal_nan=True)
/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.pyc in isclose(a, b, rtol, atol, equal_nan)
2571 # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
2572 # lib.stride_tricks, though, so we can't import it here.
-> 2573 x = x * ones_like(cond)
2574 y = y * ones_like(cond)
2575 # Avoid subtraction with infinite/nan values...
/usr/local/lib/python2.7/dist-packages/numpy/matrixlib/defmatrix.pyc in __mul__(self, other)
341 if isinstance(other, (N.ndarray, list, tuple)) :
342 # This promotes 1-D vectors to row vectors
--> 343 return N.dot(self, asmatrix(other))
344 if isscalar(other) or not hasattr(other, '__rmul__') :
345 return N.dot(self, other)
ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
为什么np.isclose会失败?从文件上看,它似乎应该起作用
谢谢这个问题来自于
np.nan==np.nan
,它在浮点逻辑中是False
In [39]: np.nan == np.nan
Out[39]: False
The `equal_nan` parameter is to force two `nan` values to be considered as equal , not to consider any value to be equal to `nan`.
In [37]: np.isclose(m3,m3)
Out[37]: array([ True, True, False], dtype=bool)
In [38]: np.isclose(m3,m3,equal_nan=True)
Out[38]: array([ True, True, True], dtype=bool)
矩阵类型是罪魁祸首(适用于数组)。不知道如何将该类型的文档解释为输入!您使用的是什么np版本?对我来说,行np.isclose(m3,m3)导致ValueError:形状(1,3)和(1,3)未对齐:3(尺寸1)!=1(0)对不起。我看不出你在处理矩阵。正如在评论中所说的,问题是isclose只接受Ndarays。矩阵是一种准弃用结构。
In [39]: np.nan == np.nan
Out[39]: False
The `equal_nan` parameter is to force two `nan` values to be considered as equal , not to consider any value to be equal to `nan`.
In [37]: np.isclose(m3,m3)
Out[37]: array([ True, True, False], dtype=bool)
In [38]: np.isclose(m3,m3,equal_nan=True)
Out[38]: array([ True, True, True], dtype=bool)