我試圖根據一些數據創建發行版,然後從該發行版隨機抽取。下面是我有:在scipy中創建新的發行版
from scipy import stats
import numpy
def getDistribution(data):
kernel = stats.gaussian_kde(data)
class rv(stats.rv_continuous):
def _cdf(self, x):
return kernel.integrate_box_1d(-numpy.Inf, x)
return rv()
if __name__ == "__main__":
# pretend this is real data
data = numpy.concatenate((numpy.random.normal(2,5,100), numpy.random.normal(25,5,100)))
d = getDistribution(data)
print d.rvs(size=100) # this usually fails
我覺得這是做什麼我也想,但我經常得到一個錯誤(見下文),當我嘗試做d.rvs()
,並d.rvs(100)
永遠不會奏效。難道我做錯了什麼?有沒有更容易或更好的方法來做到這一點?如果這是一個scipy的bug,有什麼方法可以解決它嗎?
最後,是否有更多關於在某處創建自定義分發的文檔?我發現的最好的是scipy.stats.rv_continuous文檔,它非常簡潔並且沒有有用的例子。
回溯:
Traceback (most recent call last): File "testDistributions.py", line 19, in print d.rvs(size=100) File "/usr/local/lib/python2.6/dist-packages/scipy-0.10.0-py2.6-linux-x86_64.egg/scipy/stats/distributions.py", line 696, in rvs vals = self._rvs(*args) File "/usr/local/lib/python2.6/dist-packages/scipy-0.10.0-py2.6-linux-x86_64.egg/scipy/stats/distributions.py", line 1193, in _rvs Y = self._ppf(U,*args) File "/usr/local/lib/python2.6/dist-packages/scipy-0.10.0-py2.6-linux-x86_64.egg/scipy/stats/distributions.py", line 1212, in _ppf return self.vecfunc(q,*args) File "/usr/local/lib/python2.6/dist-packages/numpy-1.6.1-py2.6-linux-x86_64.egg/numpy/lib/function_base.py", line 1862, in call theout = self.thefunc(*newargs) File "/usr/local/lib/python2.6/dist-packages/scipy-0.10.0-py2.6-linux-x86_64.egg/scipy/stats/distributions.py", line 1158, in _ppf_single_call return optimize.brentq(self._ppf_to_solve, self.xa, self.xb, args=(q,)+args, xtol=self.xtol) File "/usr/local/lib/python2.6/dist-packages/scipy-0.10.0-py2.6-linux-x86_64.egg/scipy/optimize/zeros.py", line 366, in brentq r = _zeros._brentq(f,a,b,xtol,maxiter,args,full_output,disp) ValueError: f(a) and f(b) must have different signs
編輯
對於那些好奇的,依照下列答案的建議,這裏的代碼工作:
from scipy import stats
import numpy
def getDistribution(data):
kernel = stats.gaussian_kde(data)
class rv(stats.rv_continuous):
def _rvs(self, *x, **y):
# don't ask me why it's using self._size
# nor why I have to cast to int
return kernel.resample(int(self._size))
def _cdf(self, x):
return kernel.integrate_box_1d(-numpy.Inf, x)
def _pdf(self, x):
return kernel.evaluate(x)
return rv(name='kdedist', xa=-200, xb=200)
因此,當我們正在做上述調用'randoms = getDistribution(Mydata)'然後'randoms = randoms.rvs(size = 1000)'時,它會在類內執行三個'def'嗎?即計算pdf,整合它等? – ThePredator
我確實讓我的隨機數據遵循數據分佈,但我想平滑它,以便它不會嚴格遵循數據分佈。我一直在手動調整'kernel'中的帶寬來做到這一點。例如,我們如何指定PDF功能,然後使用PDF功能使用Metropolis Hastings創建隨機數。 – ThePredator