猿问

如何检查 scipy 分布是否是离散的?

我想检查scipy分布是离散的还是连续的。无论对象是来自命名分发的冻结分发对象,还是自定义rv_discrete或rv_continuous分发的实例,测试都应该有效。


我的第一个想法是检查变量的类型,但这似乎与连续与离散并不完全对应。例如,这里有四个分布:


from scipy.stats import *

import numpy as np


dist_norm = norm(10, 2)

dist_poisson = poisson(10)


class continuous_gen(rv_continuous):

    def _pdf(self, x, *args):

        if x >= 0 and x <= 1:

            return 1

        else:

            return 0

dist_contin = continuous_gen()


xk = np.arange(7)

pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)

dist_discrete = rv_discrete(values=(xk, pk))

以下是它们的类型:


type(dist_norm)

Out[59]: scipy.stats._distn_infrastructure.rv_frozen

type(dist_poisson)

Out[60]: scipy.stats._distn_infrastructure.rv_frozen

type(dist_contin)

Out[61]: __main__.continuous_gen

type(dist_discrete)

Out[62]: scipy.stats._distn_infrastructure.rv_sample

现在我已经is_discrete()通过尝试访问该pmf()方法(只有离散分布具有)实现了一个功能,但我不确定这是否是最干净或最可靠的方法。有没有更好的办法?


def is_discrete(dist):

    try:

        _ = dist.pmf(0)

        return True

    except:

        return False


元芳怎么了
浏览 171回答 1
1回答

江户川乱折腾

您可以使用isinstance内置函数来定义自定义检查:from scipy.stats import poisson, norm, rv_discrete, rv_continuousdef is_discrete(dist):&nbsp; &nbsp; if hasattr(dist, 'dist'):&nbsp; &nbsp; &nbsp; &nbsp; return isinstance(dist.dist, rv_discrete)&nbsp; &nbsp; else: return isinstance(dist, rv_discrete)def is_continuous(dist):&nbsp; &nbsp; if hasattr(dist, 'dist'):&nbsp; &nbsp; &nbsp; &nbsp; return isinstance(dist.dist, rv_continuous)&nbsp; &nbsp; else: return isinstance(dist, rv_continuous)这将导致:class continuous_gen(rv_continuous):&nbsp; &nbsp; def _pdf(self, x, *args):&nbsp; &nbsp; &nbsp; &nbsp; if x >= 0 and x <= 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 1&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0dist_contin = continuous_gen()dist_poisson = poisson(10)is_discrete(dist_contin)#Falseis_continuous(dist_contin)#Trueis_discrete(dist_poisson)#Trueis_continuous(dist_poisson)#False
随时随地看视频慕课网APP

相关分类

Python
我要回答