gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:29:27 24 4
gpt4 key购买 nike

我想检查是否有 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

最佳答案

您可以使用 isinstance定义自定义检查的内置函数:

from scipy.stats import poisson, norm, rv_discrete, rv_continuous

def is_discrete(dist):

if hasattr(dist, 'dist'):
return isinstance(dist.dist, rv_discrete)
else: return isinstance(dist, rv_discrete)

def is_continuous(dist):

if hasattr(dist, 'dist'):
return isinstance(dist.dist, rv_continuous)
else: return isinstance(dist, rv_continuous)


这将导致:

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()
dist_poisson = poisson(10)

is_discrete(dist_contin)
#False
is_continuous(dist_contin)
#True
is_discrete(dist_poisson)
#True
is_continuous(dist_poisson)
#False

关于python - 如何检查 scipy 分布是否离散?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61529345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com