In Python small floats tending to zero

荒凉一梦 提交于 2019-11-29 09:07:22
Muhammad Alkarouri

What you describe is a standard problem with the naive Bayes classifier. You can search for underflow with that to find the answer. or see here.

The short answer is it is standard to express all that in terms of logarithms. So rather than multiplying probabilities, you sum their logarithms.

You might want to look at other algorithms as well for classification.

Would it be possible to do your work in a logarithmic space? (For example, instead of storing 1e-320, just store -320, and use addition instead of multiplication)

Floating point numbers don't have infinite precision, which is why you saw the numbers turn to 0. Could you multiply all the probabilities by a large scalar, so that your numbers stay in a higher range? If you're only worried about max and not magnitude, you don't even need to bother dividing through at the end. Alternatively you could use an infinite precision decimal, like ikanobori suggests.

Take a look at Decimal from the stdlib.

from decimal import Decimal, getcontext

getcontext().prec = 320

Decimal(1) / Decimal(7)

I am not posting the results here as it is quite long.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!