只是澄清一下这里发生了什么
np.ma.log
runs np.log
关于论点,但它捕获了警告:
In [26]: np.log([-1,0,1,2])
/usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in log
#!/usr/bin/python3
/usr/local/bin/ipython3:1: RuntimeWarning: invalid value encountered in log
#!/usr/bin/python3
Out[26]: array([ nan, -inf, 0. , 0.69314718])
它掩盖了nan
and -inf
价值观。显然将原始值复制到这些中data
slots:
In [27]: np.ma.log([-1,0,1,2])
Out[27]:
masked_array(data = [-- -- 0.0 0.6931471805599453],
mask = [ True True False False],
fill_value = 1e+20)
In [28]: _.data
Out[28]: array([-1. , 0. , 0. , 0.69314718])
(在 Py3 中运行;numpy 版本 1.13.1)
这种掩蔽行为并不是独一无二的ma.log
。这是由它的类决定的
In [41]: type(np.ma.log)
Out[41]: numpy.ma.core._MaskedUnaryOperation
In np.ma.core
它的定义是fill
and domain
属性:
log = _MaskedUnaryOperation(umath.log, 1.0,
_DomainGreater(0.0))
因此有效域(未屏蔽)>0:
In [47]: np.ma.log.domain([-1,0,1,2])
Out[47]: array([ True, True, False, False], dtype=bool)
该域掩码是or-ed
with
In [54]: ~np.isfinite(np.log([-1,0,1,2]))
...
Out[54]: array([ True, True, False, False], dtype=bool)
具有相同的值。
看起来我可以定义一个自定义log
不添加自己的域屏蔽:
In [58]: mylog = np.ma.core._MaskedUnaryOperation(np.core.umath.log)
In [59]: mylog([-1,0,1,2])
Out[59]:
masked_array(data = [ nan -inf 0. 0.69314718],
mask = False,
fill_value = 1e+20)
In [63]: np.ma.masked_array([-1,0,1,2],[1,0,0,0])
Out[63]:
masked_array(data = [-- 0 1 2],
mask = [ True False False False],
fill_value = 999999)
In [64]: np.ma.log(np.ma.masked_array([-1,0,1,2],[1,0,0,0]))
Out[64]:
masked_array(data = [-- -- 0.0 0.6931471805599453],
mask = [ True True False False],
fill_value = 1e+20)
In [65]: mylog(np.ma.masked_array([-1,0,1,2],[1,0,0,0]))
Out[65]:
masked_array(data = [-- -inf 0.0 0.6931471805599453],
mask = [ True False False False],
fill_value = 1e+20)