刚刚在triu函数的Numpy 1.8.1中发现了一些意外行为。

import numpy as np
a = np.zeros((4, 4))
a[1:, 2] = np.inf
a
>>>array([[  0.,   0.,   0.,   0.],
          [ inf,   0.,   0.,   0.],
          [ inf,   0.,   0.,   0.],
          [ inf,   0.,   0.,   0.]])

np.triu(a)
>>>array([[  0.,   0.,   0.,   0.],
          [ nan,   0.,   0.,   0.],
          [ nan,   0.,   0.,   0.],
          [ nan,   0.,   0.,   0.]])

这种行为是否可取?或者我应该提交一份错误报告吗?
编辑
我在Numpy github页面上提出了一个issue

最佳答案

一。解释
你好像忽略了RuntimeWarning

>>> np.triu(a)
twodim_base.py:450: RuntimeWarning: invalid value encountered in multiply
  out = multiply((1 - tri(m.shape[0], m.shape[1], k - 1, dtype=m.dtype)), m)

source code for numpy.triu如下:
def triu(m, k=0):
    m = asanyarray(m)
    out = multiply((1 - tri(m.shape[0], m.shape[1], k - 1, dtype=m.dtype)), m)
    return out

这使用numpy.tri得到一个对角线下有一个,上面有零的数组,并从1中减去这个,得到一个对角线下有零,上面有一个的数组:
>>> 1 - np.tri(4, 4, -1)
array([[ 1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.],
       [ 0.,  0.,  1.,  1.],
       [ 0.,  0.,  0.,  1.]])

然后它将这个元素与原始数组相乘。因此,如果原始数组有inf,则结果有inf * 0,即NaN。
2。解决办法
使用numpy.tril_indices生成下三角的索引,并将所有这些项设置为零:
>>> a = np.ones((4, 4))
>>> a[1:, 0] = np.inf
>>> a
array([[  1.,   1.,   1.,   1.],
       [ inf,   1.,   1.,   1.],
       [ inf,   1.,   1.,   1.],
       [ inf,   1.,   1.,   1.]])
>>> a[np.tril_indices(4, -1)] = 0
>>> a
array([[ 1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.],
       [ 0.,  0.,  1.,  1.],
       [ 0.,  0.,  0.,  1.]])

(根据要对a执行的操作,您可能需要在将这些条目归零之前复制一份。)

关于python - 当对具有无限值的矩阵进行调用时,Numpy Triu会生成nan,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24678932/

10-14 18:21
查看更多