Python程序數據溢出問題或出現 NAN 問題


【數據溢出問題】

overflow:溢出 

  • overflow:上溢
  • underflow:下溢 
數據溢出包括上溢和下溢。
上溢可以理解為:你想用一個int類型來保存一個非常非常大的數,而這個超出了int類型所能表示的最大的數的范圍。
下溢同理:你要用double來表示一個非常非常小的數,超出它所能表示的最小數時,就會發生數據溢出錯誤。
 

【如何避免Python程序下溢問題】

浮點數的下溢一般是由很多很小的數(如很多獨立同分布數據的概率相乘)的連乘造成的,連乘后的數值有時候會達到負幾十萬個指數級。
 
其中一個解決辦法是:對這個累乘的乘積 取自然對數,可以將連乘化為求和:
在對數中有:
 

 

這樣即可避免浮點數的下溢,但是要記得最后要 取回來(取對數)。
 
 
 
【老板給: Computing Log-Sum-Exp180711
  The "nan problem" is not due to the inference method but instead to a poor implementation of it. Since machines have limited precision, certain types of calculations involving many numbers in a different scale tend to underflow or overflow.
  If you have written the inference code by yourself, please make sure you are not doing products of probabilities to compute likelihoods, but instead, sum of logarithms. And even that, make sure your log-likelihood does not become -infinity (resulting in a "nan" value).
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM