在创建割集连续分布时使用scipy的rv_连续方法

2024-06-30 15:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我从数据生成/估计的某些pdf计算E[f(x)]。在

文件中说:

Subclassing

New random variables can be defined by subclassing rv_continuous class and re-defining at least the _pdf or the _cdf method (normalized to location 0 and scale 1) which will be given clean arguments (in between a and b) and passing the argument check method.

If positive argument checking is not correct for your RV then you will also need to re-define the _argcheck method.

因此,我子类化并定义了\u pdf,但每当我尝试调用:

print my_continuous_rv.expect(lambda x: x)

西皮冲我大喊大叫:

AttributeError: 'your_continuous_rv' object has no attribute 'a'

这是有意义的,因为我猜它是在试图求出积分的下限,因为它也会打印出错误:

^{pr2}$

我尝试将属性self.a和self.b定义为(我认为这是定义rv的限制/间隔):

self.a = float("-inf")
self.b = float("inf")

然而,当我这么做的时候,它会抱怨说:

if N > self.numargs:
AttributeError: 'your_continuous_rv' object has no attribute 'numargs'

我不太确定numargs应该是什么,但是在检查了scipy在github上的代码后,发现有以下代码行:

if not hasattr(self, 'numargs'):
    # allows more general subclassing with *args
    self.numargs = len(shapes)

这就是我的函数要取的随机变量的形状。在

目前我只做了一个非常简单的随机变量,一个浮点数作为它的可能值。所以我决定将numargs硬编码为1。但这只会让夏比更大声地喊叫。在

因此,归根结底,我认为从文档中我不清楚当我对它进行子类化时我必须做些什么,因为我做了他们说的,重写了pdf,但在完成之后,它要求我输入self.a,我硬编码了它,然后它要求我输入numargs,在这一点上,我想我的结论是,我真的不知道他们要我如何子类,房车连续。有人知道吗?我可以从我想要拟合的数据中生成我想要的pdf,然后从pdf中得到期望值和类似的东西,我还需要在rv_continuous中初始化什么才能使它实际工作?在


Tags: andtheto数据selfreyour定义
2条回答

SciPy的rv_histogram方法允许您提供数据,它提供pdf、cdf和随机生成方法。在

由于历史原因,scipy发行版是实例,因此需要有子类的实例。例如:

>>> class MyRV(stats.rv_continuous):
...    def _pdf(self, x, k):
...      return k * np.exp(-k*x)
>>> my_rv = MyRV(name='exp', a=0.)     # instantiation

注意需要指定支持的限制:默认值是a=-inf和{}。在

^{pr2}$

一旦指定了_pdf,就有了一个工作的分发实例:

>>> my_rv.cdf(4, k=3)
0.99999385578764677
>>> my_rv.rvs(k=3, size=4)
array([ 0.37696127,  1.10192779,  0.02632473,  0.25516446])
>>> my_rv.expect(lambda x: 1, args=(2,))    # k=2 here
0.9999999999999999

相关问题 更多 >