我正在尝试通过实现scipy.stats.rv_continuous来编写一个具有更易于使用的参数(true range、mu和sig)的scipy.stats.truncnorm版本。我提供了_argcheck、_get_support、_pdf和_rvs的代码,但得到了错误
_parse_args() missing 4 required positional arguments: 'a', 'b', 'mu', and 'sig'
我怀疑这与shapes或实现_parse_args有关,但不知道如何解决它(我见过How do you use scipy.stats.rv_continuous?)。
我使用的是scipy v1.5.2和Python 3.8.5。
代码:
from scipy.stats import *
import scipy.stats
class truncgauss_gen(rv_continuous):
''' a and b are bounds of true support
mu is mean
sig is std dev
'''
def _argcheck(self, a, b, sig): return (a < b) and (sig > 0)
def _get_support(self, a, b): return a, b
def _pdf(self, x, a, b, mu, sig): return scipy.stats.truncnorm.pdf(x, (a - mu) / sig, (b - mu) / sig, ac=mu, scale=sig)
def _rvs(self, a, b, mu, sig, size): return scipy.stats.truncnorm.rvs((a - mu) / sig, (b - mu) / sig, ac=mu, scale=sig, size=size)
truncgauss = truncgauss_gen(name='truncgauss', momtype=1)
if __name__ == '__main__':
print(scipy.__version__)
tg = truncgauss()
dat = tg.rvs(a=-5.1, b=10.07, mu=2.3, n=10)
print(dat)回溯:
1.5.2
Traceback (most recent call last):
File "testDistr.py", line 41, in <module>
tg = truncgauss()
File ".../opt/anaconda3/lib/python3.8/site-packages/scipy/stats/_distn_infrastructure.py", line 780, in __call__
return self.freeze(*args, **kwds)
File ".../opt/anaconda3/lib/python3.8/site-packages/scipy/stats/_distn_infrastructure.py", line 777, in freeze
return rv_frozen(self, *args, **kwds)
File ".../opt/anaconda3/lib/python3.8/site-packages/scipy/stats/_distn_infrastructure.py", line 424, in __init__
shapes, _, _ = self.dist._parse_args(*args, **kwds)
TypeError: _parse_args() missing 4 required positional arguments: 'a', 'b', 'mu', and 'sig'发布于 2021-07-16 04:04:33
不太确定问题是什么,但将所有变量传递给每个函数,如下所示似乎是可行的。
class truncG_gen(rv_continuous):
def _argcheck(self, a, b, mu, sig): return (a < b) and (sig > 0)
def _get_support(self, a, b, mu, sig): return a, b
def _pdf(self, x, a, b, mu, sig): return scipy.stats.truncnorm.pdf(x, (a - mu) / sig, (b - mu) / sig, loc=mu, scale=sig)
def _cdf(self, x, a, b, mu, sig): return scipy.stats.truncnorm.cdf(x, (a - mu) / sig, (b - mu) / sig, loc=mu, scale=sig)
def _rvs(self, a, b, mu, sig, size=None, random_state=None):
return scipy.stats.truncnorm.rvs((a - mu) / sig, (b - mu) / sig, loc=mu, scale=sig, size=size, random_state=random_state)
truncG = truncG_gen(name='truncG', momtype=1)
'''https://stackoverflow.com/questions/68335452
复制相似问题