首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:处理大数

Python:处理大数
EN

Stack Overflow用户
提问于 2018-12-17 01:53:24
回答 2查看 89关注 0票数 1

我需要计算困惑,我试着用

代码语言:javascript
复制
def get_perplexity(test_set, model):
    perplexity = 1
    n = 0
    for word in test_set:
        n += 1
        perplexity = perplexity * 1 / get_prob(model, word)
    perplexity = pow(perplexity, 1/float(n))
    return perplexity

经过一些步骤后,我的perplexity等于无穷大。我需要获取数字,作为pow(perplexity, 1/float(n))的最后一步

有没有像and result这样的乘法数字?

代码语言:javascript
复制
3.887311155784627e+243
8.311806360146177e+250
1.7707049372801292e+263
1.690802669602979e+271
3.843294667766984e+278
5.954424789834101e+290
8.859529887856071e+295
7.649470766862909e+306
EN

回答 2

Stack Overflow用户

发布于 2018-12-17 02:15:03

重复的乘法将导致一些棘手的数值不稳定,因为乘法的结果需要越来越多的位来表示。我建议您将其转换为日志空间,并使用求和而不是乘法:

代码语言:javascript
复制
import math

def get_perplexity(test_set, model):
    log_perplexity = 0
    n = 0
    for word in test_set:
        n += 1
        log_perplexity -= math.log(get_prob(model, word))
    log_perplexity /= float(n)
    return math.exp(log_perplexity)

这样,所有的对数都可以用标准的位数表示,而且不会出现数值膨胀和精度损失。此外,您还可以通过使用decimal模块引入任意精度:

代码语言:javascript
复制
import decimal

def get_perplexity(test_set, model):
    with decimal.localcontext() as ctx:
        ctx.prec = 100  # set as appropriate
        log_perplexity = decimal.Decimal(0)
        n = 0
        for word in test_set:
            n += 1
            log_perplexity -= decimal.Decimal(get_prob(model, word))).ln()
        log_perplexity /= float(n)
        return log_perplexity.exp()
票数 1
EN

Stack Overflow用户

发布于 2018-12-17 02:23:30

由于e+306只有10^306,因此可以将类分为两个部分

代码语言:javascript
复制
class BigPowerFloat:
    POWER_STEP = 10**100
    def __init__(self, input_value):
        self.value = float(input_value)
        self.power = 0

    def _move_to_power(self):
        while self.value > self.POWER_STEP:
            self.value = self.value / self.POWER_STEP
            self.power += self.POWER_STEP
        # you can add similar for negative values           


    def __mul__(self, other):
        self.value *= other
        self._move_to_power()

    # TODO other __calls for /, +, - ...

    def __str__(self):
        pass
        # make your cust to str
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53804937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档