RuntimeWarning: divide by zero encountered in log

前端 未结 5 1145
无人共我
无人共我 2020-12-02 01:25

I am using numpy.log10 to calculate the log of an array of probability values. There are some zeros in the array, and I am trying to get around it using

resu         


        
5条回答
  •  被撕碎了的回忆
    2020-12-02 01:57

    I solved this by finding the lowest non-zero number in the array and replacing all zeroes by a number lower than the lowest :p

    Resulting in a code that would look like:

    def replaceZeroes(data):
      min_nonzero = np.min(data[np.nonzero(data)])
      data[data == 0] = min_nonzero
      return data
    
     ...
    
    prob = replaceZeroes(prob)
    result = numpy.where(prob > 0.0000000001, numpy.log10(prob), -10)
    

    Note that all numbers get a tiny fraction added to them.

提交回复
热议问题