2017-10-17 143 views
1

比较矩阵时考虑下一段代码:在numpy.isclose一个可能的错误与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]], 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) 

比较它的工作如预期的NaN数组时:

In [95]: np.isclose(np.array(m1), np.array(m3), equal_nan=True) 
Out[95]: array([[ True, True, False]], dtype=bool) 

为什么NP。 isclose失败?从文档似乎它应该工作

感谢

+0

矩阵类型是罪魁祸首(适用于数组)。不知道如何解释关于该类型的文档作为输入! – sascha

回答

1

的问题来自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) 
+0

你使用的是什么np版本?对我来说,np.isclose(m3,m3)会导致ValueError:形状(1,3)和(1,3)没有对齐:3(dim 1)!= 1(dim 0) – user2717954

+1

对不起。我没有看到你用矩阵工作。就像在评论中说的那样,问题在于只接受宪法。矩阵是一个准弃用结构。 –