此無關超載_stats
錯誤。同樣的行爲可以簡單地通過
class CustomBeta(st.rv_continuous):
pass
dist = CustomBeta(4, 6)
print(dist.rvs()) # crashes
的documentation of rv_continuous
指出
New random variables can be defined by subclassing the rv_continuous class and re-defining at least the _pdf
or the _cdf
method.
您將需要提供這些方法中的至少一個來計算概率密度函數(PDF)或累積概率密度引起的函數(CDF)。
此外,
[ rv_continuous
] cannot be used directly as a distribution.
它的用法如下:
class CustomBetaGen(st.rv_continuous):
...
CustomBeta = CustomBetaGen(name='CustomBeta')
dist = CustomBeta(4, 6)
最後,rvs.()
似乎並不正確的Beta分佈工作,如果你不提供_rvs
方法。
將所有內容放在一起,在偷Beta分佈適當的方法:
from scipy.stats import beta
import scipy.stats as st
import numpy as np
class CustomBetaGen(st.rv_continuous):
def _cdf(self, x, a, b):
return beta.cdf(x, a, b)
def _pdf(self, x, a, b):
return beta.pdf(x, a, b)
def _rvs(self, a, b):
return beta.rvs(a, b)
def _stats(self, a, b):
# will add own code here
mn = a * 1.0/(a + b)
var = (a * b * 1.0)/(a + b + 1.0)/(a + b) ** 2.0
g1 = 2.0 * (b - a) * np.sqrt((1.0 + a + b)/(a * b))/(2 + a + b)
g2 = 6.0 * (a ** 3 + a ** 2 * (1 - 2 * b) + b ** 2 * (1 + b) - 2 * a * b * (2 + b))
g2 /= a * b * (a + b + 2) * (a + b + 3)
return mn, var, g1, g2
CustomBeta = CustomBetaGen(name='CustomBeta')
dist = beta(4, 6)
print(dist.rvs()) # works fine
print(dist.stats()) # (array(0.4), array(0.021818181818181816))
dist = CustomBeta(4, 6)
print(dist.rvs()) # works fine
print(dist.stats()) # (array(0.4), array(0.021818181818181816))
我得到這個錯誤,AttributeError的:「beta_gen」對象有沒有屬性「_size」 – n00b
@的n00b我也有這個奇怪的錯誤,但忘了在代碼中修復它。嘗試將'return beta._rvs(a,b)'改爲'return beta.rvs(a,b)'。 – kazemakase