gpt4 book ai didi

python - 创建自定义连续分布时使用 scipy rv_continuous 的方法

转载 作者:行者123 更新时间:2023-11-28 16:38:32 25 4
gpt4 key购买 nike

我正在尝试为我根据数据生成/估计的一些 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.

所以我对 _pdf 进行了子类化和定义,但每当我尝试调用时:

打印 my_continuous_rv.expect(lambda x: x)

scipy 对我大吼:

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

这是有道理的,因为我猜它试图找出积分的下限,因为它也打印在错误中:

lb = loc + self.a * scale

我尝试将属性 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 应该是什么,但是在 github 上检查了 scipy 的代码后,它看起来有这行代码:

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

我假设这是我的函数应该采用的随机变量的形状。

目前我只是在做一个非常简单的随机变量,它的可能值是一个 float 。所以我决定将 numargs 硬编码为 1。但这只会导致 scipy 的部分更加大喊大叫。

因此,归根结底,我认为从文档中我不清楚当我对它进行子类化时我必须做什么,因为我按照他们说的做了,以覆盖 _pdf 但在这样做之后它要求我自己.a,我对其进行了硬编码,然后它要求我提供 numargs,此时我想我得出的结论是我真的不知道他们希望我如何子类化 rv_continuous。有人知道吗?我已经可以从我想要拟合的数据中生成我想要的 pdf,然后只能从 pdf 中获得预期值和类似的东西,我还必须在 rv_continous 中初始化什么才能让它真正起作用?

最佳答案

由于历史原因,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=-infb=inf

>>> my_rv.a, my_rv.b
(0.0, inf)
>>> my_rv.numargs # gets figured out automagically
1

一旦你指定了,比如说,_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

关于python - 创建自定义连续分布时使用 scipy rv_continuous 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22854332/

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