问题描述
from numpy import *
m = array([[1,0],
[2,3]])
我想计算元素级log2(m)
,但仅在m
不为0的地方.在这些地方,我希望为0.
I would like to compute the element-wise log2(m)
, but only in the places where m
is not 0. In those places, I would like to have 0 as a result.
我现在正在反对:
RuntimeWarning: divide by zero encountered in log2
尝试1:使用where
Try 1: using where
res = where(m != 0, log2(m), 0)
可以计算出正确的结果,但仍然会记录RuntimeWarning: divide by zero encountered in log2
.看起来(从语法上来说,这很明显),numpy仍然在完整矩阵上计算log2(m)
,然后才where
选择要保留的值.
which computes me the correct result, but I still get logged a RuntimeWarning: divide by zero encountered in log2
. It looks like (and syntactically it is quite obvious) numpy still computes log2(m)
on the full matrix and only afterwards where
picks the values to keep.
我想避免这个警告.
尝试2:使用口罩
from numpy import ma
res = ma.filled(log2(ma.masked_equal(m, 0)), 0)
确保掩盖零将阻止log2
应用于它们,不是吗?不幸的是:我们仍然得到RuntimeWarning: divide by zero encountered in log2
.
Sure masking away the zeros will prevent log2
to get applied to them, won't it? Unfortunately not: We still get RuntimeWarning: divide by zero encountered in log2
.
即使矩阵被遮罩,log2
似乎仍然适用于每个元素.
Even though the matrix is masked, log2
still seems to be applied to every element.
如何在不获取除数为零的警告的情况下有效地计算numpy数组的逐元素日志?
- 当然,我可以使用
seterr
暂时禁用这些警告的记录,但这看起来并不干净. - 并且确保双 for 循环将特别有助于处理0,但会降低numpy的效率.
- Of course I could temporarily disable the logging of these warnings using
seterr
, but that doesn't look like a clean solution. - And sure a double for loop would help with treating 0s specially, but defeats the efficiency of numpy.
有什么想法吗?
推荐答案
我们可以为此使用掩码数组:
We can use masked arrays for this:
>>> from numpy import *
>>> m = array([[1,0], [2,3]])
>>> x = ma.log(m)
>>> print x.filled(0)
[[ 0. 0. ]
[ 0.69314718 1.09861229]]
这篇关于numpy:取log(matrix)时有效避免0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!