use*_*251 1 python statistics distribution scipy
我目前正在建立一个神经科学实验.基本上,刺激每x秒(x = inter-trial interval)呈现3秒.我希望x相当短(mean = 2.5)和不可预测.
我的想法是从截断为1(下限)和10(上限)的指数分布中抽取随机样本.我希望得到有界的指数分布.预期平均值为2.5.我怎么能以有效的方式做到这一点?
CT *_*Zhu 10
有两种方法可以做到这一点:
第一种是生成指数分布的随机变量,然后将值限制为(1,10).
In [14]:
import matplotlib.pyplot as plt
import scipy.stats as ss
Lambda = 2.5 #expected mean of exponential distribution is lambda in Scipy's parameterization
Size = 1000
trc_ex_rv = ss.expon.rvs(scale=Lambda, size=Size)
trc_ex_rv = trc_ex_rv[(trc_ex_rv>1)&(trc_ex_rv<10)]
In [15]:
plt.hist(trc_ex_rv)
plt.xlim(0, 12)
Out[15]:
(0, 12)
Run Code Online (Sandbox Code Playgroud)

In [16]:
trc_ex_rv
Out[16]:
array([...]) #a lot of numbers
Run Code Online (Sandbox Code Playgroud)
当然,问题是你不会得到确切的随机数(由Size这里定义).
另一种方法是使用逆变换采样,您将获得指定的确切重复次数:
In [17]:
import numpy as np
def trunc_exp_rv(low, high, scale, size):
rnd_cdf = np.random.uniform(ss.expon.cdf(x=low, scale=scale),
ss.expon.cdf(x=high, scale=scale),
size=size)
return ss.expon.ppf(q=rnd_cdf, scale=scale)
In [18]:
plt.hist(trunc_exp_rv(1, 10, Lambda, Size))
plt.xlim(0, 12)
Out[18]:
(0, 12)
Run Code Online (Sandbox Code Playgroud)

如果您希望得到的有界分布具有给定值的预期平均值,比如说2.5,您需要求出得到预期均值的scale参数.
import scipy.optimize as so
def solve_for_l(low, high, ept_mean):
A = np.array([low, high])
return 1/so.fmin(lambda L: ((np.diff(np.exp(-A*L)*(A*L+1)/L)/np.diff(np.exp(-A*L)))-ept_mean)**2,
x0=0.5,
full_output=False, disp=False)
def F(low, high, ept_mean, size):
return trunc_exp_rv(low, high,
solve_for_l(low, high, ept_mean),
size)
rv_data = F(1, 10, 2.5, 1e5)
plt.hist(rv_data, bins=50)
plt.xlim(0, 12)
print rv_data.mean()
Run Code Online (Sandbox Code Playgroud)
结果:
2.50386617882
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
2118 次 |
| 最近记录: |